'use client';

import { useReducer, useEffect } from 'react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Plus } from 'lucide-react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
  environmentMonitoringReducer,
  initialState,
  EnvironmentMonitoringAction,
  SensorDevice,
  IoTDevice
} from './components/environmentMonitoringReducer';
import { DeviceOverview } from './components/DeviceOverview';
import { RealTimeMonitoring } from './components/RealTimeMonitoring';
import { DeviceManagement } from './components/DeviceManagement';
import { DataTrends } from './components/DataTrends';
import { DeviceDialog, DeviceViewDialog } from './components/DeviceDialog';

const availableFields = [
  { id: 'field-1', name: '东区1号地' },
  { id: 'field-2', name: '西区2号地' },
  { id: 'field-3', name: '南区3号地' },
  { id: 'field-4', name: '北区4号地' },
];

export default function EnvironmentPage() {
  const [state, dispatch] = useReducer(environmentMonitoringReducer, initialState);

  useEffect(() => {
    dispatch({ type: 'LOAD_IOT_DEVICES' });
  }, []);

  const handleDeviceChange = (value: string) => {
    dispatch({ type: 'SET_SELECTED_DEVICE', payload: value });
  };

  const handleTimeRangeChange = (value: '1h' | '6h' | '24h' | '7d') => {
    dispatch({ type: 'SET_TIME_RANGE', payload: value });
  };

  const handleAddDevice = () => {
    dispatch({ type: 'SET_EDITING_DEVICE', payload: null });
    dispatch({ type: 'RESET_DEVICE_FORM' });
    dispatch({ type: 'SET_SHOW_DEVICE_DIALOG', payload: true });
  };

  const handleEditDevice = (device: SensorDevice) => {
    dispatch({ type: 'SET_EDITING_DEVICE', payload: device });
    dispatch({ type: 'SET_DEVICE_FORM', payload: {
      iotDeviceId: '',
      location: device.location,
      fieldId: device.fieldId,
    }});
    dispatch({ type: 'SET_SHOW_DEVICE_DIALOG', payload: true });
  };

  const handleViewDevice = (device: SensorDevice) => {
    dispatch({ type: 'SET_VIEWING_DEVICE', payload: device });
    dispatch({ type: 'SET_SHOW_VIEW_DIALOG', payload: true });
  };

  const handleDeleteDevice = (deviceId: string) => {
    if (confirm('确定要删除该设备吗？')) {
      dispatch({ type: 'DELETE_SENSOR_DEVICE', payload: deviceId });
      toast.success('设备已删除');
    }
  };

  const handleDeviceFormChange = (form: Partial<typeof state.deviceForm>) => {
    dispatch({ type: 'SET_DEVICE_FORM', payload: form });
  };

  const handleSaveDevice = () => {
    if (!state.deviceForm.fieldId) {
      toast.error('请选择地块');
      return;
    }

    const field = availableFields.find(f => f.id === state.deviceForm.fieldId);

    if (!field) {
      toast.error('无效的地块选择');
      return;
    }

    if (state.editingDevice) {
      // 编辑设备
      dispatch({
        type: 'UPDATE_SENSOR_DEVICE',
        payload: {
          id: state.editingDevice.id,
          updates: {
            location: state.deviceForm.location,
            fieldId: state.deviceForm.fieldId,
            fieldName: field.name,
          }
        }
      });
      toast.success('设备信息已更新');
    } else {
      // 添加新设备
      if (!state.deviceForm.iotDeviceId) {
        toast.error('请选择设备');
        return;
      }

      const iotDevice = state.availableIoTDevices.find(d => d.id === state.deviceForm.iotDeviceId);

      if (!iotDevice) {
        toast.error('无效的设备选择');
        return;
      }

      const newDevice: SensorDevice = {
        id: `device-${Date.now()}`,
        name: iotDevice.code,
        type: iotDevice.type,
        location: state.deviceForm.location,
        fieldId: state.deviceForm.fieldId,
        fieldName: field.name,
        status: 'online',
        battery: iotDevice.batteryLevel || 100,
        lastUpdate: new Date().toLocaleString('zh-CN'),
        sensors: {
          temperature: 22,
          humidity: 60,
          co2: 400,
          light: 40000,
          pm25: 30,
        },
      };

      dispatch({ type: 'ADD_SENSOR_DEVICE', payload: newDevice });

      // 更新AI数据中心的设备绑定状态
      try {
        const allIoTDevices = localStorage.getItem('smart_agriculture_ai_iot_devices');
        if (allIoTDevices) {
          const devices: IoTDevice[] = JSON.parse(allIoTDevices);
          const updatedDevices = devices.map(d =>
            d.id === state.deviceForm.iotDeviceId
              ? { ...d, bindingStatus: '已绑定' as const, bindingSystem: '地块环境监测-环境监测' }
              : d
          );
          localStorage.setItem('smart_agriculture_ai_iot_devices', JSON.stringify(updatedDevices));
        }
      } catch (error) {
        console.error('Failed to update IoT device binding status:', error);
      }

      toast.success('设备添加成功');
    }

    dispatch({ type: 'SET_SHOW_DEVICE_DIALOG', payload: false });
  };

  const handleCancelDialog = () => {
    dispatch({ type: 'SET_SHOW_DEVICE_DIALOG', payload: false });
    dispatch({ type: 'SET_SHOW_VIEW_DIALOG', payload: false });
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800 dark:text-green-200">环境监测</h2>
          <p className="text-muted-foreground">
            物联网传感器管理、环境数据采集与分析
          </p>
        </div>
        <div className="flex gap-2">
          <Button className="bg-green-600 hover:bg-green-700" onClick={handleAddDevice}>
            <Plus className="w-4 h-4 mr-2" />
            添加设备
          </Button>
        </div>
      </div>

      <DeviceOverview sensorDevices={state.sensorDevices} />

      <RealTimeMonitoring
        selectedDevice={state.selectedDevice}
        sensorDevices={state.sensorDevices}
        onDeviceChange={handleDeviceChange}
      />

      <Tabs defaultValue="devices" className="w-full">
        <TabsList>
          <TabsTrigger value="devices">设备管理</TabsTrigger>
          <TabsTrigger value="trends">数据趋势</TabsTrigger>
        </TabsList>

        <TabsContent value="devices">
          <DeviceManagement
            sensorDevices={state.sensorDevices}
            onViewDevice={handleViewDevice}
            onEditDevice={handleEditDevice}
            onDeleteDevice={handleDeleteDevice}
          />
        </TabsContent>

        <TabsContent value="trends">
          <DataTrends
            timeRange={state.timeRange}
            onTimeRangeChange={handleTimeRangeChange}
          />
        </TabsContent>
      </Tabs>

      <DeviceDialog
        showDeviceDialog={state.showDeviceDialog}
        editingDevice={state.editingDevice}
        deviceForm={state.deviceForm}
        availableIoTDevices={state.availableIoTDevices}
        onDeviceFormChange={handleDeviceFormChange}
        onSaveDevice={handleSaveDevice}
        onCancel={handleCancelDialog}
      />

      <DeviceViewDialog
        showViewDialog={state.showViewDialog}
        viewingDevice={state.viewingDevice}
        onClose={handleCancelDialog}
      />
    </div>
  );
}