"use client";

import React, { useEffect, useMemo, useState } from "react";
import moment from "moment-jalaali";
import clsx from "clsx";
import AnchorLeftIcon from "@/assets/icons/anchor-left";
import { IconButton } from "@/components/icon-button";

try {
  moment.loadPersian({ dialect: "persian-modern", usePersianDigits: false });
} catch {
  /* already loaded */
}

const WEEKDAYS = ["ش", "ی", "د", "س", "چ", "پ", "ج"];

export interface JalaliDayPickerProps {
  mode?: "single";
  selected?: Date;
  onSelect?: (date?: Date) => void;
  month?: Date;
  onMonthChange?: (month: Date) => void;
  /** تاریخ‌های غیرفعال (مثل فروشگاه تعطیل) */
  disabledDates?: Date[];
  /** غیرفعال کردن قبل از این تاریخ (معمولاً امروز) */
  disableBefore?: Date;
  className?: string;
}

function safeMoment(input?: Date | string | number | null) {
  if (input == null || input === "") return moment();
  if (input instanceof Date && Number.isNaN(input.getTime())) return moment();
  const m = moment(input);
  return m.isValid() ? m : moment();
}

export function JalaliDayPicker({
  selected,
  onSelect,
  month,
  onMonthChange,
  disabledDates = [],
  disableBefore,
  className,
}: JalaliDayPickerProps) {
  const [cursor, setCursor] = useState(() => safeMoment(month || selected));

  useEffect(() => {
    if (month) setCursor(safeMoment(month));
  }, [month]);

  useEffect(() => {
    if (!month && selected) setCursor(safeMoment(selected));
  }, [selected, month]);

  const disabledKeys = useMemo(
    () =>
      new Set(
        disabledDates
          .map((d) => moment(d))
          .filter((m) => m.isValid())
          .map((m) => m.format("jYYYY-jMM-jDD")),
      ),
    [disabledDates],
  );

  const before = useMemo(() => {
    if (!disableBefore) return null;
    const m = moment(disableBefore);
    return m.isValid() ? m.startOf("day") : null;
  }, [disableBefore]);

  const weeks = useMemo(() => {
    const base = cursor.isValid() ? cursor : moment();
    const start = base.clone().startOf("jMonth");
    const end = base.clone().endOf("jMonth");
    const gridStart = start.clone().subtract((start.day() + 1) % 7, "day");
    const gridEnd = end.clone().add((5 - end.day() + 7) % 7, "day");
    const days: moment.Moment[] = [];
    const d = gridStart.clone();
    while (d.isBefore(gridEnd, "day") || d.isSame(gridEnd, "day")) {
      days.push(d.clone());
      d.add(1, "day");
    }
    const rows: moment.Moment[][] = [];
    for (let i = 0; i < days.length; i += 7) rows.push(days.slice(i, i + 7));
    return rows;
  }, [cursor]);

  const selectedMoment = selected ? moment(selected) : null;
  const selectedKey =
    selectedMoment && selectedMoment.isValid()
      ? selectedMoment.format("jYYYY-jMM-jDD")
      : null;

  const changeMonth = (delta: number) => {
    const next = cursor.clone().add(delta, "jMonth");
    setCursor(next);
    onMonthChange?.(next.clone().startOf("jMonth").toDate());
  };

  const pick = (day: moment.Moment) => {
    const key = day.format("jYYYY-jMM-jDD");
    if (disabledKeys.has(key)) return;
    if (before && day.isBefore(before, "day")) return;
    onSelect?.(day.clone().toDate());
  };

  return (
    <div className={clsx("w-full select-none", className)}>
      <div className="flex items-center justify-between px-1">
        <IconButton onClick={() => changeMonth(-1)} aria-label="prev-month">
          <span className="text-gray-field">
            <AnchorLeftIcon size={16} />
          </span>
        </IconButton>
        <span className="text-sm font-semibold">{cursor.format("jMMMM jYYYY")}</span>
        <IconButton onClick={() => changeMonth(1)} aria-label="next-month">
          <span className="text-gray-field">
            <AnchorLeftIcon size={16} style={{ rotate: "180deg" }} />
          </span>
        </IconButton>
      </div>

      <div className="mt-4 grid grid-cols-7 text-center text-xs font-medium text-gray-field tracking-widest">
        {WEEKDAYS.map((w) => (
          <span key={w} className="py-2">
            {w}
          </span>
        ))}
      </div>

      <div className="mt-1">
        {weeks.map((row, ri) => (
          <div key={ri} className="grid grid-cols-7">
            {row.map((day) => {
              const key = day.format("jYYYY-jMM-jDD");
              const inMonth = day.jMonth() === cursor.jMonth();
              const isSelected = selectedKey === key;
              const isDisabled =
                disabledKeys.has(key) || Boolean(before && day.isBefore(before, "day"));
              return (
                <button
                  type="button"
                  key={key}
                  disabled={isDisabled}
                  onClick={() => pick(day)}
                  className={clsx(
                    "aspect-square w-full rounded-full text-base transition-colors !py-3 md:!py-0",
                    !inMonth && "text-gray-field/40",
                    isSelected && "!bg-dark !text-white",
                    !isSelected && !isDisabled && "hover:bg-gray-link",
                    isDisabled && "opacity-30 cursor-not-allowed",
                  )}
                >
                  {day.format("jD")}
                </button>
              );
            })}
          </div>
        ))}
      </div>
    </div>
  );
}

export default JalaliDayPicker;
