import React, { useEffect, useState } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { useToast } from '@/components/ui/use-toast';
import { Loader2, Tag as TagIcon } from 'lucide-react';
import type { RoleTagResponse } from '../types';
import { getAllTags, assignTags } from '../service';

interface AssignTagDialogProps {
  open: boolean;
  roleId: number;
  onOpenChange: (open: boolean) => void;
  onSuccess: () => void;
  selectedTags?: RoleTagResponse[];
}

/**
 * 分配标签对话框
 */
const AssignTagDialog: React.FC<AssignTagDialogProps> = ({
  open,
  roleId,
  onOpenChange,
  onSuccess,
  selectedTags = []
}) => {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [allTags, setAllTags] = useState<RoleTagResponse[]>([]);
  const [selectedTagIds, setSelectedTagIds] = useState<number[]>([]);

  useEffect(() => {
    if (open) {
      loadTags();
      setSelectedTagIds(selectedTags.map(tag => tag.id));
    }
  }, [open, selectedTags]);

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

  const handleToggle = (tagId: number) => {
    setSelectedTagIds(prev =>
      prev.includes(tagId)
        ? prev.filter(id => id !== tagId)
        : [...prev, tagId]
    );
  };

  const handleSubmit = async () => {
    setSubmitting(true);
    try {
      await assignTags(roleId, selectedTagIds);
      toast({
        title: '分配成功',
        description: '标签已成功分配给角色',
      });
      onSuccess();
    } catch (error) {
      console.error('分配标签失败:', error);
      toast({
        title: '分配失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <TagIcon className="h-5 w-5" /> 分配标签
          </DialogTitle>
        </DialogHeader>
        <div className="py-4">
          {loading ? (
            <div className="flex items-center justify-center py-8">
              <Loader2 className="h-6 w-6 animate-spin mr-2" />
              <span className="text-sm text-muted-foreground">加载中...</span>
            </div>
          ) : (
            <>
              <Label className="mb-3 block">选择标签</Label>
              <div className="space-y-3 max-h-[300px] overflow-y-auto border rounded-md p-4">
                {allTags.length > 0 ? (
                  allTags.map(tag => (
                    <div key={tag.id} className="flex items-center space-x-3">
                      <Checkbox
                        id={`tag-${tag.id}`}
                        checked={selectedTagIds.includes(tag.id)}
                        onCheckedChange={() => handleToggle(tag.id)}
                      />
                      <label
                        htmlFor={`tag-${tag.id}`}
                        className="flex items-center gap-2 text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer flex-1"
                      >
                        <Badge
                          variant="outline"
                          style={{ backgroundColor: tag.color, color: '#fff' }}
                        >
                          {tag.name}
                        </Badge>
                        {tag.description && (
                          <span className="text-muted-foreground text-xs">
                            {tag.description}
                          </span>
                        )}
                      </label>
                    </div>
                  ))
                ) : (
                  <div className="text-sm text-muted-foreground text-center py-4">
                    暂无可用标签
                  </div>
                )}
              </div>
            </>
          )}
        </div>
        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={submitting}
          >
            取消
          </Button>
          <Button onClick={handleSubmit} disabled={submitting || loading}>
            {submitting ? '保存中...' : '确定'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default AssignTagDialog;

