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

interface MachineryType {
  id: string;
  name: string;
  code: string;
  description: string;
  count: number;
  createdAt: string;
  updatedAt: string;
}

const STORAGE_KEY = 'machinery_types';

export function MachineryTypeManagement() {
  const [types, setTypes] = useState<MachineryType[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [showDialog, setShowDialog] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [editingType, setEditingType] = useState<MachineryType | null>(null);
  const [deletingType, setDeletingType] = useState<MachineryType | null>(null);
  
  const [formData, setFormData] = useState({
    name: '',
    code: '',
    description: '',
  });

  // 初始化数据
  useEffect(() => {
    loadTypes();
  }, []);

  const loadTypes = () => {
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored) {
      setTypes(JSON.parse(stored));
    } else {
      // 初始化默认数据
      const defaultTypes: MachineryType[] = [
        {
          id: 'type-1',
          name: '拖拉机',
          code: 'TLJ',
          description: '用于农田耕作、运输等作业',
          count: 8,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'type-2',
          name: '收割机',
          code: 'SGJ',
          description: '用于农作物收获作业',
          count: 5,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'type-3',
          name: '播种机',
          code: 'BZJ',
          description: '用于农作物播种作业',
          count: 6,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: 'type-4',
          name: '植保机',
          code: 'ZBJ',
          description: '用于农作物病虫害防治',
          count: 4,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
      ];
      localStorage.setItem(STORAGE_KEY, JSON.stringify(defaultTypes));
      setTypes(defaultTypes);
    }
  };

  const saveTypes = (updatedTypes: MachineryType[]) => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(updatedTypes));
    setTypes(updatedTypes);
  };

  // 过滤类型
  const filteredTypes = types.filter(type =>
    type.name.includes(searchKeyword) ||
    type.code.includes(searchKeyword) ||
    type.description.includes(searchKeyword)
  );

  // 打开新增对话框
  const handleAdd = () => {
    setEditingType(null);
    setFormData({ name: '', code: '', description: '' });
    setShowDialog(true);
  };

  // 打开编辑对话框
  const handleEdit = (type: MachineryType) => {
    setEditingType(type);
    setFormData({
      name: type.name,
      code: type.code,
      description: type.description,
    });
    setShowDialog(true);
  };

  // 保存类型
  const handleSave = () => {
    if (!formData.name.trim()) {
      toast.error('请输入类型名称');
      return;
    }
    if (!formData.code.trim()) {
      toast.error('请输入类型编码');
      return;
    }

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

    if (editingType) {
      // 编辑
      const updatedTypes = types.map(type =>
        type.id === editingType.id
          ? { ...type, ...formData, updatedAt: now }
          : type
      );
      saveTypes(updatedTypes);
      toast.success('农机类型更新成功');
    } else {
      // 新增
      const newType: MachineryType = {
        id: `type-${Date.now()}`,
        ...formData,
        count: 0,
        createdAt: now,
        updatedAt: now,
      };
      saveTypes([...types, newType]);
      toast.success('农机类型添加成功');
    }

    setShowDialog(false);
  };

  // 打开删除确认对话框
  const handleDeleteClick = (type: MachineryType) => {
    setDeletingType(type);
    setShowDeleteDialog(true);
  };

  // 删除类型
  const handleDelete = () => {
    if (deletingType) {
      const updatedTypes = types.filter(type => type.id !== deletingType.id);
      saveTypes(updatedTypes);
      toast.success('农机类型删除成功');
      setShowDeleteDialog(false);
      setDeletingType(null);
    }
  };

  const formatDate = (dateString: string): string => {
    return new Date(dateString).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  return (
    <div className="space-y-6">
      {/* 搜索和操作栏 */}
      <Card className="p-4">
        <div className="flex gap-4">
          <div className="flex-1">
            <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>
          </div>
          <Button
            className="bg-success hover:bg-success/90"
            onClick={handleAdd}
          >
            <Plus className="w-4 h-4 mr-2" />
            新增类型
          </Button>
        </div>
      </Card>

      {/* 统计信息 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">类型总数</p>
              <p className="mt-2 text-2xl text-success">{types.length}</p>
            </div>
            <Tag className="w-12 h-12 text-success opacity-50" />
          </div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">设备总数</p>
              <p className="mt-2 text-2xl text-info">
                {types.reduce((sum, type) => sum + type.count, 0)}
              </p>
            </div>
            <Tag className="w-12 h-12 text-info opacity-50" />
          </div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">使用最多</p>
              <p className="mt-2 text-sm text-info">
                {types.length > 0
                  ? types.reduce((max, type) => (type.count > max.count ? type : max)).name
                  : '-'}
              </p>
            </div>
            <Tag className="w-12 h-12 text-info opacity-50" />
          </div>
        </Card>

        <Card className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">最近更新</p>
              <p className="mt-2 text-xs text-warning">
                {types.length > 0
                  ? new Date(Math.max(...types.map(t => new Date(t.updatedAt).getTime()))).toLocaleDateString('zh-CN')
                  : '-'}
              </p>
            </div>
            <Tag className="w-12 h-12 text-warning opacity-50" />
          </div>
        </Card>
      </div>

      {/* 类型列表 */}
      <Card>
        <div className="p-6">
          <h3 className="text-primary mb-4">农机类型列表</h3>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>类型编码</TableHead>
                <TableHead>类型名称</TableHead>
                <TableHead>描述</TableHead>
                <TableHead>设备数量</TableHead>
                <TableHead>更新时间</TableHead>
                <TableHead className="text-right">操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredTypes.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={6} className="text-center text-muted-foreground py-8">
                    {searchKeyword ? '未找到匹配的类型' : '暂无农机类型数据'}
                  </TableCell>
                </TableRow>
              ) : (
                filteredTypes.map((type) => (
                  <TableRow key={type.id}>
                    <TableCell>
                      <Badge variant="outline">{type.code}</Badge>
                    </TableCell>
                    <TableCell className="font-medium">{type.name}</TableCell>
                    <TableCell className="text-muted-foreground max-w-xs truncate">
                      {type.description || '-'}
                    </TableCell>
                    <TableCell>
                      <Badge variant="secondary">{type.count} 台</Badge>
                    </TableCell>
                    <TableCell className="text-muted-foreground text-sm">
                      {formatDate(type.updatedAt)}
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleEdit(type)}
                        >
                          <Edit className="w-4 h-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleDeleteClick(type)}
                        >
                          <Trash2 className="w-4 h-4 text-error" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </Card>

      {/* 新增/编辑对话框 */}
      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{editingType ? '编辑农机类型' : '新增农机类型'}</DialogTitle>
            <DialogDescription>
              {editingType ? '修改农机类型信息' : '添加新的农机类型'}
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="code">类型编码 *</Label>
              <Input
                id="code"
                placeholder="如：TLJ"
                value={formData.code}
                onChange={(e) => setFormData({ ...formData, code: e.target.value.toUpperCase() })}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="name">类型名称 *</Label>
              <Input
                id="name"
                placeholder="如：拖拉机"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="description">描述</Label>
              <Textarea
                id="description"
                placeholder="请输入类型描述..."
                rows={3}
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDialog(false)}>
              取消
            </Button>
            <Button className="bg-success hover:bg-success/90" onClick={handleSave}>
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除农机类型 <span className="font-semibold">"{deletingType?.name}"</span> 吗？
              {deletingType && deletingType.count > 0 && (
                <span className="block mt-2 text-warning">
                  注意：该类型下还有 {deletingType.count} 台设备！
                </span>
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction
              className="bg-error hover:bg-error/90"
              onClick={handleDelete}
            >
              删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
