"use client";

import SystemSelectInput from "@/components/ui/SystemSelectInput/SystemSelectInput";

import Typography from "@/components/ui/Typography/Typography";
import { useDateInput } from "@/hooks/useDateInput";

type LocalSelectInputProps = Omit<
  React.ComponentProps<typeof SystemSelectInput>,
  "value" | "onChange" | "options"
>;

export interface DateInputProps {
  value: string | null;
  onChange: (value: string | null) => void;
  error?: string;
  maxYear?: number;
  yearsRange?: number;
  //   onBlur?: () => void;
  daySelectProps?: LocalSelectInputProps;
  monthSelectProps?: LocalSelectInputProps;
  yearSelectProps?: LocalSelectInputProps;
}

export default function DateInput({
  value,
  onChange,
  error,
  maxYear = new Date().getFullYear() - 11,
  yearsRange = 100,
  //   onBlur,
  daySelectProps,
  monthSelectProps,
  yearSelectProps,
}: DateInputProps) {
  const {
    year,
    month,
    day,
    yearOptions,
    monthOptions,
    dayOptions,
    localeFormat,
    handleYearChange,
    handleMonthChange,
    handleDayChange,
  } = useDateInput({
    value,
    onChange,
    maxYear,
    yearsRange,
  });

  const inputs = {
    d: (
      <SystemSelectInput
        key="d"
        value={day}
        onChange={(e) => handleDayChange(e.target.value)}
        options={dayOptions}
        placeholder="DD"
        {...daySelectProps}
      />
    ),
    m: (
      <SystemSelectInput
        key="m"
        value={month}
        onChange={(e) => handleMonthChange(e.target.value)}
        options={monthOptions}
        placeholder="MM"
        {...monthSelectProps}
      />
    ),
    y: (
      <SystemSelectInput
        key="y"
        value={year}
        onChange={(e) => handleYearChange(e.target.value)}
        options={yearOptions}
        placeholder="YYYY"
        {...yearSelectProps}
      />
    ),
  };

  return (
    <div className="flex flex-col gap-2">
      <div className="flex flex-col gap-3 min-[360px]:flex-row">
        {localeFormat.map((format) => inputs[format])}
      </div>
      {error && (
        <Typography as="p" size="xs" color="destructive" align="left">
          {error}
        </Typography>
      )}
    </div>
  );
}
