import {
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@repo/shadcn-ui/components";

import { cn } from "@repo/shadcn-ui/lib/utils";
import { Control, FieldPath, FieldValues } from "react-hook-form";
import { useTranslation } from "../../locales/i18n.ts";

type SelectFieldProps<TFormValues extends FieldValues> = {
  control: Control<TFormValues>;
  name: FieldPath<TFormValues>;
  items: Array<{ value: string; label: string }>;
  label?: string;
  placeholder?: string;
  description?: string;
  disabled?: boolean;
  required?: boolean;
  readOnly?: boolean;
  className?: string;
};

export function SelectField<TFormValues extends FieldValues>({
  control,
  name,
  items,
  label,
  placeholder,
  description,
  disabled = false,
  required = false,
  readOnly = false,
  className,
}: SelectFieldProps<TFormValues>) {
  const { t } = useTranslation();
  const isDisabled = disabled || readOnly;

  return (
    <FormField
      control={control}
      name={name}
      render={({ field }) => (
        <FormItem className={cn("space-y-0", className)}>
          {label && (
            <div className='flex justify-between items-center'>
              <FormLabel className='m-0'>{label}</FormLabel>
              {required && <span className='text-xs text-destructive'>{t("common.required")}</span>}
            </div>
          )}
          <Select onValueChange={field.onChange} defaultValue={field.value} disabled={isDisabled}>
            <FormControl>
              <SelectTrigger className='w-full'>
                <SelectValue placeholder={placeholder} />
              </SelectTrigger>
            </FormControl>
            <SelectContent>
              {items.map((item) => (
                <SelectItem key={`key-${item.value}`} value={item.value}>
                  {item.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>

          <FormDescription
            className={cn("text-xs text-muted-foreground", !description && "invisible")}
          >
            {description || "\u00A0"}
          </FormDescription>
          <FormMessage />
        </FormItem>
      )}
    />
  );
}
