'use client';

import { useState, useEffect } from 'react';
import { getRoles, type Role } from '@/services/api/roles';
import { toast } from '@/lib/toast';

interface AssignRolesModalProps {
  user: {
    id: string;
    username: string;
    displayName: string;
    roles?: { role: { id: string; name: string; code: string } }[];
  };
  onClose: () => void;
  onSave: (userId: string, roleIds: string[]) => Promise<void>;
}

export function AssignRolesModal({ user, onClose, onSave }: AssignRolesModalProps) {
  const [roles, setRoles] = useState<Role[]>([]);
  const [selectedRoles, setSelectedRoles] = useState<Set<string>>(new Set());
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    loadRoles();
  }, []);

  const loadRoles = async () => {
    try {
      const data = await getRoles();
      setRoles(data);
      
      // 设置用户当前的角色
      const currentRoleIds = new Set(user.roles?.map(ur => ur.role.id) || []);
      setSelectedRoles(currentRoleIds);
    } catch (error) {
      console.error('Failed to load roles:', error);
    } finally {
      setLoading(false);
    }
  };

  const toggleRole = (roleId: string) => {
    const newSelected = new Set(selectedRoles);
    if (newSelected.has(roleId)) {
      newSelected.delete(roleId);
    } else {
      newSelected.add(roleId);
    }
    setSelectedRoles(newSelected);
  };

  const handleSave = async () => {
    try {
      setSaving(true);
      await onSave(user.id, Array.from(selectedRoles));
      onClose();
    } catch (error: any) {
      toast.error(error?.response?.data?.message || '分配失败');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg max-w-2xl w-full mx-4 max-h-[80vh] flex flex-col">
        {/* 头部 */}
        <div className="p-6 border-b border-gray-200">
          <h2 className="text-lg font-semibold text-gray-900">
            分配角色
          </h2>
          <p className="mt-1 text-sm text-gray-600">
            为用户 <strong>{user.displayName}</strong> ({user.username}) 分配角色
          </p>
        </div>

        {/* 内容 */}
        <div className="p-6 overflow-y-auto flex-1">
          {loading ? (
            <div className="flex items-center justify-center py-8">
              <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"></div>
            </div>
          ) : (
            <div className="space-y-2">
              {roles.map((role) => (
                <label
                  key={role.id}
                  className="flex items-start p-4 border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer"
                >
                  <input
                    type="checkbox"
                    checked={selectedRoles.has(role.id)}
                    onChange={() => toggleRole(role.id)}
                    className="mt-1 h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                  />
                  <div className="ml-3 flex-1">
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-medium text-gray-900">
                        {role.name}
                      </span>
                      <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800">
                        {role.code}
                      </span>
                      {role.isBuiltIn && (
                        <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800">
                          内置
                        </span>
                      )}
                    </div>
                    {role.description && (
                      <p className="mt-1 text-xs text-gray-600">
                        {role.description}
                      </p>
                    )}
                    <p className="mt-1 text-xs text-gray-500">
                      {role.permissionCount || 0} 个权限
                    </p>
                  </div>
                </label>
              ))}

              {roles.length === 0 && (
                <div className="text-center py-8 text-gray-500">
                  暂无可用角色
                </div>
              )}
            </div>
          )}
        </div>

        {/* 底部按钮 */}
        <div className="p-6 border-t border-gray-200 flex justify-end gap-3">
          <button
            onClick={onClose}
            className="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50"
            disabled={saving}
          >
            取消
          </button>
          <button
            onClick={handleSave}
            disabled={saving || loading}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {saving ? '保存中...' : '保存'}
          </button>
        </div>
      </div>
    </div>
  );
}
