import { fetchRoleList } from '@/services/role';
import { fetchBindRoles, fetchUserDetail } from '@/services/user';
import { Button, Checkbox, Drawer, Spin, message } from 'antd';
import { useEffect, useState } from 'react';

interface BindRolesDrawerProps {
  userId: number;
  productCode: string;
  open: boolean;
  onClose: () => void;
}

export const BindRolesDrawer = ({ userId, productCode, open, onClose }: BindRolesDrawerProps) => {
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [roles, setRoles] = useState<API.RoleItem[]>([]);
  const [checkedIds, setCheckedIds] = useState<number[]>([]);

  useEffect(() => {
    if (!open) return;
    setLoading(true);
    Promise.all([fetchUserDetail({ id: userId }), fetchRoleList({ productCode, pageSize: 999 })])
      .then(([userRes, roleRes]) => {
        setRoles(roleRes.data ?? []);
        setCheckedIds(userRes.data?.roleIds ?? []);
      })
      .finally(() => setLoading(false));
  }, [open, userId, productCode]);

  const handleSave = async () => {
    setSaving(true);
    try {
      await fetchBindRoles({ userId, roleIds: checkedIds });
      message.success('保存成功');
      onClose();
    } finally {
      setSaving(false);
    }
  };

  const toggle = (id: number) =>
    setCheckedIds((prev) => (prev.includes(id) ? prev.filter((i) => i !== id) : [...prev, id]));

  return (
    <Drawer
      title="分配角色"
      open={open}
      onClose={onClose}
      width={400}
      extra={
        <Button type="primary" loading={saving} onClick={handleSave}>
          保存
        </Button>
      }
    >
      <Spin spinning={loading}>
        <div className="flex flex-col gap-2">
          {roles.map((r) => (
            <Checkbox key={r.id} checked={checkedIds.includes(r.id)} onChange={() => toggle(r.id)}>
              <span>{r.name}</span>
              <span className="text-xs text-gray-400 ml-2">级别 {r.permsLevel}</span>
            </Checkbox>
          ))}
          {roles.length === 0 && !loading && (
            <span className="text-gray-400 text-sm">该产品暂无角色</span>
          )}
        </div>
      </Spin>
    </Drawer>
  );
};
