"use client"

import React from "react";
import { useRoles, type Role } from "@/modules/users/hooks/useRoles";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useLanguage } from "@/providers/i18n-provider";


export type SelectRoleProps = {
  value: string;
  onValueChange: (value: string) => void;
  onBlur?: () => void;
  placeholder?: string;
  disabled?: boolean;
};

const SelectRole: React.FC<SelectRoleProps> = ({
  value,
  onValueChange,
  onBlur,
  placeholder = "Select Role",
  disabled = false,
}) => {
  const { languageCode } = useLanguage();
  const { data: roles, isLoading, isError } = useRoles();

  // Get role name based on locale
  const getRoleName = (role: Role) => {
    return languageCode === "ar" ? role.name_ar : role.name;
  };

  return (
    <Select
      onValueChange={onValueChange}
      value={value}
      disabled={disabled || isLoading}
    >
      <SelectTrigger onBlur={onBlur}>
        <SelectValue placeholder={placeholder} />
      </SelectTrigger>
      <SelectContent>
        {isLoading ? (
          <div className="py-6 text-center text-sm text-muted-foreground">
            Loading roles...
          </div>
        ) : isError ? (
          <div className="py-6 text-center text-sm text-destructive">
            Error loading roles
          </div>
        ) : !roles || roles.length === 0 ? (
          <div className="py-6 text-center text-sm text-muted-foreground">
            No roles available
          </div>
        ) : (
          <SelectGroup>
            {roles.map((role: Role) => (
              <SelectItem key={role.id} value={String(role.id)}>
                {getRoleName(role)}
              </SelectItem>
            ))}
          </SelectGroup>
        )}
      </SelectContent>
    </Select>
  );
};

export default SelectRole;
