import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Plus, Edit, Trash2, Save, X } from 'lucide-react';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../ui/dialog';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '../ui/alert-dialog';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { Textarea } from '../ui/textarea';
import { Switch } from '../ui/switch';
import { toast } from 'sonner@2.0.3';

// 参数定义接口
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;
}

// 设备类型接口
interface DeviceType {
  id: string;
  name: string;
  manufacturer?: string;
  model?: string;
  description?: string;
  parameterDefinitions: ParameterDefinition[];
  createdAt: string;
  updatedAt: string;
}

export function DeviceParameter() {
  const [deviceTypes, setDeviceTypes] = useState<DeviceType[]>([]);
  const [selectedType, setSelectedType] = useState<DeviceType | null>(null);
  const [showParamDialog, setShowParamDialog] = useState(false);
  const [editingParam, setEditingParam] = useState<ParameterDefinition | null>(null);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [pendingDeleteParam, setPendingDeleteParam] = useState<string | null>(null);

  // 表单状态
  const [paramForm, setParamForm] = useState({
    key: '',
    label: '',
    type: 'string' as 'string' | 'number' | 'boolean' | 'select',
    required: false,
    defaultValue: '',
    unit: '',
    min: '',
    max: '',
    description: '',
    options: [] as { label: string; value: string }[]
  });

  // 选项编辑状态
  const [optionLabel, setOptionLabel] = useState('');
  const [optionValue, setOptionValue] = useState('');

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

  const loadData = () => {
    const typesData = localStorage.getItem('smart_agriculture_ai_device_types');
    if (typesData) {
      const types = JSON.parse(typesData);
      setDeviceTypes(types);
      if (types.length > 0 && !selectedType) {
        setSelectedType(types[0]);
      }
    }
  };

  const handleTypeSelect = (typeId: string) => {
    const type = deviceTypes.find(t => t.id === typeId);
    if (type) {
      setSelectedType(type);
    }
  };

  const handleAddParam = () => {
    setEditingParam(null);
    setParamForm({
      key: '',
      label: '',
      type: 'string',
      required: false,
      defaultValue: '',
      unit: '',
      min: '',
      max: '',
      description: '',
      options: []
    });
    setShowParamDialog(true);
  };

  const handleEditParam = (param: ParameterDefinition) => {
    setEditingParam(param);
    setParamForm({
      key: param.key,
      label: param.label,
      type: param.type,
      required: param.required || false,
      defaultValue: param.defaultValue?.toString() || '',
      unit: param.unit || '',
      min: param.min?.toString() || '',
      max: param.max?.toString() || '',
      description: param.description || '',
      options: param.options || []
    });
    setShowParamDialog(true);
  };

  const handleDeleteParamClick = (paramKey: string) => {
    setPendingDeleteParam(paramKey);
    setShowDeleteConfirm(true);
  };

  const confirmDeleteParam = () => {
    if (!selectedType || !pendingDeleteParam) return;

    const updatedParams = selectedType.parameterDefinitions.filter(
      p => p.key !== pendingDeleteParam
    );

    const updatedType: DeviceType = {
      ...selectedType,
      parameterDefinitions: updatedParams,
      updatedAt: new Date().toISOString()
    };

    const updatedTypes = deviceTypes.map(t => 
      t.id === selectedType.id ? updatedType : t
    );

    setDeviceTypes(updatedTypes);
    setSelectedType(updatedType);
    localStorage.setItem('smart_agriculture_ai_device_types', JSON.stringify(updatedTypes));
    // 同步到农机负载管理使用的数据源
    localStorage.setItem('smart_agriculture_device_types', JSON.stringify(updatedTypes));
    
    toast.success('参数删除成功');
    setShowDeleteConfirm(false);
    setPendingDeleteParam(null);
  };

  const handleSaveParam = () => {
    if (!selectedType) return;

    // 验证必填项
    if (!paramForm.key.trim() || !paramForm.label.trim()) {
      toast.error('请填写参数标识和参数名称');
      return;
    }

    // 检查参数标识是否重复（编辑时除外）
    if (!editingParam || editingParam.key !== paramForm.key) {
      const exists = selectedType.parameterDefinitions.some(p => p.key === paramForm.key);
      if (exists) {
        toast.error('参数标识已存在');
        return;
      }
    }

    // 构建新参数
    const newParam: ParameterDefinition = {
      key: paramForm.key.trim(),
      label: paramForm.label.trim(),
      type: paramForm.type,
      required: paramForm.required,
      description: paramForm.description.trim()
    };

    // 根据类型设置默认值
    if (paramForm.type === 'number') {
      newParam.defaultValue = paramForm.defaultValue ? parseFloat(paramForm.defaultValue) : 0;
      if (paramForm.unit) newParam.unit = paramForm.unit;
      if (paramForm.min) newParam.min = parseFloat(paramForm.min);
      if (paramForm.max) newParam.max = parseFloat(paramForm.max);
    } else if (paramForm.type === 'boolean') {
      newParam.defaultValue = paramForm.defaultValue === 'true' || paramForm.defaultValue === true;
    } else if (paramForm.type === 'select') {
      newParam.options = paramForm.options;
      newParam.defaultValue = paramForm.defaultValue || (paramForm.options[0]?.value || '');
    } else {
      newParam.defaultValue = paramForm.defaultValue;
    }

    let updatedParams: ParameterDefinition[];
    if (editingParam) {
      // 编辑现有参数
      updatedParams = selectedType.parameterDefinitions.map(p =>
        p.key === editingParam.key ? newParam : p
      );
    } else {
      // 添加新参数
      updatedParams = [...selectedType.parameterDefinitions, newParam];
    }

    const updatedType: DeviceType = {
      ...selectedType,
      parameterDefinitions: updatedParams,
      updatedAt: new Date().toISOString()
    };

    const updatedTypes = deviceTypes.map(t => 
      t.id === selectedType.id ? updatedType : t
    );

    setDeviceTypes(updatedTypes);
    setSelectedType(updatedType);
    localStorage.setItem('smart_agriculture_ai_device_types', JSON.stringify(updatedTypes));
    // 同步到农机负载管理使用的数据源
    localStorage.setItem('smart_agriculture_device_types', JSON.stringify(updatedTypes));
    
    toast.success(editingParam ? '参数更新成功' : '参数添加成功');
    setShowParamDialog(false);
  };

  const handleAddOption = () => {
    if (!optionLabel.trim() || !optionValue.trim()) {
      toast.error('请填写选项标签和值');
      return;
    }

    const newOption = { label: optionLabel.trim(), value: optionValue.trim() };
    setParamForm({
      ...paramForm,
      options: [...paramForm.options, newOption]
    });
    setOptionLabel('');
    setOptionValue('');
  };

  const handleRemoveOption = (index: number) => {
    setParamForm({
      ...paramForm,
      options: paramForm.options.filter((_, i) => i !== index)
    });
  };

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

  const totalParams = deviceTypes.reduce((sum, type) => sum + (type.parameterDefinitions?.length || 0), 0);

  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>

      {/* 统计卡片 */}
      <div className="grid grid-cols-3 gap-4">
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">设备类型总数</div>
          <div className="mt-1">{deviceTypes.length}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">参数总数</div>
          <div className="mt-1 text-primary">{totalParams}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">当前类型参数</div>
          <div className="mt-1">
            {selectedType?.parameterDefinitions?.length || 0}
          </div>
        </Card>
      </div>

      <div className="grid grid-cols-12 gap-6">
        {/* 左侧：设备类型列表 */}
        <Card className="col-span-4 p-4">
          <h3 className="mb-4 text-primary">设备类型列表</h3>
          {deviceTypes.length === 0 ? (
            <div className="text-center text-muted-foreground py-8">
              暂无设备类型，请先在"设备类型管理"中添加
            </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-primary-muted border-2 border-primary'
                      : '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="flex items-center justify-between mb-4">
                <div>
                  <h3 className="text-primary">{selectedType.name} - 参数配置</h3>
                  <p className="text-sm text-muted-foreground mt-1">
                    {selectedType.description || '暂无描述'}
                  </p>
                </div>
                <Button onClick={handleAddParam}>
                  <Plus className="w-4 h-4 mr-2" />
                  新增参数
                </Button>
              </div>

              {selectedType.parameterDefinitions && selectedType.parameterDefinitions.length > 0 ? (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>参数标识</TableHead>
                      <TableHead>参数名称</TableHead>
                      <TableHead>类型</TableHead>
                      <TableHead>必填</TableHead>
                      <TableHead>默认值</TableHead>
                      <TableHead>单位/范围</TableHead>
                      <TableHead className="text-right">操作</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {selectedType.parameterDefinitions.map((param) => (
                      <TableRow key={param.key}>
                        <TableCell className="font-mono text-sm">{param.key}</TableCell>
                        <TableCell>{param.label}</TableCell>
                        <TableCell>
                          <Badge variant="outline">{getParamTypeLabel(param.type)}</Badge>
                        </TableCell>
                        <TableCell>
                          {param.required ? (
                            <Badge className="bg-error-muted text-error-muted-foreground">是</Badge>
                          ) : (
                            <span className="text-muted-foreground">否</span>
                          )}
                        </TableCell>
                        <TableCell>
                          {param.type === 'boolean' 
                            ? (param.defaultValue ? '是' : '否')
                            : (param.defaultValue?.toString() || '-')
                          }
                        </TableCell>
                        <TableCell>
                          {param.unit && <span>{param.unit}</span>}
                          {param.min !== undefined && param.max !== undefined && (
                            <span className="text-sm text-muted-foreground">
                              ({param.min}~{param.max})
                            </span>
                          )}
                          {param.type === 'select' && param.options && (
                            <span className="text-sm text-muted-foreground">
                              {param.options.length} 个选项
                            </span>
                          )}
                        </TableCell>
                        <TableCell className="text-right">
                          <div className="flex justify-end gap-2">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleEditParam(param)}
                              title="编辑"
                            >
                              <Edit className="w-4 h-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleDeleteParamClick(param.key)}
                              title="删除"
                            >
                              <Trash2 className="w-4 h-4 text-destructive" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              ) : (
                <div className="text-center text-muted-foreground py-12">
                  该设备类型暂无参数定义，点击"新增参数"开始配置
                </div>
              )}
            </>
          ) : (
            <div className="text-center text-muted-foreground py-12">
              请从左侧选择一个设备类型
            </div>
          )}
        </Card>
      </div>

      {/* 参数编辑对话框 */}
      <Dialog open={showParamDialog} onOpenChange={setShowParamDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editingParam ? '编辑参数' : '新增参数'}</DialogTitle>
            <DialogDescription>
              为 {selectedType?.name} 配置参数定义
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {/* 基本信息 */}
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="key">参数标识 *</Label>
                <Input
                  id="key"
                  value={paramForm.key}
                  onChange={(e) => setParamForm({ ...paramForm, key: e.target.value })}
                  placeholder="例如：temperature"
                  disabled={!!editingParam}
                />
                <p className="text-xs text-muted-foreground">
                  英文标识，用于数据传输
                </p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="label">参数名称 *</Label>
                <Input
                  id="label"
                  value={paramForm.label}
                  onChange={(e) => setParamForm({ ...paramForm, label: e.target.value })}
                  placeholder="例如：温度"
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="type">数据类型 *</Label>
                <Select
                  value={paramForm.type}
                  onValueChange={(value: any) => setParamForm({ ...paramForm, type: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="string">文本</SelectItem>
                    <SelectItem value="number">数字</SelectItem>
                    <SelectItem value="boolean">布尔</SelectItem>
                    <SelectItem value="select">选择</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="required">是否必填</Label>
                <div className="flex items-center space-x-2 h-10">
                  <Switch
                    id="required"
                    checked={paramForm.required}
                    onCheckedChange={(checked) => setParamForm({ ...paramForm, required: checked })}
                  />
                  <Label htmlFor="required" className="cursor-pointer">
                    {paramForm.required ? '必填' : '选填'}
                  </Label>
                </div>
              </div>
            </div>

            {/* 根据类型显示不同字段 */}
            {paramForm.type === 'number' && (
              <div className="grid grid-cols-3 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="unit">单位</Label>
                  <Input
                    id="unit"
                    value={paramForm.unit}
                    onChange={(e) => setParamForm({ ...paramForm, unit: e.target.value })}
                    placeholder="例如：°C"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="min">最小值</Label>
                  <Input
                    id="min"
                    type="number"
                    value={paramForm.min}
                    onChange={(e) => setParamForm({ ...paramForm, min: e.target.value })}
                    placeholder="最小值"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="max">最大值</Label>
                  <Input
                    id="max"
                    type="number"
                    value={paramForm.max}
                    onChange={(e) => setParamForm({ ...paramForm, max: e.target.value })}
                    placeholder="最大值"
                  />
                </div>
              </div>
            )}

            {/* 选择类型的选项配置 */}
            {paramForm.type === 'select' && (
              <div className="space-y-2">
                <Label>选项配置</Label>
                <div className="border rounded-lg p-4 space-y-3">
                  <div className="flex gap-2">
                    <Input
                      value={optionLabel}
                      onChange={(e) => setOptionLabel(e.target.value)}
                      placeholder="选项标签（显示文本）"
                      className="flex-1"
                    />
                    <Input
                      value={optionValue}
                      onChange={(e) => setOptionValue(e.target.value)}
                      placeholder="选项值"
                      className="flex-1"
                    />
                    <Button onClick={handleAddOption} size="sm">
                      <Plus className="w-4 h-4" />
                    </Button>
                  </div>

                  {paramForm.options.length > 0 && (
                    <div className="space-y-2">
                      <p className="text-sm text-muted-foreground">已添加的选项：</p>
                      {paramForm.options.map((option, index) => (
                        <div key={index} className="flex items-center justify-between p-2 bg-muted rounded">
                          <span className="text-sm">
                            {option.label} <span className="text-muted-foreground">({option.value})</span>
                          </span>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleRemoveOption(index)}
                          >
                            <X className="w-4 h-4" />
                          </Button>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            )}

            {/* 默认值 */}
            <div className="space-y-2">
              <Label htmlFor="defaultValue">默认值</Label>
              {paramForm.type === 'boolean' ? (
                <Select
                  value={paramForm.defaultValue?.toString() || 'false'}
                  onValueChange={(value) => setParamForm({ ...paramForm, defaultValue: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="true">是</SelectItem>
                    <SelectItem value="false">否</SelectItem>
                  </SelectContent>
                </Select>
              ) : paramForm.type === 'select' && paramForm.options.length > 0 ? (
                <Select
                  value={paramForm.defaultValue}
                  onValueChange={(value) => setParamForm({ ...paramForm, defaultValue: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {paramForm.options.map((option) => (
                      <SelectItem key={option.value} value={option.value}>
                        {option.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              ) : (
                <Input
                  id="defaultValue"
                  type={paramForm.type === 'number' ? 'number' : 'text'}
                  value={paramForm.defaultValue}
                  onChange={(e) => setParamForm({ ...paramForm, defaultValue: e.target.value })}
                  placeholder="参数默认值"
                />
              )}
            </div>

            {/* 描述 */}
            <div className="space-y-2">
              <Label htmlFor="description">描述</Label>
              <Textarea
                id="description"
                value={paramForm.description}
                onChange={(e) => setParamForm({ ...paramForm, description: e.target.value })}
                placeholder="参数说明..."
                rows={3}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowParamDialog(false)}>
              取消
            </Button>
            <Button onClick={handleSaveParam}>
              <Save className="w-4 h-4 mr-2" />
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <AlertDialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除此参数吗？此操作不可撤销。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction onClick={confirmDeleteParam}>删除</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
