import {
  Button,
  Calendar,
  Field,
  FieldDescription,
  FieldError,
  FieldLabel,
  Popover,
  PopoverTrigger
} from "@repo/shadcn-ui/components";
import { CalendarIcon } from "lucide-react";

import { cn } from "@repo/shadcn-ui/lib/utils";
import { format, isValid, parse } from "date-fns";
import { useCallback, useEffect, useMemo, useState } from "react";
import { ControllerFieldState, ControllerRenderProps, FieldValues, Path, UseFormStateReturn } from "react-hook-form";
import { useTranslation } from "../../../locales/i18n.ts";
import { DateInputField } from './date-input-field.tsx';
import { DatePopoverCalendar } from './date-popover-calendar.tsx';


export type SUICalendarProps = Omit<React.ComponentProps<
  typeof Calendar>, "select" | "onSelect">

type DatePickerInputCompProps<TFormValues extends FieldValues = FieldValues> = SUICalendarProps & {
  field: ControllerRenderProps<TFormValues, Path<TFormValues>>;
  fieldState: ControllerFieldState;
  formState: UseFormStateReturn<TFormValues>;

  displayDateFormat: string; // e.g. "dd/MM/yyyy"
  parseDateFormat: string; // e.g. "yyyy/MM/dd"

  label?: string;
  placeholder?: string;
  description?: string;

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

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

  className?: string;
};

export function DatePickerInputComp<TFormValues extends FieldValues = FieldValues>({
  field,
  fieldState,
  formState,

  parseDateFormat,
  displayDateFormat,

  label,
  placeholder,
  description,
  disabled = false,
  required = false,
  readOnly = false,
  invalid = false,

  orientation = "vertical",

  className,
  ...calendarProps
}: DatePickerInputCompProps<TFormValues>) {
  const { t } = useTranslation();
  const [open, setOpen] = useState(false);
  const [displayValue, setDisplayValue] = useState("");
  const [localError, setLocalError] = useState<string | null>(null);

  const parsedDate = useMemo(() => {
    if (!field.value) return null;
    const d = parse(field.value, parseDateFormat, new Date());
    return isValid(d) ? d : null;
  }, [field.value, parseDateFormat]);

  useEffect(() => {
    setDisplayValue(parsedDate ? format(parsedDate, displayDateFormat) : "");
  }, [parsedDate, displayDateFormat]);

  const handleClear = useCallback(() => {
    field.onChange("");
    setDisplayValue("");
    setLocalError(null);
  }, [field]);

  const validateAndSet = useCallback(() => {
    const trimmed = displayValue.trim();
    if (!trimmed) {
      handleClear();
      return;
    }
    const d = parse(trimmed, displayDateFormat, new Date());
    if (isValid(d)) {
      field.onChange(format(d, parseDateFormat));
      setDisplayValue(format(d, displayDateFormat));
      setLocalError(null);
    } else {
      setLocalError(t("components.date_picker_input_field.invalid_date"));
    }
  }, [displayValue, displayDateFormat, parseDateFormat, field, t, handleClear]);

  const hasError = Boolean(localError || fieldState.error);
  const describedById = description ? `${field.name}-desc` : undefined;
  const errorId = hasError ? `${field.name}-err` : undefined;
  const popoverId = `${field.name}-popover`;

  return (
    <Field data-invalid={invalid} orientation={orientation} className={cn("gap-1", className)}>
      <div className="flex justify-between gap-2 overflow-hidden">
        <div className="flex items-center gap-2 flex-nowrap">
          <FieldLabel htmlFor={field.name} className={cn("m-0 text-xs text-muted-foreground text-nowrap text-ellipsis", disabled && "text-muted-foreground")}>
            {label}
          </FieldLabel>
          {required && <span className="text-xs text-destructive">{t("common.required")}</span>}
        </div>
        {fieldState.isDirty && <span className="text-[10px] text-primary text-ellipsis">{t("common.modified")}</span>}
      </div>


      <Popover modal={true} open={open} onOpenChange={setOpen}>
        <PopoverTrigger asChild>

          <DateInputField
            id={field.name}
            value={displayValue}
            onChange={(v) => {
              setDisplayValue(v);
              setLocalError(null);
            }}
            onBlurConfirm={validateAndSet}
            onClear={handleClear}
            placeholder={placeholder}
            disabled={disabled}
            readOnly={readOnly}
            required={required}
            hasError={hasError}
            describedBy={[describedById, errorId].filter(Boolean).join(" ") || undefined}
            onOpenRequest={() => setOpen(true)}
            triggerButton={
              !readOnly && !disabled && (
                <PopoverTrigger asChild>
                  <Button
                    variant={'link'}
                    type='button'
                    size={"icon-sm"}
                    aria-label={t("components.date_picker_input_field.open_calendar")}
                    aria-haspopup="dialog"
                    aria-expanded={open}
                    aria-controls={popoverId}
                    onClick={() => setOpen((o) => !o)}
                    className="text-muted-foreground transition cursor-pointer -mr-3"
                  >
                    <CalendarIcon className="size-4" />
                  </Button>
                </PopoverTrigger>
              )
            }
          />

        </PopoverTrigger>

        {!disabled && !readOnly && (
          <DatePopoverCalendar
            contentId={popoverId}
            label={label}
            description={description}
            parsedDate={parsedDate}
            onSelect={(date) => {
              if (!date) return;
              field.onChange(format(date, parseDateFormat));
              setDisplayValue(format(date, displayDateFormat));
              setOpen(false);
            }}
            onToday={() => {
              const today = new Date();
              field.onChange(format(today, parseDateFormat));
              setDisplayValue(format(today, displayDateFormat));
              setOpen(false);
            }}
            onClose={() => setOpen(false)}
            {...calendarProps}
          />

        )}
      </Popover>

      {false && (
        <div className='mt-1 flex items-start justify-between'>
          <FieldDescription
            id={describedById}
            className={cn("text-xs truncate", !description && "invisible")}
          >
            {description || "\u00A0"}
          </FieldDescription>
        </div>
      )}


      <FieldError errors={[fieldState.error]} />
    </Field>
  );
}
