'use client';

import React from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Search, BookOpen, Edit, Trash2 } from 'lucide-react';
import { CategoryDictionary } from '../types';

interface CategoryListProps {
  categories: CategoryDictionary[];
  searchKeyword: string;
  categoryFilter: string;
  onSearchChange: (keyword: string) => void;
  onCategoryFilterChange: (category: string) => void;
  onEdit: (category: CategoryDictionary) => void;
  onDelete: (id: string) => void;
}

export function CategoryList({
  categories,
  searchKeyword,
  categoryFilter,
  onSearchChange,
  onCategoryFilterChange,
  onEdit,
  onDelete,
}: CategoryListProps) {
  // 过滤字典
  const filteredCategories = categories.filter(category => {
    const matchKeyword = !searchKeyword ||
      category.name.includes(searchKeyword) ||
      category.code.includes(searchKeyword) ||
      category.label.includes(searchKeyword) ||
      category.value.includes(searchKeyword);
    const matchCategory = categoryFilter === 'all' || category.category === categoryFilter;
    return matchKeyword && matchCategory;
  });

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

  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: '审批状态',
      operation_type: '作业类型',
      other: '其他',
    };
    return labels[category] || category;
  };

  return (
    <div className="space-y-6">
      {/* 搜索和筛选 */}
      <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) => onSearchChange(e.target.value)}
              className="pl-10"
            />
          </div>
          <Select value={categoryFilter} onValueChange={onCategoryFilterChange}>
            <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="operation_type">作业类型</SelectItem>
              <SelectItem value="other">其他</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </Card>

      {/* 字典列表 */}
      {Object.entries(groupedCategories).map(([category, items]) => (
        <Card key={category}>
          <div className="p-4 border-b bg-muted/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((category) => (
                <TableRow key={category.id}>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <code className="text-xs bg-muted px-2 py-1 rounded">{category.code}</code>
                      {category.isSystem && (
                        <Badge variant="outline" className="text-xs">系统</Badge>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>
                    <div>
                      <div>{category.name}</div>
                      {category.description && (
                        <p className="text-xs text-muted-foreground">{category.description}</p>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>
                    <code className="text-xs">{category.value}</code>
                  </TableCell>
                  <TableCell>{category.label}</TableCell>
                  <TableCell>{category.sortOrder}</TableCell>
                  <TableCell>
                    {category.isActive ? (
                      <Badge className="bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300">启用</Badge>
                    ) : (
                      <Badge variant="outline">停用</Badge>
                    )}
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-1">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => onEdit(category)}
                      >
                        <Edit className="w-4 h-4" />
                      </Button>
                      {!category.isSystem && (
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => onDelete(category.id)}
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Card>
      ))}

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

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