import {
  Calendar,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@repo/shadcn-ui/components";
import { CalendarIcon, LockIcon } from "lucide-react";

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

type DatePickerInputFieldProps<TFormValues extends FieldValues> = {
  control: Control<TFormValues>;
  name: FieldPath<TFormValues>;
  label: string;
  placeholder?: string;
  description?: string;
  disabled?: boolean;
  required?: boolean;
  readOnly?: boolean;
  className?: string;
  formatDateFn?: (iso: string) => string;
  parseDateFormat?: string; // e.g. "dd/MM/yyyy"
};

export function DatePickerInputField<TFormValues extends FieldValues>({
  control,
  name,
  label,
  placeholder,
  description,
  disabled = false,
  required = false,
  readOnly = false,
  className,
  formatDateFn = (iso) => format(new Date(iso), "dd/MM/yyyy"),
  parseDateFormat = "dd/MM/yyyy",
}: DatePickerInputFieldProps<TFormValues>) {
  const { t } = useTranslation();
  const isDisabled = disabled;
  const isReadOnly = readOnly && !disabled;

  return (
    <FormField
      control={control}
      name={name}
      render={({ field }) => {
        const [inputValue, setInputValue] = useState<string>(
          field.value ? formatDateFn(field.value) : ""
        );
        const [inputError, setInputError] = useState<string | null>(null);

        const handleInputChange = (value: string) => {
          setInputValue(value);
          setInputError(null); // Reset error on typing
        };

        const validateAndSetDate = () => {
          const parsed = parse(inputValue, parseDateFormat, new Date());
          if (isValid(parsed)) {
            field.onChange(parsed.toISOString());
            setInputError(null);
          } else {
            setInputError(t("common.invalid_date") || "Fecha no válida");
          }
        };

        return (
          <FormItem className={cn("space-y-2", className)}>
            <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>

            <Popover>
              <PopoverTrigger asChild>
                <FormControl>
                  <div className='relative'>
                    <input
                      type='text'
                      value={inputValue}
                      onChange={(e) => handleInputChange(e.target.value)}
                      onBlur={validateAndSetDate}
                      onKeyDown={(e) => {
                        if (e.key === "Enter") {
                          e.preventDefault();
                          validateAndSetDate();
                        }
                      }}
                      readOnly={isReadOnly}
                      disabled={isDisabled}
                      className={cn(
                        "w-full rounded-md border px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-2 focus:ring-ring",
                        isDisabled && "bg-muted text-muted-foreground cursor-not-allowed",
                        isReadOnly && "bg-muted text-foreground cursor-default",
                        !isDisabled && !isReadOnly && "bg-white text-foreground",
                        inputError && "border-destructive ring-destructive"
                      )}
                      placeholder={placeholder}
                    />
                    <div className='absolute inset-y-0 right-2 flex items-center pointer-events-none'>
                      {isReadOnly ? (
                        <LockIcon className='h-4 w-4 text-muted-foreground' />
                      ) : (
                        <CalendarIcon className='h-4 w-4 text-muted-foreground' />
                      )}
                    </div>
                  </div>
                </FormControl>
              </PopoverTrigger>

              {!isDisabled && !isReadOnly && (
                <PopoverContent className='w-auto p-0'>
                  <Calendar
                    mode='single'
                    selected={field.value ? new Date(field.value) : undefined}
                    onSelect={(date) => {
                      if (date) {
                        const iso = date.toISOString();
                        field.onChange(iso);
                        setInputValue(formatDateFn(iso));
                        setInputError(null);
                      }
                    }}
                    initialFocus
                  />
                </PopoverContent>
              )}
            </Popover>

            <p
              className={cn(
                "text-xs",
                inputError ? "text-destructive" : "text-muted-foreground",
                !description && !inputError && "invisible"
              )}
            >
              {inputError || description || "\u00A0"}
            </p>

            <FormMessage />
          </FormItem>
        );
      }}
    />
  );
}
