'use client';

import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import {
  Thermometer,
  Droplets,
  Leaf,
  Eye,
  Wind,
  X
} from 'lucide-react';
import { SensorDevice, IoTDevice } from './environmentMonitoringReducer';

interface DeviceDialogProps {
  showDeviceDialog: boolean;
  editingDevice: SensorDevice | null;
  deviceForm: {
    iotDeviceId: string;
    location: string;
    fieldId: string;
  };
  availableIoTDevices: IoTDevice[];
  onDeviceFormChange: (form: Partial<typeof deviceForm>) => void;
  onSaveDevice: () => void;
  onCancel: () => void;
}

interface DeviceViewDialogProps {
  showViewDialog: boolean;
  viewingDevice: SensorDevice | null;
  onClose: () => void;
}

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

export function DeviceDialog({
  showDeviceDialog,
  editingDevice,
  deviceForm,
  availableIoTDevices,
  onDeviceFormChange,
  onSaveDevice,
  onCancel
}: DeviceDialogProps) {
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'online': return 'bg-green-500';
      case 'offline': return 'bg-gray-500';
      case 'warning': return 'bg-yellow-500';
      default: return 'bg-gray-500';
    }
  };

  const getStatusLabel = (status: string) => {
    switch (status) {
      case 'online': return '在线';
      case 'offline': return '离线';
      case 'warning': return '警告';
      default: return '未知';
    }
  };

  return (
    <Dialog open={showDeviceDialog} onOpenChange={onCancel}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>{editingDevice ? '编辑设备' : '添加设备'}</DialogTitle>
          <DialogDescription>
            {editingDevice ? '修改设备信息' : '从物联设备数据接入中选择设备并配置'}
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4">
          {!editingDevice && (
            <div>
              <Label>选择设备</Label>
              <Select
                value={deviceForm.iotDeviceId}
                onValueChange={(value) => onDeviceFormChange({ iotDeviceId: value })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="请从物联设备数据接入中选择" />
                </SelectTrigger>
                <SelectContent>
                  {availableIoTDevices.length === 0 ? (
                    <div className="p-4 text-sm text-muted-foreground text-center">
                      暂无可用设备<br />
                      请先在AI系统-全域数据感知中心-物联设备数据接入中添加环境监测站设备
                    </div>
                  ) : (
                    availableIoTDevices.map((device) => (
                      <SelectItem key={device.id} value={device.id}>
                        {device.code} - {device.name} ({device.manufacturer} {device.model})
                      </SelectItem>
                    ))
                  )}
                </SelectContent>
              </Select>
            </div>
          )}

          <div>
            <Label>选择地块</Label>
            <Select
              value={deviceForm.fieldId}
              onValueChange={(value) => onDeviceFormChange({ fieldId: value })}
            >
              <SelectTrigger>
                <SelectValue placeholder="请选择地块" />
              </SelectTrigger>
              <SelectContent>
                {availableFields.map((field) => (
                  <SelectItem key={field.id} value={field.id}>
                    {field.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div>
            <Label>安装位置</Label>
            <Input
              value={deviceForm.location}
              onChange={(e) => onDeviceFormChange({ location: e.target.value })}
              placeholder="如：地块中心位置"
            />
          </div>

          <div className="flex justify-end gap-2 pt-4 border-t">
            <Button variant="outline" onClick={onCancel}>
              取消
            </Button>
            <Button className="bg-green-600 hover:bg-green-700" onClick={onSaveDevice}>
              保存
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

export function DeviceViewDialog({
  showViewDialog,
  viewingDevice,
  onClose
}: DeviceViewDialogProps) {
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'online': return 'bg-green-500';
      case 'offline': return 'bg-gray-500';
      case 'warning': return 'bg-yellow-500';
      default: return 'bg-gray-500';
    }
  };

  const getStatusLabel = (status: string) => {
    switch (status) {
      case 'online': return '在线';
      case 'offline': return '离线';
      case 'warning': return '警告';
      default: return '未知';
    }
  };

  return (
    <Dialog open={showViewDialog} onOpenChange={onClose}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>设备详情</DialogTitle>
          <DialogDescription>
            {viewingDevice?.name} - {viewingDevice?.type}
          </DialogDescription>
        </DialogHeader>
        {viewingDevice && (
          <div className="space-y-4">
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <Label>设备名称</Label>
                <div className="mt-1 p-2 bg-muted rounded-md text-sm">{viewingDevice.name}</div>
              </div>
              <div>
                <Label>设备类型</Label>
                <div className="mt-1 p-2 bg-muted rounded-md text-sm">{viewingDevice.type}</div>
              </div>
              <div>
                <Label>所属地块</Label>
                <div className="mt-1 p-2 bg-muted rounded-md text-sm">{viewingDevice.fieldName}</div>
              </div>
              <div>
                <Label>安装位置</Label>
                <div className="mt-1 p-2 bg-muted rounded-md text-sm">{viewingDevice.location}</div>
              </div>
              <div>
                <Label>设备状态</Label>
                <div className="mt-1">
                  <Badge className={`${getStatusColor(viewingDevice.status)} text-white`}>
                    {getStatusLabel(viewingDevice.status)}
                  </Badge>
                </div>
              </div>
              <div>
                <Label>电池电量</Label>
                <div className="mt-1 p-2 bg-muted rounded-md text-sm">
                  <span className={viewingDevice.battery < 40 ? 'text-red-600 dark:text-red-400' : ''}>
                    {viewingDevice.battery}%
                  </span>
                </div>
              </div>
              <div className="sm:col-span-2">
                <Label>最后更新时间</Label>
                <div className="mt-1 p-2 bg-muted rounded-md text-sm">{viewingDevice.lastUpdate}</div>
              </div>
            </div>

            <div>
              <Label>传感器数据</Label>
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 mt-2">
                {viewingDevice.sensors.temperature && (
                  <Card className="p-3 bg-red-50 dark:bg-red-950 border-red-200 dark:border-red-800">
                    <div className="flex items-center gap-2">
                      <Thermometer className="w-4 h-4 text-red-600 dark:text-red-400" />
                      <div>
                        <p className="text-xs text-muted-foreground">温度</p>
                        <p className="text-sm font-medium">{viewingDevice.sensors.temperature}°C</p>
                      </div>
                    </div>
                  </Card>
                )}
                {viewingDevice.sensors.humidity && (
                  <Card className="p-3 bg-blue-50 dark:bg-blue-950 border-blue-200 dark:border-blue-800">
                    <div className="flex items-center gap-2">
                      <Droplets className="w-4 h-4 text-blue-600 dark:text-blue-400" />
                      <div>
                        <p className="text-xs text-muted-foreground">湿度</p>
                        <p className="text-sm font-medium">{viewingDevice.sensors.humidity}%</p>
                      </div>
                    </div>
                  </Card>
                )}
                {viewingDevice.sensors.co2 && (
                  <Card className="p-3 bg-green-50 dark:bg-green-950 border-green-200 dark:border-green-800">
                    <div className="flex items-center gap-2">
                      <Leaf className="w-4 h-4 text-green-600 dark:text-green-400" />
                      <div>
                        <p className="text-xs text-muted-foreground">CO₂</p>
                        <p className="text-sm font-medium">{viewingDevice.sensors.co2} ppm</p>
                      </div>
                    </div>
                  </Card>
                )}
                {viewingDevice.sensors.light && (
                  <Card className="p-3 bg-yellow-50 dark:bg-yellow-950 border-yellow-200 dark:border-yellow-800">
                    <div className="flex items-center gap-2">
                      <Eye className="w-4 h-4 text-yellow-600 dark:text-yellow-400" />
                      <div>
                        <p className="text-xs text-muted-foreground">光照</p>
                        <p className="text-sm font-medium">{(viewingDevice.sensors.light / 1000).toFixed(1)}k lux</p>
                      </div>
                    </div>
                  </Card>
                )}
                {viewingDevice.sensors.pm25 && (
                  <Card className="p-3 bg-purple-50 dark:bg-purple-950 border-purple-200 dark:border-purple-800">
                    <div className="flex items-center gap-2">
                      <Wind className="w-4 h-4 text-purple-600 dark:text-purple-400" />
                      <div>
                        <p className="text-xs text-muted-foreground">PM2.5</p>
                        <p className="text-sm font-medium">{viewingDevice.sensors.pm25} μg/m³</p>
                      </div>
                    </div>
                  </Card>
                )}
              </div>
            </div>

            <div className="flex justify-end pt-4 border-t">
              <Button variant="outline" onClick={onClose}>
                关闭
              </Button>
            </div>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}