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 { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '../ui/alert-dialog';
import { Label } from '../ui/label';
import { Textarea } from '../ui/textarea';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { Search, Plus, Edit, Trash2, BookOpen, X, ArrowUp, ArrowDown } from 'lucide-react';
import { toast } from 'sonner@2.0.3';

// 数据字典组类型
interface DictionaryGroup {
  id: string;
  code: string;
  name: string;
  description?: string;
  items: DictionaryItem[];
  createdAt: string;
  updatedAt: string;
}

// 字典项类型
interface DictionaryItem {
  id: string;
  value: string;
  label: string;
  sortOrder: number;
  isSystem?: boolean;
}

export function DataDictionary() {
  const [dictionaryGroups, setDictionaryGroups] = useState<DictionaryGroup[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [showDialog, setShowDialog] = useState(false);
  const [editingGroup, setEditingGroup] = useState<DictionaryGroup | null>(null);
  const [deletingGroup, setDeletingGroup] = useState<DictionaryGroup | null>(null);

  const [formData, setFormData] = useState({
    code: '',
    name: '',
    description: '',
  });

  // 批量编辑的字典项列表
  type BatchItem = {
    id: string;
    originalId?: string;
    value: string;
    label: string;
    sortOrder: number;
    isSystem?: boolean;
  };

  const [batchItems, setBatchItems] = useState<BatchItem[]>([
    { id: '1', value: '', label: '', sortOrder: 1 }
  ]);

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

  const loadDictionaryGroups = () => {
    const data = localStorage.getItem('smart_agriculture_dictionary_groups');
    if (data) {
      setDictionaryGroups(JSON.parse(data));
    } else {
      const mockData: DictionaryGroup[] = [
        {
          id: 'group-1',
          code: 'GENDER',
          name: '性别',
          description: '人员性别分类',
          items: [
            { id: 'item-1', value: 'male', label: '男', sortOrder: 1, isSystem: true },
            { id: 'item-2', value: 'female', label: '女', sortOrder: 2, isSystem: true },
          ],
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'group-2',
          code: 'STATUS',
          name: '状态',
          description: '通用状态分类',
          items: [
            { id: 'item-3', value: 'active', label: '启用', sortOrder: 1, isSystem: true },
            { id: 'item-4', value: 'inactive', label: '停用', sortOrder: 2, isSystem: true },
          ],
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'group-3',
          code: 'CROP_TYPE',
          name: '作物类型',
          description: '农作物分类',
          items: [
            { id: 'item-5', value: 'wheat', label: '小麦', sortOrder: 1 },
            { id: 'item-6', value: 'rice', label: '水稻', sortOrder: 2 },
            { id: 'item-7', value: 'corn', label: '玉米', sortOrder: 3 },
          ],
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
        {
          id: 'group-4',
          code: 'UNIT',
          name: '单位',
          description: '计量单位',
          items: [
            { id: 'item-8', value: 'kg', label: '千克', sortOrder: 1 },
            { id: 'item-9', value: 'ton', label: '吨', sortOrder: 2 },
            { id: 'item-10', value: 'm', label: '米', sortOrder: 3 },
            { id: 'item-11', value: 'ha', label: '公顷', sortOrder: 4 },
          ],
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
        },
      ];
      saveDictionaryGroups(mockData);
    }
  };

  const saveDictionaryGroups = (groups: DictionaryGroup[]) => {
    setDictionaryGroups(groups);
    localStorage.setItem('smart_agriculture_dictionary_groups', JSON.stringify(groups));
  };

  // 筛选字典组
  const filteredGroups = dictionaryGroups.filter(group => {
    if (!searchKeyword) return true;
    const keyword = searchKeyword.toLowerCase();
    return (
      group.code.toLowerCase().includes(keyword) ||
      group.name.toLowerCase().includes(keyword) ||
      group.description?.toLowerCase().includes(keyword) ||
      group.items.some(item => 
        item.value.toLowerCase().includes(keyword) ||
        item.label.toLowerCase().includes(keyword)
      )
    );
  });

  const handleAdd = () => {
    setEditingGroup(null);
    setFormData({
      code: '',
      name: '',
      description: '',
    });
    setBatchItems([{ id: '1', value: '', label: '', sortOrder: 1 }]);
    setShowDialog(true);
  };

  const handleEdit = (group: DictionaryGroup) => {
    setEditingGroup(group);
    setFormData({
      code: group.code,
      name: group.name,
      description: group.description || '',
    });

    // 加载现有字典项
    const items: BatchItem[] = group.items
      .sort((a, b) => a.sortOrder - b.sortOrder)
      .map((item) => ({
        id: item.id,
        originalId: item.id,
        value: item.value,
        label: item.label,
        sortOrder: item.sortOrder,
        isSystem: item.isSystem,
      }));

    setBatchItems(items);
    setShowDialog(true);
  };

  const handleDelete = (group: DictionaryGroup) => {
    setDeletingGroup(group);
  };

  const confirmDelete = () => {
    if (!deletingGroup) return;

    // 检查是否有系统字典项
    const hasSystemItems = deletingGroup.items.some(item => item.isSystem);
    if (hasSystemItems) {
      toast.error('该字典包含系统内置项，不能删除');
      setDeletingGroup(null);
      return;
    }

    const updated = dictionaryGroups.filter(g => g.id !== deletingGroup.id);
    saveDictionaryGroups(updated);
    toast.success('删除成功');
    setDeletingGroup(null);
  };

  const handleSave = () => {
    const now = new Date().toISOString();

    // 验证基础信息
    if (!formData.code.trim() || !formData.name.trim()) {
      toast.error('请填写编码和名称');
      return;
    }

    // 验证字典项
    const validItems = batchItems.filter(item => item.value.trim() && item.label.trim());
    if (validItems.length === 0) {
      toast.error('请至少添加一个有效的字典项');
      return;
    }

    // 检查编码是否重复
    if (!editingGroup) {
      const exists = dictionaryGroups.some(g => g.code === formData.code);
      if (exists) {
        toast.error('编码已存在');
        return;
      }
    } else {
      const exists = dictionaryGroups.some(g => g.code === formData.code && g.id !== editingGroup.id);
      if (exists) {
        toast.error('编码已存在');
        return;
      }
    }

    if (editingGroup) {
      // 编辑模式
      const items: DictionaryItem[] = validItems.map((item) => ({
        id: item.originalId || `item-${Date.now()}-${Math.random()}`,
        value: item.value,
        label: item.label,
        sortOrder: item.sortOrder,
        isSystem: item.isSystem,
      }));

      const updated = dictionaryGroups.map(g =>
        g.id === editingGroup.id
          ? {
              ...g,
              code: formData.code,
              name: formData.name,
              description: formData.description,
              items: items,
              updatedAt: now,
            }
          : g
      );

      saveDictionaryGroups(updated);
      toast.success('更新成功');
    } else {
      // 新增模式
      const items: DictionaryItem[] = validItems.map((item, index) => ({
        id: `item-${Date.now()}-${index}`,
        value: item.value,
        label: item.label,
        sortOrder: item.sortOrder,
      }));

      const newGroup: DictionaryGroup = {
        id: `group-${Date.now()}`,
        code: formData.code,
        name: formData.name,
        description: formData.description,
        items: items,
        createdAt: now,
        updatedAt: now,
      };

      saveDictionaryGroups([...dictionaryGroups, newGroup]);
      toast.success(`成功添加字典组：${formData.name}`);
    }

    setShowDialog(false);
  };

  // 添加字典项
  const handleAddBatchItem = () => {
    const maxOrder = Math.max(...batchItems.map(item => item.sortOrder), 0);
    setBatchItems([
      ...batchItems,
      { id: Date.now().toString(), value: '', label: '', sortOrder: maxOrder + 1 }
    ]);
  };

  // 删除字典项
  const handleRemoveBatchItem = (id: string) => {
    const item = batchItems.find(i => i.id === id);

    if (item?.isSystem) {
      toast.error('系统内置项不能删除');
      return;
    }

    if (batchItems.length <= 1) {
      toast.error('至少保留一个字典项');
      return;
    }

    setBatchItems(batchItems.filter(item => item.id !== id));
  };

  // 更新字典项
  const handleUpdateBatchItem = (id: string, field: 'value' | 'label' | 'sortOrder', value: string | number) => {
    setBatchItems(batchItems.map(item =>
      item.id === id ? { ...item, [field]: value } : item
    ));
  };

  // 移动字典项
  const handleMoveBatchItem = (index: number, direction: 'up' | 'down') => {
    const newItems = [...batchItems];
    const targetIndex = direction === 'up' ? index - 1 : index + 1;

    if (targetIndex < 0 || targetIndex >= newItems.length) return;

    [newItems[index], newItems[targetIndex]] = [newItems[targetIndex], newItems[index]];

    newItems.forEach((item, idx) => {
      item.sortOrder = idx + 1;
    });

    setBatchItems(newItems);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800 dark:text-green-400">数据字典</h2>
          <p className="text-muted-foreground">管理系统内所有数据字典</p>
        </div>
        <Button onClick={handleAdd}>
          <Plus className="w-4 h-4 mr-2" />
          新增字典
        </Button>
      </div>

      {/* 搜索 */}
      <Card className="p-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>
      </Card>

      {/* 字典列表 */}
      {filteredGroups.map((group) => (
        <Card key={group.id}>
          <div className="p-4 border-b bg-muted/30">
            <div className="flex items-center justify-between">
              <div className="flex-1">
                <div className="flex items-center gap-3">
                  <BookOpen className="w-5 h-5 text-green-600 dark:text-green-400" />
                  <div>
                    <div className="flex items-center gap-2">
                      <h3>{group.name}</h3>
                      <code className="text-xs bg-muted px-2 py-1 rounded">{group.code}</code>
                      <Badge variant="outline">{group.items.length}项</Badge>
                    </div>
                    {group.description && (
                      <p className="text-sm text-muted-foreground mt-1">{group.description}</p>
                    )}
                  </div>
                </div>
              </div>
              <div className="flex gap-2">
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => handleEdit(group)}
                  title="编辑字典"
                >
                  <Edit className="w-4 h-4" />
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => handleDelete(group)}
                  title="删除字典"
                >
                  <Trash2 className="w-4 h-4" />
                </Button>
              </div>
            </div>
          </div>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="bg-muted/30 w-16">排序</TableHead>
                <TableHead className="bg-muted/30">值</TableHead>
                <TableHead className="bg-muted/30">标签</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {group.items.sort((a, b) => a.sortOrder - b.sortOrder).map((item) => (
                <TableRow key={item.id}>
                  <TableCell className="text-center">{item.sortOrder}</TableCell>
                  <TableCell>
                    <code className="text-xs">{item.value}</code>
                  </TableCell>
                  <TableCell>{item.label}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Card>
      ))}

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

      {/* 编辑对话框 */}
      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {editingGroup ? `编辑字典：${editingGroup.name}` : '新增字典'}
            </DialogTitle>
            <DialogDescription className="sr-only">
              {editingGroup ? '编辑数据字典' : '新增数据字典'}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            {/* 基础信息 */}
            <Card className="p-4 bg-muted/50">
              <h4 className="mb-3">基础信息</h4>
              <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.toUpperCase() })}
                      placeholder="CROP_TYPE"
                      disabled={editingGroup?.items.some(i => i.isSystem)}
                    />
                    <p className="text-xs text-muted-foreground mt-1">
                      使用大写字母和下划线
                    </p>
                  </div>
                  <div>
                    <Label>名称 *</Label>
                    <Input
                      value={formData.name}
                      onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                      placeholder="作物类型"
                    />
                  </div>
                </div>
                <div>
                  <Label>描述</Label>
                  <Textarea
                    value={formData.description}
                    onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                    placeholder="字典用途说明..."
                    rows={2}
                  />
                </div>
              </div>
            </Card>

            {/* 字典项列表 */}
            <Card className="p-4">
              <div className="flex items-center justify-between mb-3">
                <h4>字典项列表</h4>
                <Button onClick={handleAddBatchItem} size="sm">
                  <Plus className="w-4 h-4 mr-1" />
                  添加项
                </Button>
              </div>
              
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="bg-muted/30 w-16">排序</TableHead>
                    <TableHead className="bg-muted/30">值 *</TableHead>
                    <TableHead className="bg-muted/30">标签 *</TableHead>
                    <TableHead className="bg-muted/30 w-20 text-center">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {batchItems.map((item, index) => (
                    <TableRow key={item.id}>
                      {/* 排序号 */}
                      <TableCell>
                        <Input
                          type="number"
                          value={item.sortOrder}
                          onChange={(e) => handleUpdateBatchItem(item.id, 'sortOrder', parseInt(e.target.value) || 1)}
                          className="text-center w-16"
                          min={1}
                        />
                      </TableCell>

                      {/* 值 */}
                      <TableCell>
                        <Input
                          value={item.value}
                          onChange={(e) => handleUpdateBatchItem(item.id, 'value', e.target.value)}
                          placeholder="wheat"
                          disabled={item.isSystem}
                        />
                      </TableCell>

                      {/* 标签 */}
                      <TableCell>
                        <Input
                          value={item.label}
                          onChange={(e) => handleUpdateBatchItem(item.id, 'label', e.target.value)}
                          placeholder="小麦"
                        />
                      </TableCell>

                      {/* 操作 */}
                      <TableCell>
                        <div className="flex items-center justify-center gap-1">
                          <Button
                            size="sm"
                            variant="ghost"
                            className="h-7 w-7 p-0"
                            onClick={() => handleMoveBatchItem(index, 'up')}
                            disabled={index === 0}
                            title="上移"
                          >
                            <ArrowUp className="w-3 h-3" />
                          </Button>
                          <Button
                            size="sm"
                            variant="ghost"
                            className="h-7 w-7 p-0"
                            onClick={() => handleMoveBatchItem(index, 'down')}
                            disabled={index === batchItems.length - 1}
                            title="下移"
                          >
                            <ArrowDown className="w-3 h-3" />
                          </Button>
                          <Button
                            size="sm"
                            variant="ghost"
                            className="h-7 w-7 p-0"
                            onClick={() => handleRemoveBatchItem(item.id)}
                            disabled={batchItems.length <= 1 || item.isSystem}
                            title={item.isSystem ? '系统项不能删除' : '删除此项'}
                          >
                            <X className="w-3 h-3" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>

              <div className="text-xs text-muted-foreground bg-blue-50 dark:bg-blue-950/30 p-3 rounded border border-blue-200 dark:border-blue-900 mt-3">
                <p className="text-blue-800 dark:text-blue-300">
                  💡 <strong>使用说明：</strong>
                </p>
                <ul className="mt-1 space-y-1 text-blue-700 dark:text-blue-400">
                  <li>• 值（value）：用于程序逻辑，建议使用英文</li>
                  <li>• 标签（label）：用于界面显示，使用中文</li>
                  <li>• 使用上下箭头调整字典项顺序</li>
                  <li>• 系统内置项不可删除或修改值，但可以修改标签</li>
                </ul>
              </div>
            </Card>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDialog(false)}>
              取消
            </Button>
            <Button onClick={handleSave}>
              {editingGroup
                ? '保存'
                : `保存（${batchItems.filter(i => i.value && i.label).length}项）`
              }
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <AlertDialog open={!!deletingGroup} onOpenChange={() => setDeletingGroup(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              您确定要删除字典 <strong>"{deletingGroup?.name}"</strong> 吗？
              <br />
              编码：<code className="bg-muted px-2 py-1 rounded text-xs">{deletingGroup?.code}</code>
              <br />
              <br />
              此操作将删除该字典及其下所有 <strong>{deletingGroup?.items.length}</strong> 个字典项，且无法恢复。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction onClick={confirmDelete} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
              确认删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 使用说明 */}
      <Card className="p-4 bg-blue-50 dark:bg-blue-950/30 border-blue-200 dark:border-blue-900">
        <h4 className="text-blue-900 dark:text-blue-400 mb-2">
          <BookOpen className="w-4 h-4 inline mr-2" />
          数据字典说明
        </h4>
        <ul className="space-y-1 text-sm text-blue-800 dark:text-blue-300">
          <li>• <strong>字典组：</strong>由编码、名称、描述和字典项列表组成</li>
          <li>• <strong>编码：</strong>唯一标识，使用大写字母和下划线，如 CROP_TYPE</li>
          <li>• <strong>字典项：</strong>包含值（程序使用）和标签（界面显示）</li>
          <li>• <strong>系统字典：</strong>系统内置字典不可删除，字典项值不可修改</li>
          <li>• <strong>删除操作：</strong>删除字典时会二次确认，包含系统项的字典不可删除</li>
        </ul>
      </Card>
    </div>
  );
}
