"use client";

import { useCallback, useEffect, useState } from "react";
import { Button } from "@/components/ui/Button";
import { PersianDatePicker } from "@/components/ui/PersianDatePicker";
import {
  type ClassSchedule,
  computeSessionDates,
} from "@/lib/class-session-dates";
import { apiGet } from "@/lib/api";

function todayIso() {
  return new Date().toISOString().slice(0, 10);
}

function formatFaDate(iso: string) {
  try {
    return new Date(iso + "T12:00:00").toLocaleDateString("fa-IR", {
      weekday: "long",
      year: "numeric",
      month: "long",
      day: "numeric",
    });
  } catch {
    return iso;
  }
}

function shiftDays(iso: string, days: number) {
  const d = new Date(iso + "T12:00:00");
  d.setDate(d.getDate() + days);
  return d.toISOString().slice(0, 10);
}

export function SessionDateField({
  value,
  onChange,
  classRoomId,
  subjectId,
}: {
  value: string;
  onChange: (iso: string) => void;
  classRoomId: number;
  subjectId?: number | null;
}) {
  const [sessionDates, setSessionDates] = useState<string[]>([]);

  const loadSessions = useCallback(async () => {
    try {
      const schedules = await apiGet<ClassSchedule[]>(`/schedules?class_room_id=${classRoomId}`);
      const today = todayIso();
      setSessionDates(computeSessionDates(shiftDays(today, -400), shiftDays(today, 21), schedules, { subjectId }));
    } catch {
      setSessionDates([]);
    }
  }, [classRoomId, subjectId]);

  useEffect(() => {
    void loadSessions();
  }, [loadSessions]);

  return (
    <div className="flex flex-wrap items-center justify-between gap-2 rounded-2xl border border-slate-200 bg-slate-50 px-3 py-2.5">
      <div>
        <div className="text-[11px] font-medium text-slate-500">تاریخ</div>
        <div className="text-sm font-semibold text-slate-800">{formatFaDate(value)}</div>
      </div>
      <PersianDatePicker
        value={value}
        sessionDates={sessionDates}
        onChange={(next) => {
          if (next) onChange(next.slice(0, 10));
        }}
        renderTrigger={(openCalendar) => (
          <Button
            type="button"
            variant="secondary"
            className="h-9 rounded-xl px-3 text-xs"
            onClick={openCalendar}
          >
            تغییر تاریخ
          </Button>
        )}
      />
    </div>
  );
}
