'use client';

import { useEffect, useState } from 'react';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useTranslation } from '@/hooks/useTranslation';
import { getRoles, type Role } from '@/services/api/roles';

// 模块级缓存：角色列表跨 mount 复用，避免每次打开 dialog 都重发请求。
// 角色变更场景在 IAM Admin 上下文中是低频操作，缓存陈旧风险可接受。
let rolesCache: Promise<Role[]> | null = null;
const fetchRolesCached = () => {
  if (!rolesCache) rolesCache = getRoles().catch((e) => { rolesCache = null; throw e; });
  return rolesCache;
};

interface Props {
  value: string;
  onChange: (id: string) => void;
  disabled?: boolean;
  placeholder?: string;
}

export function RolePicker({ value, onChange, disabled, placeholder }: Props) {
  const { t } = useTranslation();
  const [roles, setRoles] = useState<Role[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchRolesCached()
      .then(setRoles)
      .finally(() => setLoading(false));
  }, []);

  const fallbackPlaceholder = loading ? t.iamAdmin.common.loading : t.iamAdmin.common.pickRole;

  return (
    <Select value={value} onValueChange={onChange} disabled={disabled || loading}>
      <SelectTrigger>
        <SelectValue placeholder={placeholder ?? fallbackPlaceholder} />
      </SelectTrigger>
      <SelectContent>
        {roles.map((r) => (
          <SelectItem key={r.id} value={r.id}>
            <span className="font-medium">{r.name}</span>
            <span className="ml-2 text-xs text-gray-500">{r.code}</span>
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}
