import React, { useEffect, useState, useRef } from 'react';
import { getDevices, getHistory, SensorData, Device } from '../services/api';
import { formatSensorValue, getSensorPrecision } from '../utils/formatters';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import LoadingSpinner from '../components/LoadingSpinner';
import StatusIndicator from '../components/StatusIndicator';
import { ConnectionStatus } from '../hooks/useRealTimeData';

const History: React.FC = () => {
  const [devices, setDevices] = useState<Device[]>([]);
  const [selectedDevice, setSelectedDevice] = useState<Device | null>(null);
  const [historyData, setHistoryData] = useState<SensorData[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [lastUpdate, setLastUpdate] = useState<string>('');
  const [connectionStatus, setConnectionStatus] = useState<ConnectionStatus>('disconnected');
  const pollingRef = useRef<NodeJS.Timeout | null>(null);

  // 디바이스 목록 불러오기
  useEffect(() => {
    (async () => {
      try {
        setError(null);
        setConnectionStatus('connecting');
        const devs = await getDevices();
        setDevices(devs);
        if (devs.length > 0) {
          setSelectedDevice(devs[0]);
        }
        setConnectionStatus('connected');
      } catch (err) {
        setError('디바이스 목록을 불러오는 중 오류가 발생했습니다.');
        setConnectionStatus('error');
      }
    })();
  }, []);

  // 디바이스 변경 시 히스토리 불러오기
  useEffect(() => {
    if (selectedDevice) {
      fetchHistory(selectedDevice.device_id);
      startPolling(selectedDevice.device_id);
    }
    return () => {
      stopPolling();
    };
    // eslint-disable-next-line
  }, [selectedDevice]);

  // 폴링 시작
  const startPolling = (deviceId: string) => {
    stopPolling();
    console.log('🔄 히스토리 폴링 시작 - 디바이스:', deviceId);
    
    // 즉시 첫 번째 데이터 가져오기
    fetchHistory(deviceId);
    
    // 5초마다 폴링
    pollingRef.current = setInterval(() => {
      console.log('⏰ 히스토리 폴링 실행 - 디바이스:', deviceId);
      fetchHistory(deviceId);
    }, 5000);
  };

  // 폴링 중지
  const stopPolling = () => {
    if (pollingRef.current) {
      clearInterval(pollingRef.current);
      pollingRef.current = null;
      console.log('🛑 히스토리 폴링 중지');
    }
  };

  // 히스토리 데이터 불러오기
  const fetchHistory = async (deviceId: string) => {
    setLoading(true);
    try {
      setError(null);
      setConnectionStatus('connecting');
      
      console.log(`📡 히스토리 데이터 요청 - 디바이스: ${deviceId}`);
      const res = await getHistory(deviceId, 100, 0);
      
      // 데이터 유효성 검사 및 정리
      const validData = res.data
        .filter((item: any) => item && typeof item === 'object' && item.device_id)
        .map((item: any) => {
          const safeNumber = (value: any): number => {
            if (typeof value === 'number' && !isNaN(value) && isFinite(value)) {
              return value;
            }
            return 0;
          };

          return {
            ...item,
            temperature: safeNumber(item.temperature),
            humidity: safeNumber(item.humidity),
            pm10: safeNumber(item.pm10),
            pm25: safeNumber(item.pm25),
            pressure: safeNumber(item.pressure),
            illumination: safeNumber(item.illumination),
            tvoc: safeNumber(item.tvoc),
            co2: safeNumber(item.co2),
            o2: safeNumber(item.o2),
            co: safeNumber(item.co)
          };
        });
      
      setHistoryData(validData);
      setLastUpdate(new Date().toISOString());
      setConnectionStatus('connected');
      console.log(`✅ 히스토리 데이터 수신 완료 - ${validData.length}개`);
    } catch (e) {
      setHistoryData([]);
      setError('히스토리 데이터를 불러오는 중 오류가 발생했습니다.');
      setConnectionStatus('error');
      console.error('❌ 히스토리 데이터 요청 실패:', e);
    } finally {
      setLoading(false);
    }
  };

  // 수동 새로고침
  const handleRefresh = () => {
    if (selectedDevice) {
      console.log('🔄 수동 새로고침 시작');
      fetchHistory(selectedDevice.device_id);
    }
  };

  return (
    <div className="space-y-6">
      {/* 상태 표시 */}
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-bold text-gray-900">센서 히스토리</h1>
        <div className="flex items-center space-x-4">
          <StatusIndicator
            isConnected={connectionStatus === 'connected'}
            connectionStatus={connectionStatus}
            dataSource="polling"
            lastUpdate={lastUpdate}
            error={error}
          />
          <button
            onClick={handleRefresh}
            disabled={loading}
            className="px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {loading ? '새로고침 중...' : '새로고침'}
          </button>
        </div>
      </div>

      {/* 에러 메시지 */}
      {error && (
        <div className="bg-yellow-50 border border-yellow-200 rounded-md p-4">
          <div className="flex">
            <div className="flex-shrink-0">
              <svg className="h-5 w-5 text-yellow-400" viewBox="0 0 20 20" fill="currentColor">
                <path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
              </svg>
            </div>
            <div className="ml-3">
              <p className="text-sm text-yellow-700">{error}</p>
            </div>
          </div>
        </div>
      )}

      <div className="flex items-center space-x-4 mb-4">
        <label className="font-medium">디바이스 선택:</label>
        <select
          className="border rounded px-2 py-1"
          value={selectedDevice?.device_id || ''}
          onChange={e => {
            const dev = devices.find(d => d.device_id === e.target.value);
            setSelectedDevice(dev || null);
          }}
        >
          {devices.map(dev => (
            <option key={dev.device_id} value={dev.device_id}>{dev.name} ({dev.device_id})</option>
          ))}
        </select>
      </div>
      
      {loading ? (
        <div className="flex items-center justify-center h-64">
          <LoadingSpinner size="lg" text="데이터를 불러오는 중..." />
        </div>
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* 온도 */}
          <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
            <h3 className="text-lg font-medium text-gray-900 mb-4">온도 시계열</h3>
            {historyData.length > 0 ? (
              <ResponsiveContainer width="100%" height={250}>
                <LineChart data={historyData} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="recorded_time" tickFormatter={v => v.slice(5, 16)} />
                  <YAxis />
                  <Tooltip formatter={(v: any) => formatSensorValue(v, getSensorPrecision('temperature'))} />
                  <Legend />
                  <Line type="monotone" dataKey="temperature" stroke="#3b82f6" strokeWidth={2} dot={false} />
                </LineChart>
              </ResponsiveContainer>
            ) : (
              <div className="flex items-center justify-center h-[250px]">
                <p className="text-gray-500">데이터가 없습니다</p>
              </div>
            )}
          </div>
          {/* 습도 */}
          <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
            <h3 className="text-lg font-medium text-gray-900 mb-4">습도 시계열</h3>
            {historyData.length > 0 ? (
              <ResponsiveContainer width="100%" height={250}>
                <LineChart data={historyData} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="recorded_time" tickFormatter={v => v.slice(5, 16)} />
                  <YAxis />
                  <Tooltip formatter={(v: any) => formatSensorValue(v, getSensorPrecision('humidity'))} />
                  <Legend />
                  <Line type="monotone" dataKey="humidity" stroke="#10b981" strokeWidth={2} dot={false} />
                </LineChart>
              </ResponsiveContainer>
            ) : (
              <div className="flex items-center justify-center h-[250px]">
                <p className="text-gray-500">데이터가 없습니다</p>
              </div>
            )}
          </div>
          {/* PM10/PM2.5 */}
          <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
            <h3 className="text-lg font-medium text-gray-900 mb-4">미세먼지(PM10/PM2.5)</h3>
            {historyData.length > 0 ? (
              <ResponsiveContainer width="100%" height={250}>
                <LineChart data={historyData} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="recorded_time" tickFormatter={v => v.slice(5, 16)} />
                  <YAxis />
                  <Tooltip />
                  <Legend />
                  <Line type="monotone" dataKey="pm10" stroke="#f97316" strokeWidth={2} dot={false} name="PM10" />
                  <Line type="monotone" dataKey="pm25" stroke="#ef4444" strokeWidth={2} dot={false} name="PM2.5" />
                </LineChart>
              </ResponsiveContainer>
            ) : (
              <div className="flex items-center justify-center h-[250px]">
                <p className="text-gray-500">데이터가 없습니다</p>
              </div>
            )}
          </div>
          {/* CO2/TVOC */}
          <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
            <h3 className="text-lg font-medium text-gray-900 mb-4">CO2/TVOC</h3>
            {historyData.length > 0 ? (
              <ResponsiveContainer width="100%" height={250}>
                <LineChart data={historyData} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="recorded_time" tickFormatter={v => v.slice(5, 16)} />
                  <YAxis />
                  <Tooltip />
                  <Legend />
                  <Line type="monotone" dataKey="co2" stroke="#10b981" strokeWidth={2} dot={false} name="CO2" />
                  <Line type="monotone" dataKey="tvoc" stroke="#a855f7" strokeWidth={2} dot={false} name="TVOC" />
                </LineChart>
              </ResponsiveContainer>
            ) : (
              <div className="flex items-center justify-center h-[250px]">
                <p className="text-gray-500">데이터가 없습니다</p>
              </div>
            )}
          </div>
          {/* CO/O2 */}
          <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
            <h3 className="text-lg font-medium text-gray-900 mb-4">CO/O2</h3>
            {historyData.length > 0 ? (
              <ResponsiveContainer width="100%" height={250}>
                <LineChart data={historyData} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="recorded_time" tickFormatter={v => v.slice(5, 16)} />
                  <YAxis />
                  <Tooltip />
                  <Legend />
                  <Line type="monotone" dataKey="co" stroke="#ef4444" strokeWidth={2} dot={false} name="CO" />
                  <Line type="monotone" dataKey="o2" stroke="#06b6d4" strokeWidth={2} dot={false} name="O2" />
                </LineChart>
              </ResponsiveContainer>
            ) : (
              <div className="flex items-center justify-center h-[250px]">
                <p className="text-gray-500">데이터가 없습니다</p>
              </div>
            )}
          </div>
          {/* 기압/조도 */}
          <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
            <h3 className="text-lg font-medium text-gray-900 mb-4">기압/조도</h3>
            {historyData.length > 0 ? (
              <ResponsiveContainer width="100%" height={250}>
                <LineChart data={historyData} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="recorded_time" tickFormatter={v => v.slice(5, 16)} />
                  <YAxis />
                  <Tooltip />
                  <Legend />
                  <Line type="monotone" dataKey="pressure" stroke="#3b82f6" strokeWidth={2} dot={false} name="기압" />
                  <Line type="monotone" dataKey="illumination" stroke="#eab308" strokeWidth={2} dot={false} name="조도" />
                </LineChart>
              </ResponsiveContainer>
            ) : (
              <div className="flex items-center justify-center h-[250px]">
                <p className="text-gray-500">데이터가 없습니다</p>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default History;