import { useState, useEffect } from 'react';
import { Card } from '../../ui/card';
import { Badge } from '../../ui/badge';
import { Eye, Info } from 'lucide-react';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../../ui/table';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '../../ui/dialog';
import { Button } from '../../ui/button';
import { Alert, AlertDescription } from '../../ui/alert';

// 参数定义接口
interface ParameterDefinition {
  key: string;
  label: string;
  type: 'string' | 'number' | 'boolean' | 'select';
  required?: boolean;
  defaultValue?: any;
  options?: { label: string; value: any }[];
  unit?: string;
  min?: number;
  max?: number;
  description?: string;
}

// 负载类型接口（从设备类型管理获取）
interface LoadType {
  id: string;
  name: string;
  manufacturer?: string;
  model?: string;
  description?: string;
  parameterDefinitions: ParameterDefinition[];
  createdAt: string;
  updatedAt: string;
}

export function LoadType() {
  const [loadTypes, setLoadTypes] = useState<LoadType[]>([]);
  const [showViewDialog, setShowViewDialog] = useState(false);
  const [showParamsDialog, setShowParamsDialog] = useState(false);
  const [viewingType, setViewingType] = useState<LoadType | null>(null);
  const [viewingParams, setViewingParams] = useState<LoadType | null>(null);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = () => {
    // 从全域数据感知中心的设备类型管理读取数据
    let data = localStorage.getItem('smart_agriculture_device_types');
    
    // 如果没有数据，尝试从AI系统的数据源读取
    if (!data) {
      data = localStorage.getItem('smart_agriculture_ai_device_types');
    }
    
    if (data) {
      const types = JSON.parse(data);
      // 确保所有类型都有parameterDefinitions字段
      const normalizedTypes = types.map((type: any) => ({
        ...type,
        parameterDefinitions: type.parameterDefinitions || []
      }));
      setLoadTypes(normalizedTypes);
      // 同步到本地存储
      localStorage.setItem('smart_agriculture_device_types', JSON.stringify(normalizedTypes));
    } else {
      // 如果都没有数据，创建默认样例数据
      const mockTypes: LoadType[] = [
        {
          id: 'device-type-1',
          name: '土壤传感器',
          manufacturer: '施耐德',
          model: 'SOIL-100',
          description: '高精度土壤温湿度、养分监测传感器',
          parameterDefinitions: [
            {
              key: 'measurementInterval',
              label: '测量间隔',
              type: 'number',
              unit: '分钟',
              required: true,
              defaultValue: 30,
              min: 5,
              max: 120,
              description: '数据测量时间间隔'
            },
            {
              key: 'uploadMode',
              label: '上传模式',
              type: 'select',
              options: [
                { label: '实时上传', value: 'realtime' },
                { label: '定时上传', value: 'scheduled' }
              ],
              defaultValue: 'scheduled',
              description: '数据上传方式'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-6',
          name: 'GPS定位终端',
          manufacturer: '中国北斗',
          model: 'BD-GPS-1000',
          description: '北斗/GPS双模定位终端，实时位置追踪和轨迹记录',
          parameterDefinitions: [
            {
              key: 'positionInterval',
              label: '定位间隔',
              type: 'number',
              unit: '秒',
              required: true,
              defaultValue: 10,
              min: 1,
              max: 300,
              description: '位置更新时间间隔'
            },
            {
              key: 'workMode',
              label: '工作模式',
              type: 'select',
              options: [
                { label: '北斗优先', value: 'beidou' },
                { label: 'GPS优先', value: 'gps' },
                { label: '双模', value: 'dual' }
              ],
              defaultValue: 'dual',
              description: '定位系统选择'
            },
            {
              key: 'savePath',
              label: '保存轨迹',
              type: 'boolean',
              defaultValue: true,
              description: '是否保存历史轨迹'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-7',
          name: '高清摄像头',
          manufacturer: '海康威视',
          model: 'HIK-CAM-2000',
          description: '4K高清摄像头，支持夜视、变焦和AI识别',
          parameterDefinitions: [
            {
              key: 'resolution',
              label: '分辨率',
              type: 'select',
              options: [
                { label: '1080P', value: '1080' },
                { label: '2K', value: '2k' },
                { label: '4K', value: '4k' }
              ],
              required: true,
              defaultValue: '4k'
            },
            {
              key: 'frameRate',
              label: '帧率',
              type: 'number',
              unit: 'fps',
              defaultValue: 30,
              min: 15,
              max: 60,
              description: '视频帧率'
            },
            {
              key: 'nightVision',
              label: '夜视功能',
              type: 'boolean',
              defaultValue: true
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-8',
          name: '油耗监测仪',
          manufacturer: '博世',
          model: 'BOSCH-FUEL-300',
          description: '精密油耗监测仪，实时监测燃油消耗和液位',
          parameterDefinitions: [
            {
              key: 'updateInterval',
              label: '更新间隔',
              type: 'number',
              unit: '秒',
              required: true,
              defaultValue: 5,
              min: 1,
              max: 60,
              description: '数据更新频率'
            },
            {
              key: 'alarmThreshold',
              label: '低油位报警',
              type: 'number',
              unit: '%',
              defaultValue: 20,
              min: 5,
              max: 50,
              description: '低于此百分比时报警'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-9',
          name: '转速传感器',
          manufacturer: '西门子',
          model: 'SIEMENS-RPM-500',
          description: '高精度转速传感器，用于监测发动机和作业部件转速',
          parameterDefinitions: [
            {
              key: 'samplingRate',
              label: '采样率',
              type: 'number',
              unit: 'Hz',
              required: true,
              defaultValue: 100,
              min: 10,
              max: 1000,
              description: '每秒采样次数'
            },
            {
              key: 'maxRPM',
              label: '最大转速',
              type: 'number',
              unit: 'RPM',
              required: true,
              defaultValue: 3000,
              min: 500,
              max: 10000
            },
            {
              key: 'overSpeedAlarm',
              label: '超速报警',
              type: 'boolean',
              defaultValue: true
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'device-type-10',
          name: '作业深度传感器',
          manufacturer: '约翰迪尔',
          model: 'JD-DEPTH-600',
          description: '耕作深度监测传感器，确保作业深度一致性',
          parameterDefinitions: [
            {
              key: 'measurementUnit',
              label: '测量单位',
              type: 'select',
              options: [
                { label: '厘米', value: 'cm' },
                { label: '英寸', value: 'inch' }
              ],
              required: true,
              defaultValue: 'cm'
            },
            {
              key: 'targetDepth',
              label: '目标深度',
              type: 'number',
              unit: 'cm',
              required: true,
              defaultValue: 25,
              min: 5,
              max: 50,
              description: '期望耕作深度'
            },
            {
              key: 'tolerance',
              label: '容差范围',
              type: 'number',
              unit: 'cm',
              defaultValue: 3,
              min: 1,
              max: 10,
              description: '允许偏差范围'
            }
          ],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
      ];
      setLoadTypes(mockTypes);
      localStorage.setItem('smart_agriculture_device_types', JSON.stringify(mockTypes));
    }
  };

  const handleView = (type: LoadType) => {
    setViewingType(type);
    setShowViewDialog(true);
  };

  const handleViewParams = (type: LoadType) => {
    setViewingParams(type);
    setShowParamsDialog(true);
  };

  const getParamTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      'number': '数字',
      'string': '文本',
      'boolean': '布尔',
      'select': '选择'
    };
    return labels[type] || type;
  };

  // 参数统计
  const totalParams = loadTypes.reduce((sum, type) => sum + (type.parameterDefinitions?.length || 0), 0);
  const typesWithParams = loadTypes.filter(type => (type.parameterDefinitions?.length || 0) > 0).length;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-primary">负载类型管理</h2>
          <p className="text-muted-foreground">查看农机负载设备的类型信息（只读）</p>
        </div>
      </div>

      {/* 数据来源说明 */}
      <Alert>
        <Info className="h-4 w-4" />
        <AlertDescription>
          负载类型数据来源于"AI作物模型精准决策系统 → 全域数据感知中心 → 设备类型管理"。
          如需新增、编辑或删除负载类型，请前往该模块进行管理。
        </AlertDescription>
      </Alert>

      {/* 统计卡片 */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">总类型数</div>
          <div className="mt-1">{loadTypes.length}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">参数模板总数</div>
          <div className="mt-1 text-success">{totalParams}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">已配置模板</div>
          <div className="mt-1">{typesWithParams} / {loadTypes.length}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">已填写品牌</div>
          <div className="mt-1 text-info">
            {loadTypes.filter(t => t.manufacturer).length}
          </div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">已填写型号</div>
          <div className="mt-1">
            {loadTypes.filter(t => t.model).length}
          </div>
        </Card>
      </div>

      {/* 类型列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>类型名称</TableHead>
              <TableHead>品牌</TableHead>
              <TableHead>型号</TableHead>
              <TableHead>描述</TableHead>
              <TableHead>参数模板</TableHead>
              <TableHead className="text-right">操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loadTypes.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="text-center text-muted-foreground py-8">
                  暂无数据，请前往"AI作物模型精准决策系统 → 全域数据感知中心 → 设备类型管理"添加设备类型
                </TableCell>
              </TableRow>
            ) : (
              loadTypes.map(type => (
                <TableRow key={type.id}>
                  <TableCell>{type.name}</TableCell>
                  <TableCell>{type.manufacturer || '-'}</TableCell>
                  <TableCell>{type.model || '-'}</TableCell>
                  <TableCell className="max-w-md">
                    <div className="truncate">
                      {type.description || '-'}
                    </div>
                  </TableCell>
                  <TableCell>
                    {(type.parameterDefinitions?.length || 0) > 0 ? (
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleViewParams(type)}
                        className="text-success hover:text-success/80"
                      >
                        <Eye className="w-4 h-4 mr-1" />
                        {type.parameterDefinitions.length} 个参数
                      </Button>
                    ) : (
                      <span className="text-muted-foreground text-sm">未定义</span>
                    )}
                  </TableCell>
                  <TableCell className="text-right">
                    <Button 
                      variant="ghost" 
                      size="sm" 
                      onClick={() => handleView(type)}
                      title="查看详情"
                    >
                      <Eye className="w-4 h-4" />
                    </Button>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>

      {/* 查看详情对话框 */}
      <Dialog open={showViewDialog} onOpenChange={setShowViewDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>负载类型详情</DialogTitle>
            <DialogDescription>查看负载类型的详细信息</DialogDescription>
          </DialogHeader>
          {viewingType && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>类型名称</Label>
                  <div className="field-value">{viewingType.name}</div>
                </div>
                <div>
                  <Label>品牌</Label>
                  <div className="field-value">{viewingType.manufacturer || '-'}</div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>型号</Label>
                  <div className="field-value">{viewingType.model || '-'}</div>
                </div>
                <div>
                  <Label>参数模板数量</Label>
                  <div className="field-value">
                    {viewingType.parameterDefinitions?.length || 0} 个
                  </div>
                </div>
              </div>

              <div>
                <Label>描述</Label>
                <div className="field-value min-h-[5rem]">
                  {viewingType.description || '-'}
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>创建时间</Label>
                  <div className="field-value">
                    {new Date(viewingType.createdAt).toLocaleString('zh-CN')}
                  </div>
                </div>
                <div>
                  <Label>更新时间</Label>
                  <div className="field-value">
                    {new Date(viewingType.updatedAt).toLocaleString('zh-CN')}
                  </div>
                </div>
              </div>

              {(viewingType.parameterDefinitions?.length || 0) > 0 && (
                <div className="pt-4 border-t">
                  <Button
                    variant="outline"
                    onClick={() => {
                      setShowViewDialog(false);
                      handleViewParams(viewingType);
                    }}
                    className="w-full"
                  >
                    <Eye className="w-4 h-4 mr-2" />
                    查看参数模板
                  </Button>
                </div>
              )}
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 查看参数模板对话框 */}
      <Dialog open={showParamsDialog} onOpenChange={setShowParamsDialog}>
        <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>参数模板详情</DialogTitle>
            <DialogDescription>
              {viewingParams?.name} - 共 {viewingParams?.parameterDefinitions?.length || 0} 个参数
            </DialogDescription>
          </DialogHeader>
          {viewingParams && (
            <div className="space-y-4">
              {(viewingParams.parameterDefinitions?.length || 0) === 0 ? (
                <div className="text-center text-muted-foreground py-8">
                  该类型尚未配置参数模板
                </div>
              ) : (
                <div className="space-y-4">
                  {viewingParams.parameterDefinitions.map((param, index) => (
                    <Card key={index} className="p-4">
                      <div className="space-y-3">
                        {/* 参数基本信息 */}
                        <div className="flex items-start justify-between">
                          <div>
                            <div className="flex items-center gap-2">
                              <span className="font-medium">{param.label}</span>
                              {param.required && (
                                <Badge variant="destructive" className="text-xs">必填</Badge>
                              )}
                              <Badge variant="outline" className="text-xs">
                                {getParamTypeLabel(param.type)}
                              </Badge>
                            </div>
                            <div className="text-sm text-muted-foreground mt-1">
                              字段Key: {param.key}
                            </div>
                          </div>
                          {param.defaultValue !== undefined && (
                            <Badge variant="secondary">
                              默认值: {String(param.defaultValue)}{param.unit ? ` ${param.unit}` : ''}
                            </Badge>
                          )}
                        </div>

                        {/* 参数描述 */}
                        {param.description && (
                          <div className="text-sm text-muted-foreground bg-muted/50 p-2 rounded">
                            {param.description}
                          </div>
                        )}

                        {/* 参数约束 */}
                        <div className="flex flex-wrap gap-4 text-sm">
                          {param.type === 'number' && (
                            <>
                              {param.min !== undefined && (
                                <div className="text-muted-foreground">
                                  最小值: <span className="text-foreground">{param.min}</span>
                                </div>
                              )}
                              {param.max !== undefined && (
                                <div className="text-muted-foreground">
                                  最大值: <span className="text-foreground">{param.max}</span>
                                </div>
                              )}
                              {param.unit && (
                                <div className="text-muted-foreground">
                                  单位: <span className="text-foreground">{param.unit}</span>
                                </div>
                              )}
                            </>
                          )}
                          {param.type === 'select' && param.options && (
                            <div className="w-full">
                              <div className="text-muted-foreground mb-2">可选值:</div>
                              <div className="flex flex-wrap gap-2">
                                {param.options.map((opt, idx) => (
                                  <Badge key={idx} variant="outline">
                                    {opt.label}
                                  </Badge>
                                ))}
                              </div>
                            </div>
                          )}
                        </div>
                      </div>
                    </Card>
                  ))}
                </div>
              )}
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}

// Label组件（如果没有导入）
function Label({ children, className = '' }: { children: React.ReactNode; className?: string }) {
  return (
    <label className={`text-sm font-semibold text-muted-foreground uppercase tracking-wide ${className}`}>
      {children}
    </label>
  );
}
