import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Badge } from '../ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../ui/dialog';
import { Label } from '../ui/label';
import { Textarea } from '../ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Switch } from '../ui/switch';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { DataDictionary as DataDictionaryType } from '../../types/system-params';
import { Search, Plus, Edit, Trash2, BookOpen, Download, Upload } from 'lucide-react';
import { toast } from 'sonner@2.0.3';

export function DataDictionary() {
  const [dictionaries, setDictionaries] = useState<DataDictionaryType[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [categoryFilter, setCategoryFilter] = useState<string>('all');
  const [showDialog, setShowDialog] = useState(false);
  const [editingDict, setEditingDict] = useState<DataDictionaryType | null>(null);

  const [formData, setFormData] = useState({
    code: '',
    name: '',
    category: 'other',
    value: '',
    label: '',
    sortOrder: 0,
    description: '',
    isActive: true,
  });

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

  const loadDictionaries = () => {
    const data = localStorage.getItem('smart_agriculture_data_dictionary');
    if (data) {
      setDictionaries(JSON.parse(data));
    } else {
      const mockData: DataDictionaryType[] = [
        // 性别
        {
          id: 'dict-1',
          code: 'GENDER_MALE',
          name: '性别-男',
          category: 'gender',
          value: 'male',
          label: '男',
          sortOrder: 1,
          isSystem: true,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'dict-2',
          code: 'GENDER_FEMALE',
          name: '性别-女',
          category: 'gender',
          value: 'female',
          label: '女',
          sortOrder: 2,
          isSystem: true,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        // 状态
        {
          id: 'dict-3',
          code: 'STATUS_ACTIVE',
          name: '状态-激活',
          category: 'status',
          value: 'active',
          label: '激活',
          sortOrder: 1,
          isSystem: true,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'dict-4',
          code: 'STATUS_INACTIVE',
          name: '状态-停用',
          category: 'status',
          value: 'inactive',
          label: '停用',
          sortOrder: 2,
          isSystem: true,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        // 单位类型
        {
          id: 'dict-5',
          code: 'UNIT_AREA_MU',
          name: '面积单位-亩',
          category: 'unit',
          value: 'mu',
          label: '亩',
          sortOrder: 1,
          description: '中国传统面积单位',
          isSystem: false,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'dict-6',
          code: 'UNIT_AREA_HECTARE',
          name: '面积单位-公顷',
          category: 'unit',
          value: 'hectare',
          label: '公顷',
          sortOrder: 2,
          description: '国际通用面积单位',
          isSystem: false,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'dict-7',
          code: 'UNIT_WEIGHT_KG',
          name: '重量单位-千克',
          category: 'unit',
          value: 'kg',
          label: '千克',
          sortOrder: 3,
          isSystem: false,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'dict-8',
          code: 'UNIT_WEIGHT_TON',
          name: '重量单位-吨',
          category: 'unit',
          value: 'ton',
          label: '吨',
          sortOrder: 4,
          isSystem: false,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        // 天气
        {
          id: 'dict-9',
          code: 'WEATHER_SUNNY',
          name: '天气-晴',
          category: 'weather',
          value: 'sunny',
          label: '晴',
          sortOrder: 1,
          isSystem: false,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'dict-10',
          code: 'WEATHER_CLOUDY',
          name: '天气-多云',
          category: 'weather',
          value: 'cloudy',
          label: '多云',
          sortOrder: 2,
          isSystem: false,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'dict-11',
          code: 'WEATHER_RAINY',
          name: '天气-雨',
          category: 'weather',
          value: 'rainy',
          label: '雨',
          sortOrder: 3,
          isSystem: false,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        // 土壤类型
        {
          id: 'dict-12',
          code: 'SOIL_SANDY',
          name: '土壤-砂土',
          category: 'soil_type',
          value: 'sandy',
          label: '砂土',
          sortOrder: 1,
          description: '含砂粒较多的土壤',
          isSystem: false,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'dict-13',
          code: 'SOIL_LOAMY',
          name: '土壤-壤土',
          category: 'soil_type',
          value: 'loamy',
          label: '壤土',
          sortOrder: 2,
          description: '砂粘适中的土壤',
          isSystem: false,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'dict-14',
          code: 'SOIL_CLAY',
          name: '土壤-黏土',
          category: 'soil_type',
          value: 'clay',
          label: '黏土',
          sortOrder: 3,
          description: '含黏粒较多的土壤',
          isSystem: false,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        // 作业类型
        {
          id: 'dict-15',
          code: 'OPERATION_PLOWING',
          name: '作业类型-耕地',
          category: 'operation_type',
          value: 'plowing',
          label: '耕地',
          sortOrder: 1,
          description: '翻耕土地作业',
          isSystem: false,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'dict-16',
          code: 'OPERATION_SEEDING',
          name: '作业类型-播种',
          category: 'operation_type',
          value: 'seeding',
          label: '播种',
          sortOrder: 2,
          description: '播种作业',
          isSystem: false,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'dict-17',
          code: 'OPERATION_FERTILIZING',
          name: '作业类型-施肥',
          category: 'operation_type',
          value: 'fertilizing',
          label: '施肥',
          sortOrder: 3,
          description: '施肥作业',
          isSystem: false,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'dict-18',
          code: 'OPERATION_SPRAYING',
          name: '作业类型-喷药',
          category: 'operation_type',
          value: 'spraying',
          label: '喷药',
          sortOrder: 4,
          description: '喷洒农药作业',
          isSystem: false,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'dict-19',
          code: 'OPERATION_IRRIGATION',
          name: '作业类型-灌溉',
          category: 'operation_type',
          value: 'irrigation',
          label: '灌溉',
          sortOrder: 5,
          description: '灌溉作业',
          isSystem: false,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'dict-20',
          code: 'OPERATION_HARVESTING',
          name: '作业类型-收获',
          category: 'operation_type',
          value: 'harvesting',
          label: '收获',
          sortOrder: 6,
          description: '收获作业',
          isSystem: false,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'dict-21',
          code: 'OPERATION_WEEDING',
          name: '作业类型-除草',
          category: 'operation_type',
          value: 'weeding',
          label: '除草',
          sortOrder: 7,
          description: '除草作业',
          isSystem: false,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'dict-22',
          code: 'OPERATION_HARROWING',
          name: '作业类型-耙地',
          category: 'operation_type',
          value: 'harrowing',
          label: '耙地',
          sortOrder: 8,
          description: '耙地整地作业',
          isSystem: false,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'dict-23',
          code: 'OPERATION_TRANSPORT',
          name: '作业类型-运输',
          category: 'operation_type',
          value: 'transport',
          label: '运输',
          sortOrder: 9,
          description: '农产品运输作业',
          isSystem: false,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'dict-24',
          code: 'OPERATION_OTHER',
          name: '作业类型-其他',
          category: 'operation_type',
          value: 'other',
          label: '其他',
          sortOrder: 10,
          description: '其他农事作业',
          isSystem: false,
          isActive: true,
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
      ];
      localStorage.setItem('smart_agriculture_data_dictionary', JSON.stringify(mockData));
      setDictionaries(mockData);
    }
  };

  const saveDictionaries = (newDicts: DataDictionaryType[]) => {
    localStorage.setItem('smart_agriculture_data_dictionary', JSON.stringify(newDicts));
    setDictionaries(newDicts);
  };

  const filteredDictionaries = dictionaries.filter(dict => {
    const matchKeyword = !searchKeyword ||
      dict.name.includes(searchKeyword) ||
      dict.code.includes(searchKeyword) ||
      dict.label.includes(searchKeyword) ||
      dict.value.includes(searchKeyword);
    const matchCategory = categoryFilter === 'all' || dict.category === categoryFilter;
    return matchKeyword && matchCategory;
  });

  // 按分类分组
  const groupedDictionaries = filteredDictionaries.reduce((acc, dict) => {
    if (!acc[dict.category]) {
      acc[dict.category] = [];
    }
    acc[dict.category].push(dict);
    return acc;
  }, {} as Record<string, DataDictionaryType[]>);

  const handleAdd = () => {
    setEditingDict(null);
    setFormData({
      code: '',
      name: '',
      category: 'other',
      value: '',
      label: '',
      sortOrder: 0,
      description: '',
      isActive: true,
    });
    setShowDialog(true);
  };

  const handleEdit = (dict: DataDictionaryType) => {
    setEditingDict(dict);
    setFormData({
      code: dict.code,
      name: dict.name,
      category: dict.category,
      value: dict.value,
      label: dict.label,
      sortOrder: dict.sortOrder,
      description: dict.description || '',
      isActive: dict.isActive,
    });
    setShowDialog(true);
  };

  const handleDelete = (id: string) => {
    const dict = dictionaries.find(d => d.id === id);
    if (dict?.isSystem) {
      toast.error('系统内置字典不能删除');
      return;
    }

    const updated = dictionaries.filter(d => d.id !== id);
    saveDictionaries(updated);
    toast.success('删除成功');
  };

  const handleSave = () => {
    if (!formData.code.trim() || !formData.name.trim() || !formData.value.trim() || !formData.label.trim()) {
      toast.error('请填写必填项');
      return;
    }

    const now = new Date().toISOString();

    if (editingDict) {
      // 编辑
      const updated = dictionaries.map(dict =>
        dict.id === editingDict.id
          ? {
              ...dict,
              ...formData,
              updatedAt: now,
            }
          : dict
      );
      saveDictionaries(updated);
      toast.success('更新成功');
    } else {
      // 新增
      const newDict: DataDictionaryType = {
        id: `dict-${Date.now()}`,
        ...formData,
        isSystem: false,
        createdAt: now,
        updatedAt: now,
      };
      saveDictionaries([...dictionaries, newDict]);
      toast.success('添加成功');
    }

    setShowDialog(false);
  };

  const handleExport = () => {
    const dataStr = JSON.stringify(filteredDictionaries, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `data_dictionary_${new Date().getTime()}.json`;
    link.click();
    toast.success('导出成功');
  };

  const getCategoryLabel = (category: string) => {
    const labels: Record<string, string> = {
      gender: '性别',
      status: '状态',
      unit: '单位',
      weather: '天气',
      soil_type: '土壤类型',
      irrigation_method: '灌溉方式',
      fertilizer_type: '肥料类型',
      pesticide_type: '农药类型',
      task_status: '任务状态',
      task_priority: '任务优先级',
      approval_status: '审批状态',
      other: '其他',
    };
    return labels[category] || category;
  };

  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">集中管理系统内所有基础字典项</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={handleExport}>
            <Download className="w-4 h-4 mr-2" />
            导出
          </Button>
          <Button onClick={handleAdd}>
            <Plus className="w-4 h-4 mr-2" />
            新增字典
          </Button>
        </div>
      </div>

      {/* 搜索和筛选 */}
      <Card className="p-4">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <Input
              placeholder="搜索编码、名称、标签、值..."
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              className="pl-10"
            />
          </div>
          <Select value={categoryFilter} onValueChange={setCategoryFilter}>
            <SelectTrigger>
              <SelectValue placeholder="字典分类" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部分类</SelectItem>
              <SelectItem value="gender">性别</SelectItem>
              <SelectItem value="status">状态</SelectItem>
              <SelectItem value="unit">单位</SelectItem>
              <SelectItem value="weather">天气</SelectItem>
              <SelectItem value="soil_type">土壤类型</SelectItem>
              <SelectItem value="irrigation_method">灌溉方式</SelectItem>
              <SelectItem value="fertilizer_type">肥料类型</SelectItem>
              <SelectItem value="pesticide_type">农药类型</SelectItem>
              <SelectItem value="task_status">任务状态</SelectItem>
              <SelectItem value="task_priority">任务优先级</SelectItem>
              <SelectItem value="approval_status">审批状态</SelectItem>
              <SelectItem value="other">其他</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </Card>

      {/* 字典列表 */}
      {Object.entries(groupedDictionaries).map(([category, items]) => (
        <Card key={category}>
          <div className="p-4 border-b bg-gray-50">
            <h3 className="flex items-center gap-2">
              <BookOpen className="w-5 h-5 text-green-600" />
              {getCategoryLabel(category)}
              <Badge variant="outline">{items.length}</Badge>
            </h3>
          </div>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>编码</TableHead>
                <TableHead>名称</TableHead>
                <TableHead>值</TableHead>
                <TableHead>标签</TableHead>
                <TableHead>排序</TableHead>
                <TableHead>状态</TableHead>
                <TableHead>操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {items.sort((a, b) => a.sortOrder - b.sortOrder).map((dict) => (
                <TableRow key={dict.id}>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <code className="text-xs bg-gray-100 px-2 py-1 rounded">{dict.code}</code>
                      {dict.isSystem && (
                        <Badge variant="outline" className="text-xs">系统</Badge>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>
                    <div>
                      <div>{dict.name}</div>
                      {dict.description && (
                        <p className="text-xs text-muted-foreground">{dict.description}</p>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>
                    <code className="text-xs">{dict.value}</code>
                  </TableCell>
                  <TableCell>{dict.label}</TableCell>
                  <TableCell>{dict.sortOrder}</TableCell>
                  <TableCell>
                    {dict.isActive ? (
                      <Badge className="bg-green-100 text-green-700">启用</Badge>
                    ) : (
                      <Badge variant="outline">停用</Badge>
                    )}
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-1">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleEdit(dict)}
                      >
                        <Edit className="w-4 h-4" />
                      </Button>
                      {!dict.isSystem && (
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleDelete(dict.id)}
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Card>
      ))}

      {filteredDictionaries.length === 0 && (
        <Card className="p-12 text-center text-muted-foreground">
          暂无字典数据
        </Card>
      )}

      {/* 编辑对话框 */}
      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>
              {editingDict ? '编辑字典' : '新增字典'}
            </DialogTitle>
            <DialogDescription className="sr-only">
              {editingDict ? '编辑数据字典' : '添加新数据字典'}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>编码 *</Label>
                <Input
                  value={formData.code}
                  onChange={(e) => setFormData({ ...formData, code: e.target.value })}
                  placeholder="GENDER_MALE"
                  disabled={editingDict?.isSystem}
                />
              </div>
              <div>
                <Label>名称 *</Label>
                <Input
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="性别-男"
                />
              </div>
            </div>
            <div>
              <Label>字典分类 *</Label>
              <Select
                value={formData.category}
                onValueChange={(value) => setFormData({ ...formData, category: value })}
                disabled={editingDict?.isSystem}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="gender">性别</SelectItem>
                  <SelectItem value="status">状态</SelectItem>
                  <SelectItem value="unit">单位</SelectItem>
                  <SelectItem value="weather">天气</SelectItem>
                  <SelectItem value="soil_type">土壤类型</SelectItem>
                  <SelectItem value="irrigation_method">灌溉方式</SelectItem>
                  <SelectItem value="fertilizer_type">肥料类型</SelectItem>
                  <SelectItem value="pesticide_type">农药类型</SelectItem>
                  <SelectItem value="task_status">任务状态</SelectItem>
                  <SelectItem value="task_priority">任务优先级</SelectItem>
                  <SelectItem value="approval_status">审批状态</SelectItem>
                  <SelectItem value="other">其他</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>值 *</Label>
                <Input
                  value={formData.value}
                  onChange={(e) => setFormData({ ...formData, value: e.target.value })}
                  placeholder="male"
                  disabled={editingDict?.isSystem}
                />
                <p className="text-xs text-muted-foreground mt-1">
                  程序中使用的值，建议使用英文
                </p>
              </div>
              <div>
                <Label>标签 *</Label>
                <Input
                  value={formData.label}
                  onChange={(e) => setFormData({ ...formData, label: e.target.value })}
                  placeholder="男"
                />
                <p className="text-xs text-muted-foreground mt-1">
                  界面上显示的文本
                </p>
              </div>
            </div>
            <div>
              <Label>描述</Label>
              <Textarea
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                placeholder="请输入描述"
                rows={2}
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>排序</Label>
                <Input
                  type="number"
                  value={formData.sortOrder}
                  onChange={(e) => setFormData({ ...formData, sortOrder: parseInt(e.target.value) || 0 })}
                />
              </div>
              <div className="flex items-center justify-between pt-6">
                <Label>是否启用</Label>
                <Switch
                  checked={formData.isActive}
                  onCheckedChange={(checked) => setFormData({ ...formData, isActive: checked })}
                />
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDialog(false)}>
              取消
            </Button>
            <Button onClick={handleSave}>
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 使用说明 */}
      <Card className="p-4 bg-blue-50 border-blue-200">
        <h4 className="text-blue-900 mb-2">
          <BookOpen className="w-4 h-4 inline mr-2" />
          数据字典说明
        </h4>
        <ul className="space-y-1 text-sm text-blue-800">
          <li>• 数据字典用于存储系统中的枚举值和下拉选项</li>
          <li>• 编码应遵循命名规范，使用大写字母和下划线（如 GENDER_MALE）</li>
          <li>• 值（value）用于程序逻辑，标签（label）用于界面显示</li>
          <li>• 系统内置字典不可删除，但可以编辑标签和状态</li>
          <li>• 支持按分类分组展示，便于管理和查找</li>
        </ul>
      </Card>
    </div>
  );
}
