import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useDevices } from '../hooks/useDevices';
import { useSensorData } from '../hooks/useSensorData';
import LoadingSpinner from '../components/LoadingSpinner';
import StatusIndicator from '../components/StatusIndicator';
import SensorCard from '../components/SensorCard';
import SensorChart from '../components/SensorChart';
import { 
  transformSensorDataToChartData, 
  transformSensorDataToCardData,
  validateChartData,
  ChartDataPoint,
  SensorCardData
} from '../utils/dataTransformers';
import { isSensorData } from '../utils/typeGuards';

// 안전한 숫자 변환 함수 - 타입 안전성 강화
const safeNumber = (value: any, defaultValue: number = 0): number => {
  if (value === null || value === undefined) {
    return defaultValue;
  }
  
  const num = Number(value);
  if (typeof num === 'number' && !isNaN(num) && isFinite(num)) {
    return num;
  }
  
  return defaultValue;
};

// 센서 데이터 유효성 검증 함수
const validateSensorData = (data: any): boolean => {
  return data && 
         typeof data === 'object' && 
         typeof data.device_id === 'string' && 
         data.device_id.length > 0;
};

const Dashboard: React.FC = () => {
  const { devices, loading: devicesLoading, error: devicesError, refetch: refetchDevices } = useDevices();
  const deviceIds = useMemo(() => devices.map(d => d.device_id), [devices]);
  
  console.log('🏠 Dashboard 렌더링 - 디바이스 ID:', deviceIds);
  
  const { 
    latestData, 
    loading: dataLoading, 
    error: dataError, 
    refetch: refetchData,
    isConnected,
    dataSource,
    lastUpdate,
    connectionStatus,
    retryCount
  } = useSensorData(deviceIds);
  
  console.log('📊 Dashboard 데이터 상태:', {
    deviceIds,
    latestDataCount: latestData?.length || 0,
    loading: dataLoading,
    error: dataError,
    isConnected,
    dataSource,
    lastUpdate
  });

  // 첫 번째 디바이스 데이터 메모이제이션 - null 체크 강화
  const firstDeviceData = useMemo(() => {
    if (!latestData || !Array.isArray(latestData) || latestData.length === 0) {
      return null;
    }
    
    const validData = latestData.find(data => validateSensorData(data));
    return validData || null;
  }, [latestData]);

  // 센서 카드 데이터 메모이제이션 - 새로운 변환 유틸리티 사용
  const sensorCards = useMemo((): SensorCardData[] => {
    return transformSensorDataToCardData(firstDeviceData);
  }, [firstDeviceData]);

  // 차트 데이터 메모이제이션 - 새로운 변환 유틸리티 사용
  const chartData = useMemo((): ChartDataPoint[] => {
    try {
      const transformedData = transformSensorDataToChartData(latestData);
      
      // 변환된 데이터 유효성 검증
      if (!validateChartData(transformedData)) {
        console.warn('Invalid chart data detected, using default data');
        return transformSensorDataToChartData([]);
      }
      
      return transformedData;
    } catch (err) {
      console.error('Error processing chart data:', err);
      return transformSensorDataToChartData([]);
    }
  }, [latestData]);

  // 에러 처리
  const error = devicesError || dataError;

  if (devicesLoading || dataLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <LoadingSpinner size="lg" text="데이터를 불러오는 중..." />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <div className="text-red-600 mb-4">
            <svg className="w-12 h-12 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
            </svg>
          </div>
          <h3 className="text-lg font-medium text-gray-900 mb-2">오류가 발생했습니다</h3>
          <p className="text-gray-600 mb-4">{error}</p>
          <button
            onClick={() => {
              refetchDevices();
              refetchData();
            }}
            className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
          >
            다시 시도
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 상태 표시 */}
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-bold text-gray-900">센서 대시보드</h1>
        <StatusIndicator
          isConnected={isConnected}
          connectionStatus={connectionStatus}
          dataSource={dataSource}
          lastUpdate={lastUpdate}
          error={dataError}
          retryCount={retryCount}
        />
      </div>

      {/* 요약 카드 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
        <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
          <div className="flex items-center">
            <div className="p-2 bg-blue-100 rounded-lg">
              <span className="text-2xl">📱</span>
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-600">활성 디바이스</p>
              <p className="text-2xl font-semibold text-gray-900">
                {devices.filter(d => d.status === 'active').length}
              </p>
            </div>
          </div>
        </div>

        <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
          <div className="flex items-center">
            <div className="p-2 bg-purple-100 rounded-lg">
              <span className="text-2xl">📊</span>
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-600">총 데이터</p>
              <p className="text-2xl font-semibold text-gray-900">
                {latestData.length}
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* 센서 카드들 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
        {sensorCards.slice(0, 4).map((card, index) => (
          <SensorCard key={index} {...card} />
        ))}
      </div>

      <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
        {sensorCards.slice(4, 8).map((card, index) => (
          <SensorCard key={index + 4} {...card} />
        ))}
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {sensorCards.slice(8, 10).map((card, index) => (
          <SensorCard key={index + 8} {...card} />
        ))}
      </div>

      {/* 기본 센서 차트 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <SensorChart
          title="온도 변화"
          data={chartData}
          dataKeys={['temperature']}
          colors={['#3b82f6']}
          names={['온도']}
        />

        <SensorChart
          title="습도 변화"
          data={chartData}
          dataKeys={['humidity']}
          colors={['#10b981']}
          names={['습도']}
        />
      </div>

      {/* 환경 센서 차트 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <SensorChart
          title="미세먼지 (PM10/PM2.5)"
          data={chartData}
          dataKeys={['pm10', 'pm25']}
          colors={['#f97316', '#ef4444']}
          names={['PM10', 'PM2.5']}
        />

        <SensorChart
          title="기압 & 조도"
          data={chartData}
          dataKeys={['pressure']}
          colors={['#3b82f6']}
          names={['기압 (hPa)']}
          rightYAxisId="right"
          rightDataKeys={['illumination']}
          rightColors={['#eab308']}
          rightNames={['조도 (lux)']}
        />
      </div>

      {/* 가스 센서 차트 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <SensorChart
          title="TVOC & CO2"
          data={chartData}
          dataKeys={['tvoc']}
          colors={['#a855f7']}
          names={['TVOC (ppb)']}
          rightYAxisId="right"
          rightDataKeys={['co2']}
          rightColors={['#10b981']}
          rightNames={['CO2 (ppm)']}
        />

        <SensorChart
          title="O2 & CO"
          data={chartData}
          dataKeys={['o2']}
          colors={['#06b6d4']}
          names={['O2 (%)']}
          rightYAxisId="right"
          rightDataKeys={['co']}
          rightColors={['#ef4444']}
          rightNames={['CO (ppm)']}
        />
      </div>

      {/* 디바이스 목록 */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200">
        <div className="px-6 py-4 border-b border-gray-200">
          <h3 className="text-lg font-medium text-gray-900">디바이스 상태</h3>
        </div>
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  디바이스 ID
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  이름
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  상태
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  마지막 연결
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {devices.map((device) => (
                <tr key={device.id}>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                    {device.device_id}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {device.name}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${
                      device.status === 'active' 
                        ? 'bg-green-100 text-green-800' 
                        : 'bg-red-100 text-red-800'
                    }`}>
                      {device.status}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {new Date(device.last_seen).toLocaleString()}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

export default Dashboard; 