import { CustomerModalSelector } from "@erp/customers/components";
import { Field, FieldLabel } from "@repo/shadcn-ui/components";
import { cn } from '@repo/shadcn-ui/lib/utils';
import { CustomerSummary } from 'node_modules/@erp/customers/src/web/schemas';

import { Control, Controller, FieldPath, FieldValues } from "react-hook-form";

type CustomerModalSelectorFieldProps<TFormValues extends FieldValues> = {
  control: Control<TFormValues>;
  name: FieldPath<TFormValues>;

  label?: string;
  description?: string;

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

  disabled?: boolean;
  required?: boolean;
  readOnly?: boolean;
  className?: string;
  initialRecipient?: unknown;
};

export function RecipientModalSelectorField<TFormValues extends FieldValues>({
  control,
  name,

  label,
  description,

  orientation = 'vertical',


  disabled = false,
  required = false,
  readOnly = false,
  className,
  initialRecipient = {},
}: CustomerModalSelectorFieldProps<TFormValues>) {
  const isDisabled = disabled;
  const isReadOnly = readOnly && !disabled;


  return (
    <Controller
      control={control}
      name={name}
      render={({ field, fieldState }) => {
        const { name, value, onChange, onBlur, ref } = field;

        return (
          <Field data-invalid={fieldState.invalid} orientation={orientation} className={cn("gap-1", className)}>
            {label && <FieldLabel className='text-xs text-muted-foreground text-nowrap' htmlFor={name}>{label}</FieldLabel>}
            <CustomerModalSelector
              value={value}
              onValueChange={onChange}
              disabled={isDisabled}
              readOnly={isReadOnly}
              initialCustomer={{
                ...initialRecipient as CustomerSummary
              }}
            />
          </Field>
        );
      }}
    />
  );
}
