"use client";

import { useEffect, useMemo, useState } from "react";
import { useTranslations } from "next-intl";

import { SelectInput } from "@/components/ui/SelectInput/SelectInput";

import styles from "./TimePicker.module.scss";

// Конвертирует 12-часовой формат в 24-часовой "HH:mm"
const to24HourFormat = (
  h: string,
  m: string,
  p: "AM" | "PM"
): string | null => {
  const hour = parseInt(h, 10);
  const minute = parseInt(m, 10);
  if (isNaN(hour) || isNaN(minute)) return null;

  let h24 = hour;
  if (p === "PM" && h24 < 12) h24 += 12;
  if (p === "AM" && h24 === 12) h24 = 0; // Полночь
  return `${String(h24).padStart(2, "0")}:${String(minute).padStart(2, "0")}`;
};

// Конвертирует 24-часовой "HH:mm" в объект {h, m, p}
const from24HourFormat = (val: string | null) => {
  if (!val || !/^\d{2}:\d{2}$/.test(val)) {
    return { h: "", m: "", p: "AM" as const };
  }
  const [h24, m] = val.split(":").map(Number);
  const p = h24 >= 12 ? ("PM" as const) : ("AM" as const);
  const h12 = h24 % 12 || 12; // 0 и 12 становятся 12
  return { h: String(h12), m: String(m).padStart(2, "0"), p };
};

interface TimePickerProps {
  label?: string;
  value: string | null; // Ожидается "HH:mm" (24h)
  onChange: (value: string | null) => void;
  error?: string;
  onBlur?: () => void;
}

export default function TimePicker({
  label,
  value,
  onChange,
  error,
  onBlur,
}: TimePickerProps) {
  const t = useTranslations("TimePicker");

  const [{ h, m, p }, setState] = useState(from24HourFormat(value));

  useEffect(() => {
    if (value === null) {
      onChange("12:00");
    }
  }, [value, onChange]);

  useEffect(() => {
    setState(from24HourFormat(value));
  }, [value]);

  const hourOptions = useMemo(
    () =>
      Array.from({ length: 12 }, (_, i) => ({
        value: i + 1,
        label: String(i + 1),
      })),
    []
  );
  const minuteOptions = useMemo(
    () =>
      Array.from({ length: 60 }, (_, i) => ({
        value: String(i).padStart(2, "0"),
        label: String(i).padStart(2, "0"),
      })),
    []
  );
  const periodOptions = [
    { value: "AM", label: "AM" },
    { value: "PM", label: "PM" },
  ];

  const handleStateChange = (newState: {
    h: string;
    m: string;
    p: "AM" | "PM";
  }) => {
    setState(newState);
    const formattedTime = to24HourFormat(newState.h, newState.m, newState.p);
    if (formattedTime !== value) {
      onChange(formattedTime);
    }
  };

  return (
    <div className={styles.container} onBlur={onBlur}>
      {label && <p className={styles.mainLabel}>{label}</p>}
      <div className={styles.inputsWrapper}>
        <SelectInput
          value={h}
          onChange={e => handleStateChange({ h: e.target.value, m, p })}
          options={hourOptions}
          placeholder={t("hour")}
          error={error}
        />
        <SelectInput
          value={m}
          onChange={e => handleStateChange({ h, m: e.target.value, p })}
          options={minuteOptions}
          placeholder={t("minute")}
          error={error}
        />
        <SelectInput
          value={p}
          onChange={e =>
            handleStateChange({ h, m, p: e.target.value as "AM" | "PM" })
          }
          options={periodOptions}
          placeholder={t("period")}
          error={error}
        />
      </div>
      {error && <p className={styles.errorText}>{error}</p>}
    </div>
  );
}
