import React, { useEffect, useState, useMemo } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogBody,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { useToast } from '@/components/ui/use-toast';
import { Loader2, Tag as TagIcon, Search } 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[]>([]);
  const [searchText, setSearchText] = useState('');

  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);
    }
  };

  // 过滤标签
  const filteredTags = useMemo(() => {
    if (!searchText.trim()) return allTags;
    const searchLower = searchText.toLowerCase();
    return allTags.filter(tag => 
      tag.name.toLowerCase().includes(searchLower) ||
      tag.description?.toLowerCase().includes(searchLower)
    );
  }, [allTags, searchText]);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[550px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <TagIcon className="h-5 w-5" />
            分配标签
          </DialogTitle>
        </DialogHeader>

        <DialogBody>
          {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>
          ) : (
            <div className="space-y-4">
              {/* 搜索框 */}
              {allTags.length > 0 && (
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <Input
                    placeholder="搜索标签名称或描述..."
                    value={searchText}
                    onChange={(e) => setSearchText(e.target.value)}
                    className="pl-9"
                  />
                </div>
              )}

              {/* 统计信息 */}
              {allTags.length > 0 && (
                <div className="flex items-center justify-between text-sm text-muted-foreground">
                  <span>共 {filteredTags.length} 个标签</span>
                  <span>已选 {selectedTagIds.length} 个</span>
                </div>
              )}

              {/* 标签列表 */}
              <div className="space-y-2 max-h-[320px] overflow-y-auto">
                {filteredTags.length > 0 ? (
                  filteredTags.map(tag => (
                    <div
                      key={tag.id}
                      className="flex items-center gap-3 p-2.5 rounded-md hover:bg-muted/50 transition-colors cursor-pointer"
                      onClick={() => handleToggle(tag.id)}
                    >
                      <Checkbox
                        id={`tag-${tag.id}`}
                        checked={selectedTagIds.includes(tag.id)}
                        onCheckedChange={() => handleToggle(tag.id)}
                        onClick={(e) => e.stopPropagation()}
                      />
                      <div className="flex-1 flex items-center gap-2">
                        <Badge
                          variant="outline"
                          style={{ backgroundColor: tag.color, color: '#fff' }}
                        >
                          {tag.name}
                        </Badge>
                        {tag.description && (
                          <span className="text-xs text-muted-foreground">
                            {tag.description}
                          </span>
                        )}
                      </div>
                    </div>
                  ))
                ) : searchText ? (
                  <div className="text-center py-8 text-muted-foreground">
                    <p className="text-sm">未找到匹配的标签</p>
                  </div>
                ) : (
                  <div className="text-center py-8 text-muted-foreground">
                    <p className="text-sm">暂无可用标签</p>
                  </div>
                )}
              </div>
            </div>
          )}
        </DialogBody>

        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={submitting}
          >
            取消
          </Button>
          <Button 
            onClick={handleSubmit} 
            disabled={submitting || loading}
          >
            {submitting ? '保存中...' : '确定'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default AssignTagDialog;

