import {
  Field,
  FieldDescription,
  FieldError,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@repo/shadcn-ui/components";
import { cn } from "@repo/shadcn-ui/lib/utils";
import React from "react";
import { Controller, type FieldPath, type FieldValues, useFormContext } from "react-hook-form";

import { FormFieldLabel } from "./form-field-label.tsx";

interface SelectFieldItem {
  value: string;
  label: string;
}

type SelectFieldProps<TFormValues extends FieldValues> = {
  name: FieldPath<TFormValues>;

  label?: string;
  description?: string;

  disabled?: boolean;
  required?: boolean;
  readOnly?: boolean;

  placeholder?: string;
  items?: SelectFieldItem[];

  orientation?: "vertical" | "horizontal" | "responsive";

  className?: string;
  inputClassName?: string;
};

export function SelectField<TFormValues extends FieldValues>({
  name,

  label,
  description,

  disabled = false,
  required = false,
  readOnly = false,

  placeholder,
  items = [],

  orientation = "vertical",

  className,
  inputClassName,
}: SelectFieldProps<TFormValues>) {
  const triggerId = React.useId();
  const { control, formState } = useFormContext<TFormValues>();
  const isDisabled = Boolean(disabled || readOnly || formState.isSubmitting);

  return (
    <Controller
      control={control}
      name={name}
      render={({ field, fieldState }) => {
        const fieldValue = typeof field.value === "string" ? field.value.trim() : "";

        const normalizedItems =
          fieldValue && !items.some((item) => item.value === fieldValue)
            ? [{ value: fieldValue, label: fieldValue }, ...items]
            : items;

        return (
          <Field
            className={cn("gap-1", className)}
            data-invalid={fieldState.invalid}
            orientation={orientation}
          >
            {label ? (
              <FormFieldLabel htmlFor={triggerId} required={required}>
                {label}
              </FormFieldLabel>
            ) : null}

            <Select
              disabled={isDisabled}
              onValueChange={field.onChange}
              value={field.value ?? undefined}
            >
              <SelectTrigger
                aria-invalid={fieldState.invalid}
                aria-required={required}
                className={cn(
                  "bg-muted/50 font-medium",
                  "hover:border-ring hover:ring-ring/20 hover:ring-[3px]",
                  "focus-visible:border-ring focus-visible:ring-ring/60 focus-visible:ring-[3px]",
                  "placeholder:text-muted-foreground/50",
                  inputClassName
                )}
                id={triggerId}
              >
                <SelectValue
                  className={"placeholder:font-normal placeholder:italic"}
                  placeholder={placeholder}
                />
              </SelectTrigger>
              <SelectContent>
                {normalizedItems.map((item) => (
                  <SelectItem key={`key-${item.value}`} value={item.value}>
                    {item.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            {description ? (
              <FieldDescription>{description}</FieldDescription>
            ) : (
              <div aria-hidden="true" className="min-h-5" />
            )}
            <FieldError errors={[fieldState.error]} />
          </Field>
        );
      }}
    />
  );
}
