import React, { useEffect, useState } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@/components/ui/table';
import { useToast } from '@/components/ui/use-toast';
import { Loader2, Plus, Edit, Trash2, Settings } from 'lucide-react';
import type { RoleTagResponse, RoleTagRequest } from '../types';
import { getAllTags, createRoleTag, updateRoleTag, deleteRoleTag } from '../service';

interface TagDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSuccess: () => void;
}

/**
 * 标签管理对话框
 */
const TagDialog: React.FC<TagDialogProps> = ({
  open,
  onOpenChange,
  onSuccess
}) => {
  const { toast } = useToast();
  const [tags, setTags] = useState<RoleTagResponse[]>([]);
  const [loading, setLoading] = useState(false);
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [editingTag, setEditingTag] = useState<RoleTagResponse | null>(null);
  const [formData, setFormData] = useState<Partial<RoleTagRequest>>({
    color: '#1677ff',
  });

  useEffect(() => {
    if (open) {
      loadTags();
    }
  }, [open]);

  const loadTags = async () => {
    try {
      setLoading(true);
      const data = await getAllTags();
      setTags(data);
    } catch (error) {
      console.error('获取标签列表失败:', error);
      toast({
        title: '加载失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    } finally {
      setLoading(false);
    }
  };

  const handleAdd = () => {
    setEditingTag(null);
    setFormData({ color: '#1677ff' });
    setEditDialogOpen(true);
  };

  const handleEdit = (record: RoleTagResponse) => {
    setEditingTag(record);
    setFormData({
      name: record.name,
      color: record.color,
      description: record.description,
    });
    setEditDialogOpen(true);
  };

  const handleDelete = async (id: number, name: string) => {
    try {
      await deleteRoleTag(id);
      toast({
        title: '删除成功',
        description: `标签 "${name}" 已删除`,
      });
      loadTags();
    } catch (error) {
      console.error('删除失败:', error);
      toast({
        title: '删除失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    }
  };

  const handleSubmit = async () => {
    try {
      // 验证
      if (!formData.name?.trim()) {
        toast({
          title: '提示',
          description: '请输入标签名称',
          variant: 'destructive'
        });
        return;
      }

      if (!formData.color) {
        toast({
          title: '提示',
          description: '请选择标签颜色',
          variant: 'destructive'
        });
        return;
      }

      if (editingTag) {
        await updateRoleTag(editingTag.id, formData as RoleTagRequest);
        toast({
          title: '更新成功',
          description: `标签 "${formData.name}" 已更新`,
        });
      } else {
        await createRoleTag(formData as RoleTagRequest);
        toast({
          title: '创建成功',
          description: `标签 "${formData.name}" 已创建`,
        });
      }
      setEditDialogOpen(false);
      loadTags();
    } catch (error) {
      console.error('保存失败:', error);
      toast({
        title: '保存失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    }
  };

  return (
    <>
      {/* 标签列表对话框 */}
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="sm:max-w-[700px]">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Settings className="h-5 w-5" /> 标签管理
            </DialogTitle>
          </DialogHeader>
          <div className="py-4">
            <div className="mb-4">
              <Button onClick={handleAdd}>
                <Plus className="h-4 w-4 mr-2" />
                新建标签
              </Button>
            </div>
            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-[200px]">标签名称</TableHead>
                    <TableHead>描述</TableHead>
                    <TableHead className="w-[150px] text-right">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {loading ? (
                    <TableRow>
                      <TableCell colSpan={3} className="h-24 text-center">
                        <div className="flex items-center justify-center">
                          <Loader2 className="h-6 w-6 animate-spin mr-2" />
                          <span className="text-sm text-muted-foreground">加载中...</span>
                        </div>
                      </TableCell>
                    </TableRow>
                  ) : tags.length > 0 ? (
                    tags.map((tag) => (
                      <TableRow key={tag.id}>
                        <TableCell>
                          <Badge
                            variant="outline"
                            style={{ backgroundColor: tag.color, color: '#fff' }}
                          >
                            {tag.name}
                          </Badge>
                        </TableCell>
                        <TableCell className="max-w-[300px] truncate" title={tag.description}>
                          {tag.description || '-'}
                        </TableCell>
                        <TableCell className="text-right">
                          <div className="flex justify-end gap-2">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleEdit(tag)}
                              title="编辑"
                            >
                              <Edit className="h-4 w-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleDelete(tag.id, tag.name)}
                              className="text-red-600 hover:text-red-700 hover:bg-red-50"
                              title="删除"
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  ) : (
                    <TableRow>
                      <TableCell colSpan={3} className="h-24 text-center text-muted-foreground">
                        暂无标签数据
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </div>
          </div>
          <DialogFooter>
            <Button onClick={() => onOpenChange(false)}>关闭</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 标签编辑对话框 */}
      <Dialog open={editDialogOpen} onOpenChange={setEditDialogOpen}>
        <DialogContent className="sm:max-w-[400px]">
          <DialogHeader>
            <DialogTitle>{editingTag ? '编辑标签' : '新建标签'}</DialogTitle>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label htmlFor="name">标签名称 *</Label>
              <Input
                id="name"
                value={formData.name || ''}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                placeholder="请输入标签名称"
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="color">标签颜色 *</Label>
              <div className="flex items-center gap-2">
                <Input
                  id="color"
                  type="color"
                  value={formData.color || '#1677ff'}
                  onChange={(e) => setFormData({ ...formData, color: e.target.value })}
                  className="w-20 h-10"
                />
                <Badge
                  variant="outline"
                  style={{ backgroundColor: formData.color || '#1677ff', color: '#fff' }}
                >
                  预览效果
                </Badge>
              </div>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="description">描述</Label>
              <Textarea
                id="description"
                value={formData.description || ''}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                placeholder="请输入描述"
                rows={4}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setEditDialogOpen(false)}>
              取消
            </Button>
            <Button onClick={handleSubmit}>确定</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
};

export default TagDialog;

