"use client";

import { useState, useRef, useEffect } from "react";
import { DayPicker } from "react-day-picker";
import { srLatn } from "date-fns/locale";
import { CalendarDaysIcon } from "@heroicons/react/24/outline";
import "react-day-picker/style.css";

function parseInputDate(s: string): Date | null {
  const match = s.trim().match(/^(\d{1,2})\.(\d{1,2})\.(\d{4})$/);
  if (!match) return null;
  const [, d, m, y] = match;
  const date = new Date(Number(y), Number(m) - 1, Number(d));
  return isNaN(date.getTime()) ? null : date;
}

function fmtDMY(d: Date) {
  const dd = String(d.getDate()).padStart(2, "0");
  const mm = String(d.getMonth() + 1).padStart(2, "0");
  const yyyy = d.getFullYear();
  return `${dd}.${mm}.${yyyy}`;
}

type Props = {
  value: string;
  onChange: (v: string) => void;
  placeholder?: string;
};

export function DatePickerInput({ value, onChange, placeholder = "dd.mm.yyyy" }: Props) {
  const [open, setOpen] = useState(false);
  const wrapRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function onClickOutside(e: MouseEvent) {
      if (wrapRef.current && !wrapRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    document.addEventListener("mousedown", onClickOutside);
    return () => document.removeEventListener("mousedown", onClickOutside);
  }, []);

  const selected = parseInputDate(value) ?? undefined;

  return (
    <div ref={wrapRef} className="relative">
      <div className="flex items-center border border-gray-200 rounded-lg overflow-hidden focus-within:ring-2 focus-within:ring-sky-300">
        <input
          type="text"
          className="px-3 py-2 text-sm w-28 focus:outline-none"
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder}
        />
        <button
          type="button"
          onClick={() => setOpen((v) => !v)}
          className="px-2 py-2 text-gray-400 hover:text-sky-600 hover:bg-sky-50 transition-colors border-l border-gray-200"
          tabIndex={-1}
        >
          <CalendarDaysIcon className="w-4 h-4" />
        </button>
      </div>

      {open && (
        <div className="absolute z-50 mt-1 bg-white rounded-2xl shadow-xl border border-gray-100 p-2">
          <DayPicker
            mode="single"
            selected={selected}
            onSelect={(date) => {
              if (date) {
                onChange(fmtDMY(date));
                setOpen(false);
              }
            }}
            locale={srLatn}
            weekStartsOn={1}
            showOutsideDays
          />
        </div>
      )}
    </div>
  );
}
