import React, { useState } from 'react';
import { logger } from '../utils/logger';
import { exportCurrentData } from '../utils/exportData';
import SystemMonitor from '../components/SystemMonitor';
import ExportButton from '../components/ExportButton';
import LoadingSpinner from '../components/LoadingSpinner';

const Settings: React.FC = () => {
  const [activeTab, setActiveTab] = useState<'monitoring' | 'logs' | 'export'>('monitoring');
  const [isExporting, setIsExporting] = useState(false);

  const handleExportLogs = async (format: 'csv' | 'json') => {
    setIsExporting(true);
    try {
      const logs = logger.exportLogs();
      const userActions = logger.exportUserActions();
      
      const exportData = {
        logs,
        userActions,
        exportTime: new Date().toISOString()
      };

      if (format === 'csv') {
        // CSV 형식으로 변환
        const csvContent = convertLogsToCSV(exportData);
        downloadFile(csvContent, `logs-${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.csv`, 'text/csv');
      } else {
        // JSON 형식으로 변환
        const jsonContent = JSON.stringify(exportData, null, 2);
        downloadFile(jsonContent, `logs-${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.json`, 'application/json');
      }
    } catch (error) {
      console.error('Failed to export logs:', error);
    } finally {
      setIsExporting(false);
    }
  };

  const convertLogsToCSV = (data: any) => {
    const headers = ['Timestamp', 'Level', 'Message', 'Component', 'Session ID'];
    const rows = [
      ...data.logs.map((log: any) => [
        log.timestamp,
        log.level,
        log.message,
        log.data?.component || '',
        log.sessionId
      ]),
      ...data.userActions.map((action: any) => [
        action.timestamp,
        'USER_ACTION',
        action.action,
        action.component,
        action.sessionId
      ])
    ];

    let csv = headers.join(',') + '\n';
    csv += rows.map(row => 
      row.map((cell: any) => 
        typeof cell === 'string' && cell.includes(',') 
          ? `"${cell}"` 
          : cell
      ).join(',')
    ).join('\n');

    return csv;
  };

  const downloadFile = (content: string, filename: string, mimeType: string) => {
    const blob = new Blob([content], { type: mimeType });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  const clearLogs = () => {
    if (window.confirm('모든 로그를 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.')) {
      logger.clearLogs();
      window.location.reload();
    }
  };

  const logStats = logger.getLogStats();

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">설정</h1>
      </div>

      {/* 탭 네비게이션 */}
      <div className="border-b border-gray-200 dark:border-gray-700">
        <nav className="-mb-px flex space-x-8">
          {[
            { id: 'monitoring', label: '시스템 모니터링', icon: '📊' },
            { id: 'logs', label: '로그 관리', icon: '📝' },
            { id: 'export', label: '데이터 내보내기', icon: '📤' }
          ].map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id as any)}
              className={`py-2 px-1 border-b-2 font-medium text-sm ${
                activeTab === tab.id
                  ? 'border-blue-500 text-blue-600 dark:text-blue-400'
                  : 'border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 hover:border-gray-300 dark:hover:border-gray-600'
              }`}
            >
              <span className="mr-2">{tab.icon}</span>
              {tab.label}
            </button>
          ))}
        </nav>
      </div>

      {/* 탭 컨텐츠 */}
      <div className="mt-6">
        {activeTab === 'monitoring' && (
          <div className="space-y-6">
            <SystemMonitor />
          </div>
        )}

        {activeTab === 'logs' && (
          <div className="space-y-6">
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6">
              <div className="flex justify-between items-center mb-4">
                <h3 className="text-lg font-medium text-gray-900 dark:text-white">로그 관리</h3>
                <div className="flex space-x-2">
                  <button
                    onClick={() => handleExportLogs('csv')}
                    disabled={isExporting}
                    className="inline-flex items-center px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50"
                  >
                    {isExporting ? <LoadingSpinner size="sm" /> : 'CSV 내보내기'}
                  </button>
                  <button
                    onClick={() => handleExportLogs('json')}
                    disabled={isExporting}
                    className="inline-flex items-center px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50"
                  >
                    {isExporting ? <LoadingSpinner size="sm" /> : 'JSON 내보내기'}
                  </button>
                  <button
                    onClick={clearLogs}
                    className="inline-flex items-center px-3 py-2 border border-red-300 dark:border-red-600 rounded-md shadow-sm text-sm font-medium text-red-700 dark:text-red-300 bg-white dark:bg-gray-800 hover:bg-red-50 dark:hover:bg-red-900 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
                  >
                    로그 삭제
                  </button>
                </div>
              </div>

              <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
                <div className="text-center">
                  <div className="text-2xl font-semibold text-gray-900 dark:text-white">
                    {logStats.total}
                  </div>
                  <div className="text-sm text-gray-600 dark:text-gray-400">전체 로그</div>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-semibold text-blue-600">
                    {logStats.byLevel.debug}
                  </div>
                  <div className="text-sm text-gray-600 dark:text-gray-400">Debug</div>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-semibold text-green-600">
                    {logStats.byLevel.info}
                  </div>
                  <div className="text-sm text-gray-600 dark:text-gray-400">Info</div>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-semibold text-yellow-600">
                    {logStats.byLevel.warn}
                  </div>
                  <div className="text-sm text-gray-600 dark:text-gray-400">Warning</div>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-semibold text-red-600">
                    {logStats.byLevel.error}
                  </div>
                  <div className="text-sm text-gray-600 dark:text-gray-400">Error</div>
                </div>
              </div>
            </div>
          </div>
        )}

        {activeTab === 'export' && (
          <div className="space-y-6">
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6">
              <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-4">데이터 내보내기</h3>
              <p className="text-gray-600 dark:text-gray-400 mb-4">
                센서 데이터와 로그를 다양한 형식으로 내보낼 수 있습니다.
              </p>
              
              <div className="space-y-4">
                <div>
                  <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-2">센서 데이터</h4>
                  <p className="text-sm text-gray-600 dark:text-gray-400 mb-2">
                    현재 페이지의 센서 데이터를 CSV 또는 JSON 형식으로 내보냅니다.
                  </p>
                  <ExportButton data={[]} />
                </div>
                
                <div className="border-t border-gray-200 dark:border-gray-700 pt-4">
                  <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-2">시스템 로그</h4>
                  <p className="text-sm text-gray-600 dark:text-gray-400 mb-2">
                    애플리케이션 로그와 사용자 행동 데이터를 내보냅니다.
                  </p>
                  <div className="flex space-x-2">
                    <button
                      onClick={() => handleExportLogs('csv')}
                      disabled={isExporting}
                      className="inline-flex items-center px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50"
                    >
                      {isExporting ? <LoadingSpinner size="sm" /> : '로그 CSV 내보내기'}
                    </button>
                    <button
                      onClick={() => handleExportLogs('json')}
                      disabled={isExporting}
                      className="inline-flex items-center px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50"
                    >
                      {isExporting ? <LoadingSpinner size="sm" /> : '로그 JSON 내보내기'}
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default Settings; 