import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { Users } from 'lucide-react';
import type { UserResponse, Role } from '../types';

interface AssignRolesDialogProps {
  open: boolean;
  record: UserResponse | null;
  allRoles: Role[];
  onOpenChange: (open: boolean) => void;
  onConfirm: (roleIds: number[]) => Promise<void>;
}

/**
 * 分配角色对话框
 */
const AssignRolesDialog: React.FC<AssignRolesDialogProps> = ({
  open,
  record,
  allRoles,
  onOpenChange,
  onConfirm,
}) => {
  const [selectedRoles, setSelectedRoles] = useState<number[]>([]);

  useEffect(() => {
    if (open && record) {
      setSelectedRoles(record.roles?.map(r => r.id) || []);
    }
  }, [open, record]);

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

  const handleSubmit = async () => {
    await onConfirm(selectedRoles);
  };

  if (!record) return null;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Users className="h-5 w-5" /> 分配角色
          </DialogTitle>
        </DialogHeader>
        <div className="grid gap-4 py-4">
          <div className="text-sm text-muted-foreground">
            为用户 "<span className="font-semibold text-foreground">{record.username}</span>" 分配角色
          </div>

          <div className="grid gap-2">
            <Label>选择角色</Label>
            <div className="space-y-3 max-h-[300px] overflow-y-auto border rounded-md p-3">
              {allRoles.length > 0 ? (
                allRoles.map(role => (
                  <div key={role.id} className="flex items-center space-x-2">
                    <Checkbox
                      id={`role-${role.id}`}
                      checked={selectedRoles.includes(role.id)}
                      onCheckedChange={() => handleToggle(role.id)}
                    />
                    <label
                      htmlFor={`role-${role.id}`}
                      className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
                    >
                      {role.name}
                      {role.description && (
                        <span className="text-muted-foreground ml-2">({role.description})</span>
                      )}
                    </label>
                  </div>
                ))
              ) : (
                <div className="text-sm text-muted-foreground text-center py-4">
                  暂无可用角色
                </div>
              )}
            </div>
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button onClick={handleSubmit}>确定</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default AssignRolesDialog;

