import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '../ui/dialog';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { Label } from '../ui/label';
import {
  Eye,
  Settings,
  Info,
  RefreshCw,
  Gauge,
  TrendingUp,
  CheckCircle,
  AlertCircle,
  Package,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

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

// 设备类型接口（来自AI系统）
interface DeviceType {
  id: string;
  name: string;
  manufacturer?: string;
  model?: string;
  description?: string;
  parameterDefinitions: ParameterDefinition[];
  createdAt: string;
  updatedAt: string;
}

export function WaterFertilizerParameter() {
  const [deviceTypes, setDeviceTypes] = useState<DeviceType[]>([]);
  const [selectedType, setSelectedType] = useState<DeviceType | null>(null);
  const [showViewDialog, setShowViewDialog] = useState(false);
  const [viewingParameter, setViewingParameter] = useState<ParameterDefinition | null>(null);
  const [paramTypeFilter, setParamTypeFilter] = useState<string>('all');
  const [requiredFilter, setRequiredFilter] = useState<string>('all');

  // 从AI系统加载设备类型和参数
  useEffect(() => {
    loadDeviceParameters();
  }, []);

  // 从AI系统加载设备参数数据
  const loadDeviceParameters = () => {
    const data = localStorage.getItem('smart_agriculture_ai_device_types');
    if (data) {
      const types: DeviceType[] = JSON.parse(data);
      setDeviceTypes(types);
      
      // 默认选择第一个设备类型
      if (types.length > 0 && !selectedType) {
        setSelectedType(types[0]);
      }
      
      toast.success(`已从AI系统加载 ${types.length} 个设备类型`);
    } else {
      toast.info('请先在AI系统-全域数据感知中心-设备参数管理中配置设备参数');
    }
  };

  // 选择设备类型
  const handleTypeSelect = (typeId: string) => {
    const type = deviceTypes.find(t => t.id === typeId);
    if (type) {
      setSelectedType(type);
      // 重置筛选
      setParamTypeFilter('all');
      setRequiredFilter('all');
    }
  };

  // 查看参数详情
  const handleViewParameter = (parameter: ParameterDefinition) => {
    setViewingParameter(parameter);
    setShowViewDialog(true);
  };

  // 获取参数类型样式
  const getParameterTypeBadge = (type: string) => {
    const colors: { [key: string]: string } = {
      'string': 'bg-blue-100 text-blue-800',
      'number': 'bg-green-100 text-green-800',
      'boolean': 'bg-purple-100 text-purple-800',
      'select': 'bg-orange-100 text-orange-800',
    };
    return (
      <Badge className={colors[type] || 'bg-gray-100 text-gray-800'}>
        {type === 'string' ? '字符串' : 
         type === 'number' ? '数值' : 
         type === 'boolean' ? '布尔值' : 
         type === 'select' ? '选择' : type}
      </Badge>
    );
  };

  // 统计数据
  const totalDeviceTypes = deviceTypes.length;
  const totalParameters = deviceTypes.reduce((sum, type) => sum + (type.parameterDefinitions?.length || 0), 0);
  const currentTypeParams = selectedType?.parameterDefinitions?.length || 0;
  const requiredParameters = deviceTypes.reduce((sum, type) => {
    return sum + (type.parameterDefinitions?.filter(p => p.required)?.length || 0);
  }, 0);
  const numberParameters = deviceTypes.reduce((sum, type) => {
    return sum + (type.parameterDefinitions?.filter(p => p.type === 'number')?.length || 0);
  }, 0);

  // 筛选参数
  const getFilteredParameters = () => {
    if (!selectedType || !selectedType.parameterDefinitions) return [];
    
    let filtered = selectedType.parameterDefinitions;

    // 参数类型筛选
    if (paramTypeFilter !== 'all') {
      filtered = filtered.filter(param => param.type === paramTypeFilter);
    }

    // 必填项筛选
    if (requiredFilter !== 'all') {
      filtered = filtered.filter(param => 
        requiredFilter === 'required' ? param.required : !param.required
      );
    }

    return filtered;
  };

  const filteredParameters = getFilteredParameters();

  // 获取唯一的参数类型列表
  const parameterTypes = selectedType?.parameterDefinitions 
    ? Array.from(new Set(selectedType.parameterDefinitions.map(p => p.type)))
    : [];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">水肥机参数配置</h2>
          <p className="text-muted-foreground">
            数据来源：AI作物模型精准决策系统 - 全域数据感知中心 - 设备参数管理（只读模式）
          </p>
        </div>
        <Button variant="outline" onClick={loadDeviceParameters}>
          <RefreshCw className="w-4 h-4 mr-2" />
          刷新数据
        </Button>
      </div>

      {/* 只读模式提示 */}
      <Card className="p-4 bg-blue-50 border-blue-200">
        <div className="flex items-start gap-3">
          <Info className="w-5 h-5 text-blue-600 mt-0.5" />
          <div>
            <p className="text-blue-900">
              <strong>只读模式</strong>：本页面数据来自AI系统的设备参数管理，仅供查询查看。
            </p>
            <p className="text-sm text-blue-700 mt-1">
              如需添加或修改参数配置，请前往：<strong>AI作物模型精准决策系统 → 全域数据感知中心 → 设备参数管理</strong>
            </p>
          </div>
        </div>
      </Card>

      {/* 统计卡片 */}
      <div className="grid grid-cols-5 gap-4">
        <Card className="p-4 bg-gradient-to-br from-blue-50 to-blue-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">设备类型</p>
              <p className="mt-2 text-2xl text-blue-600">{totalDeviceTypes}</p>
            </div>
            <Package className="w-10 h-10 text-blue-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-4 bg-gradient-to-br from-green-50 to-green-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">参数总数</p>
              <p className="mt-2 text-2xl text-green-600">{totalParameters}</p>
            </div>
            <Settings className="w-10 h-10 text-green-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-4 bg-gradient-to-br from-purple-50 to-purple-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">当前类型</p>
              <p className="mt-2 text-2xl text-purple-600">{currentTypeParams}</p>
            </div>
            <CheckCircle className="w-10 h-10 text-purple-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-4 bg-gradient-to-br from-red-50 to-red-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">必填参数</p>
              <p className="mt-2 text-2xl text-red-600">{requiredParameters}</p>
            </div>
            <AlertCircle className="w-10 h-10 text-red-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-4 bg-gradient-to-br from-orange-50 to-orange-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">数值参数</p>
              <p className="mt-2 text-2xl text-orange-600">{numberParameters}</p>
            </div>
            <Gauge className="w-10 h-10 text-orange-600 opacity-50" />
          </div>
        </Card>
      </div>

      <div className="grid grid-cols-12 gap-6">
        {/* 左侧：设备类型列表 */}
        <Card className="col-span-4 p-4">
          <h3 className="mb-4 text-green-800">设备类型列表</h3>
          {deviceTypes.length === 0 ? (
            <div className="text-center text-muted-foreground py-8">
              <Package className="w-12 h-12 mx-auto mb-2 opacity-30" />
              <p>暂无设备类型</p>
              <p className="text-sm mt-1">请先在AI系统中添加设备类型</p>
            </div>
          ) : (
            <div className="space-y-2">
              {deviceTypes.map(type => (
                <div
                  key={type.id}
                  onClick={() => handleTypeSelect(type.id)}
                  className={`p-3 rounded-lg cursor-pointer transition-all ${
                    selectedType?.id === type.id
                      ? 'bg-green-50 border-2 border-green-500'
                      : 'bg-muted hover:bg-accent border-2 border-transparent'
                  }`}
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1 min-w-0">
                      <h4 className="truncate">{type.name}</h4>
                      <p className="text-sm text-muted-foreground mt-1">
                        {type.manufacturer || '未知厂商'} {type.model ? `· ${type.model}` : ''}
                      </p>
                    </div>
                    <Badge variant="outline" className="ml-2">
                      {type.parameterDefinitions?.length || 0}
                    </Badge>
                  </div>
                </div>
              ))}
            </div>
          )}
        </Card>

        {/* 右侧：参数列表 */}
        <Card className="col-span-8 p-4">
          {selectedType ? (
            <>
              <div className="mb-4">
                <div className="flex items-center justify-between mb-2">
                  <div>
                    <h3 className="text-green-800">{selectedType.name} - 参数配置</h3>
                    <p className="text-sm text-muted-foreground mt-1">
                      {selectedType.description || '暂无描述'}
                    </p>
                  </div>
                </div>

                {/* 筛选器 */}
                {selectedType.parameterDefinitions && selectedType.parameterDefinitions.length > 0 && (
                  <div className="flex gap-3 mt-4">
                    <Select value={paramTypeFilter} onValueChange={setParamTypeFilter}>
                      <SelectTrigger className="w-40">
                        <SelectValue placeholder="参数类型" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="all">全部类型</SelectItem>
                        {parameterTypes.map(type => (
                          <SelectItem key={type} value={type}>
                            {type === 'string' ? '字符串' : 
                             type === 'number' ? '数值' : 
                             type === 'boolean' ? '布尔值' : 
                             type === 'select' ? '选择' : type}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <Select value={requiredFilter} onValueChange={setRequiredFilter}>
                      <SelectTrigger className="w-40">
                        <SelectValue placeholder="必填筛选" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="all">全部</SelectItem>
                        <SelectItem value="required">必填</SelectItem>
                        <SelectItem value="optional">可选</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                )}
              </div>

              {selectedType.parameterDefinitions && selectedType.parameterDefinitions.length > 0 ? (
                filteredParameters.length > 0 ? (
                  <div className="overflow-x-auto">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>参数键</TableHead>
                          <TableHead>参数名称</TableHead>
                          <TableHead>数据类型</TableHead>
                          <TableHead>单位</TableHead>
                          <TableHead>取值范围</TableHead>
                          <TableHead>默认值</TableHead>
                          <TableHead>必填</TableHead>
                          <TableHead>操作</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {filteredParameters.map((param) => (
                          <TableRow key={param.key} className="hover:bg-gray-50">
                            <TableCell>
                              <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                                {param.key}
                              </code>
                            </TableCell>
                            <TableCell>
                              <div className="flex items-center gap-2">
                                <Settings className="w-4 h-4 text-green-600" />
                                {param.label}
                              </div>
                            </TableCell>
                            <TableCell>{getParameterTypeBadge(param.type)}</TableCell>
                            <TableCell>{param.unit || '-'}</TableCell>
                            <TableCell className="text-sm">
                              {param.type === 'number' && param.min !== undefined && param.max !== undefined
                                ? `${param.min} ~ ${param.max}`
                                : param.type === 'select' && param.options
                                ? `${param.options.length} 个选项`
                                : '-'}
                            </TableCell>
                            <TableCell className="text-sm text-muted-foreground">
                              {param.defaultValue !== undefined && param.defaultValue !== null
                                ? String(param.defaultValue)
                                : '-'}
                            </TableCell>
                            <TableCell>
                              {param.required ? (
                                <Badge className="bg-red-100 text-red-800">必填</Badge>
                              ) : (
                                <Badge variant="outline">可选</Badge>
                              )}
                            </TableCell>
                            <TableCell>
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => handleViewParameter(param)}
                              >
                                <Eye className="w-4 h-4 mr-1" />
                                查看
                              </Button>
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </div>
                ) : (
                  <div className="text-center text-muted-foreground py-8">
                    没有符合筛选条件的参数
                  </div>
                )
              ) : (
                <div className="text-center text-muted-foreground py-8">
                  <Settings className="w-12 h-12 mx-auto mb-2 opacity-30" />
                  <p>该设备类型暂无参数配置</p>
                  <p className="text-sm mt-1">请在AI系统中为此设备类型添加参数</p>
                </div>
              )}
            </>
          ) : (
            <div className="text-center text-muted-foreground py-12">
              <Settings className="w-16 h-16 mx-auto mb-3 opacity-30" />
              <p>请从左侧选择一个设备类型</p>
            </div>
          )}
        </Card>
      </div>

      {/* 查看参数详情对话框 */}
      <Dialog open={showViewDialog} onOpenChange={setShowViewDialog}>
        <DialogContent className="max-w-3xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>参数详情</DialogTitle>
            <DialogDescription>
              查看参数的完整配置信息（只读）
            </DialogDescription>
          </DialogHeader>
          {viewingParameter && (
            <div className="space-y-6">
              {/* 基本信息 */}
              <div>
                <h3 className="mb-3 text-green-800">基本信息</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>参数键（Key）</Label>
                    <div className="field-value">
                      <code className="bg-gray-100 px-2 py-1 rounded">
                        {viewingParameter.key}
                      </code>
                    </div>
                  </div>
                  <div>
                    <Label>参数名称</Label>
                    <div className="field-value">{viewingParameter.label}</div>
                  </div>
                  <div>
                    <Label>数据类型</Label>
                    <div className="field-value">{getParameterTypeBadge(viewingParameter.type)}</div>
                  </div>
                  <div>
                    <Label>必填项</Label>
                    <div className="field-value">
                      {viewingParameter.required ? (
                        <Badge className="bg-red-100 text-red-800">是</Badge>
                      ) : (
                        <Badge variant="outline">否</Badge>
                      )}
                    </div>
                  </div>
                </div>
              </div>

              {/* 设备类型信息 */}
              {selectedType && (
                <div>
                  <h3 className="mb-3 text-green-800">设备类型</h3>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label>设备类型名称</Label>
                      <div className="field-value">
                        <Badge variant="outline">{selectedType.name}</Badge>
                      </div>
                    </div>
                    <div>
                      <Label>设备类型ID</Label>
                      <div className="field-value">
                        <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                          {selectedType.id}
                        </code>
                      </div>
                    </div>
                    {selectedType.manufacturer && (
                      <div>
                        <Label>生产厂商</Label>
                        <div className="field-value">{selectedType.manufacturer}</div>
                      </div>
                    )}
                    {selectedType.model && (
                      <div>
                        <Label>产品型号</Label>
                        <div className="field-value">{selectedType.model}</div>
                      </div>
                    )}
                  </div>
                </div>
              )}

              {/* 参数配置 */}
              <div>
                <h3 className="mb-3 text-green-800">参数配置</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>单位</Label>
                    <div className="field-value">{viewingParameter.unit || '-'}</div>
                  </div>
                  <div>
                    <Label>默认值</Label>
                    <div className="field-value">
                      {viewingParameter.defaultValue !== undefined && viewingParameter.defaultValue !== null
                        ? String(viewingParameter.defaultValue)
                        : '-'}
                    </div>
                  </div>
                  {viewingParameter.type === 'number' && (
                    <>
                      <div>
                        <Label>最小值</Label>
                        <div className="field-value">
                          {viewingParameter.min !== undefined ? viewingParameter.min : '-'}
                        </div>
                      </div>
                      <div>
                        <Label>最大值</Label>
                        <div className="field-value">
                          {viewingParameter.max !== undefined ? viewingParameter.max : '-'}
                        </div>
                      </div>
                      <div>
                        <Label>取值范围</Label>
                        <div className="field-value">
                          {viewingParameter.min !== undefined && viewingParameter.max !== undefined
                            ? `${viewingParameter.min} ~ ${viewingParameter.max}`
                            : '-'}
                        </div>
                      </div>
                    </>
                  )}
                </div>
              </div>

              {/* 选项列表（如果是select类型） */}
              {viewingParameter.type === 'select' && viewingParameter.options && viewingParameter.options.length > 0 && (
                <div>
                  <h3 className="mb-3 text-green-800">可选值</h3>
                  <div className="bg-gray-50 p-3 rounded border">
                    <div className="space-y-2">
                      {viewingParameter.options.map((option, index) => (
                        <div key={index} className="flex items-center justify-between p-2 bg-white rounded">
                          <span>{option.label}</span>
                          <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                            {option.value}
                          </code>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              )}

              {/* 参数描述 */}
              {viewingParameter.description && (
                <div>
                  <Label>参数描述</Label>
                  <div className="field-value bg-gray-50 p-3 rounded border">
                    {viewingParameter.description}
                  </div>
                </div>
              )}

              {/* 数据来源说明 */}
              <div className="bg-blue-50 p-3 rounded border border-blue-200">
                <div className="flex items-start gap-2">
                  <Info className="w-4 h-4 text-blue-600 mt-0.5" />
                  <p className="text-sm text-blue-900">
                    此参数配置来自AI系统-设备参数管理。如需修改参数定义，请前往AI系统进行操作。
                  </p>
                </div>
              </div>

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