"use client";

type PersianTimeFieldProps = {
  label: string;
  value: string;
  onChange: (value: string) => void;
  required?: boolean;
};

function pad(value: number) {
  return String(value).padStart(2, "0");
}

function toPersianNumber(value: string) {
  return new Intl.NumberFormat("fa-IR").format(Number(value));
}

export default function PersianTimeField({
  label,
  value,
  onChange,
  required = false,
}: PersianTimeFieldProps) {
  const [hour = "12", minute = "00"] = value ? value.split(":") : ["12", "00"];

  return (
    <div className="space-y-2">
      <label className="block text-sm font-medium text-slate-700">{label}</label>
      <input
        className="pointer-events-none absolute opacity-0"
        value={value}
        onChange={() => undefined}
        required={required}
        tabIndex={-1}
      />

      <div className="grid grid-cols-[1fr_auto_1fr] items-center gap-2 rounded-2xl border border-slate-200 bg-white px-3 py-3 shadow-sm">
        <select
          value={hour}
          onChange={(event) => onChange(`${event.target.value}:${minute}`)}
          className="w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-slate-900 outline-none transition focus:border-cyan-400 focus:ring-2 focus:ring-cyan-200"
        >
          {Array.from({ length: 24 }, (_, index) => pad(index)).map((item) => (
            <option key={item} value={item}>
              {toPersianNumber(item)}
            </option>
          ))}
        </select>

        <span className="text-lg font-bold text-slate-400">:</span>

        <select
          value={minute}
          onChange={(event) => onChange(`${hour}:${event.target.value}`)}
          className="w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-slate-900 outline-none transition focus:border-cyan-400 focus:ring-2 focus:ring-cyan-200"
        >
          {Array.from({ length: 60 }, (_, index) => pad(index)).map((item) => (
            <option key={item} value={item}>
              {toPersianNumber(item)}
            </option>
          ))}
        </select>
      </div>
    </div>
  );
}
