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

export function LoadParameter() {
  const [deviceTypes, setDeviceTypes] = useState<DeviceType[]>([]);
  const [selectedType, setSelectedType] = useState<DeviceType | null>(null);
  const [showParamDialog, setShowParamDialog] = useState(false);
  const [viewingParam, setViewingParam] = useState<ParameterDefinition | null>(null);

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

  const loadData = () => {
    // 从全域数据感知中心的设备参数管理读取数据
    let typesData = localStorage.getItem('smart_agriculture_device_types');
    
    // 如果没有数据，尝试从AI系统的数据源读取
    if (!typesData) {
      typesData = localStorage.getItem('smart_agriculture_ai_device_types');
    }
    
    if (typesData) {
      const types = JSON.parse(typesData);
      setDeviceTypes(types);
      // 同步到本地存储
      localStorage.setItem('smart_agriculture_device_types', JSON.stringify(types));
    } else {
      // 如果都没有数据，显示空列表（数据会在LoadType中创建）
      setDeviceTypes([]);
    }
  };

  const getCategoryColor = (category: string) => {
    const colors: Record<string, string> = {
      '摄像头': 'bg-info-muted text-info',
      '北斗终端': 'bg-success-muted text-success',
      'GPS终端': 'bg-success-muted text-success',
      '转速传感器': 'bg-info-muted text-info',
      '油耗传感器': 'bg-warning-muted text-warning',
      '温度传感器': 'bg-error-muted text-error',
      '湿度传感器': 'bg-info-muted text-info',
      '深度传感器': 'bg-info-muted text-info',
      '流量传感器': 'bg-info-muted text-info',
      '其他': 'bg-muted text-muted-foreground',
    };
    return colors[category] || 'bg-muted text-muted-foreground';
  };

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

  const handleManageParams = (type: DeviceType) => {
    setSelectedType(type);
  };

  const handleViewParam = (param: ParameterDefinition) => {
    setViewingParam(param);
    setShowParamDialog(true);
  };

  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-1 lg:grid-cols-2 gap-6">
        {/* 左侧：设备类型列表 */}
        <Card>
          <div className="p-4 border-b">
            <h3>设备类型列表</h3>
            <p className="text-sm text-muted-foreground">选择设备类型以查看参数模板</p>
          </div>
          <div className="p-4">
            {deviceTypes.length === 0 ? (
              <div className="text-center text-muted-foreground py-8">
                暂无设备类型，请前往"AI作物模型精准决策系统 → 全域数据感知中心 → 设备类型管理"添加设备类型
              </div>
            ) : (
              <div className="space-y-2">
                {deviceTypes.map(type => (
                  <div
                    key={type.id}
                    className={`p-4 rounded-lg border-2 cursor-pointer transition-all ${
                      selectedType?.id === type.id
                        ? 'border-success bg-success-muted'
                        : 'border-border hover:border-success/50'
                    }`}
                    onClick={() => handleManageParams(type)}
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <Settings className="w-5 h-5 text-muted-foreground" />
                        <div>
                          <div className="flex items-center gap-2">
                            <span>{type.name}</span>
                            <Badge variant="secondary" className={getCategoryColor(type.category)}>
                              {type.category}
                            </Badge>
                          </div>
                          <div className="text-sm text-muted-foreground mt-1">
                            {type.manufacturer} {type.model}
                          </div>
                        </div>
                      </div>
                      <Badge variant="outline">
                        {type.parameterDefinitions.length} 个参数
                      </Badge>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </Card>

        {/* 右侧：参数列表 */}
        <Card>
          <div className="p-4 border-b">
            <div className="flex items-center justify-between">
              <div>
                <h3>参数模板</h3>
                {selectedType ? (
                  <p className="text-sm text-muted-foreground">{selectedType.name}</p>
                ) : (
                  <p className="text-sm text-muted-foreground">请选择设备类型</p>
                )}
              </div>
            </div>
          </div>

          <div className="p-4">
            {!selectedType ? (
              <div className="text-center text-muted-foreground py-12">
                <Settings className="w-12 h-12 mx-auto mb-3 opacity-30" />
                <p>请从左侧选择设备类型</p>
              </div>
            ) : selectedType.parameterDefinitions.length === 0 ? (
              <div className="text-center text-muted-foreground py-12">
                <p>该设备类型暂未配置参数模板</p>
                <p className="text-sm mt-2">请前往设备参数管理模块添加参数</p>
              </div>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>参数名称</TableHead>
                    <TableHead>编码</TableHead>
                    <TableHead>类型</TableHead>
                    <TableHead>必填</TableHead>
                    <TableHead className="text-right">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {selectedType.parameterDefinitions.map((param, index) => (
                    <TableRow key={index}>
                      <TableCell>
                        <div>
                          <div>{param.label}</div>
                          {param.description && (
                            <div className="text-xs text-muted-foreground mt-1">
                              {param.description}
                            </div>
                          )}
                        </div>
                      </TableCell>
                      <TableCell>
                        <code className="text-xs bg-muted px-2 py-1 rounded">
                          {param.key}
                        </code>
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline">
                          {getParamTypeLabel(param.type)}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        {param.required ? (
                          <Badge variant="destructive" className="text-xs">必填</Badge>
                        ) : (
                          <Badge variant="secondary" className="text-xs">可选</Badge>
                        )}
                      </TableCell>
                      <TableCell className="text-right">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleViewParam(param)}
                          title="查看详情"
                        >
                          <Eye className="w-4 h-4" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            )}
          </div>
        </Card>
      </div>

      {/* 查看参数详情对话框 */}
      <Dialog open={showParamDialog} onOpenChange={setShowParamDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>参数详情</DialogTitle>
            <DialogDescription>查看参数的详细配置信息</DialogDescription>
          </DialogHeader>
          
          {viewingParam && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>参数名称</Label>
                  <div className="field-value">{viewingParam.label}</div>
                </div>
                <div>
                  <Label>参数编码</Label>
                  <div className="field-value">
                    <code className="text-sm">{viewingParam.key}</code>
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label>参数类型</Label>
                  <div className="field-value">
                    <Badge variant="outline">
                      {getParamTypeLabel(viewingParam.type)}
                    </Badge>
                  </div>
                </div>
                <div>
                  <Label>是否必填</Label>
                  <div className="field-value">
                    {viewingParam.required ? (
                      <Badge variant="destructive">必填</Badge>
                    ) : (
                      <Badge variant="secondary">可选</Badge>
                    )}
                  </div>
                </div>
              </div>

              {viewingParam.description && (
                <div>
                  <Label>参数描述</Label>
                  <div className="field-value min-h-[4rem]">
                    {viewingParam.description}
                  </div>
                </div>
              )}

              {viewingParam.defaultValue !== undefined && (
                <div>
                  <Label>默认值</Label>
                  <div className="field-value">
                    {String(viewingParam.defaultValue)}
                    {viewingParam.unit && ` ${viewingParam.unit}`}
                  </div>
                </div>
              )}

              {viewingParam.type === 'number' && (
                <div className="grid grid-cols-3 gap-4">
                  {viewingParam.min !== undefined && (
                    <div>
                      <Label>最小值</Label>
                      <div className="field-value">{viewingParam.min}</div>
                    </div>
                  )}
                  {viewingParam.max !== undefined && (
                    <div>
                      <Label>最大值</Label>
                      <div className="field-value">{viewingParam.max}</div>
                    </div>
                  )}
                  {viewingParam.unit && (
                    <div>
                      <Label>单位</Label>
                      <div className="field-value">{viewingParam.unit}</div>
                    </div>
                  )}
                </div>
              )}

              {viewingParam.type === 'select' && viewingParam.options && (
                <div>
                  <Label>可选值</Label>
                  <div className="mt-2 space-y-2">
                    {viewingParam.options.map((option, idx) => (
                      <div key={idx} className="flex items-center gap-3 p-2 bg-muted rounded">
                        <Badge variant="outline">{option.label}</Badge>
                        <code className="text-xs text-muted-foreground">
                          value: {option.value}
                        </code>
                      </div>
                    ))}
                  </div>
                </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>
  );
}
