"use client";
import { useState, useMemo } from "react";
import { ChevronLeft, ChevronRight, Clock } from "lucide-react";

interface TimeSlotPickerProps {
  value: string;
  onChange: (value: string) => void;
  workStart?: number;
  workEnd?: number;
  interval?: number;
  label?: string;
}

const DAYS = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];

export default function TimeSlotPicker({
  value,
  onChange,
  workStart = 8,
  workEnd = 22,
  interval = 30,
  label = "Date & Time *",
}: TimeSlotPickerProps) {
  const today = useMemo(() => {
    const d = new Date();
    d.setHours(0, 0, 0, 0);
    return d;
  }, []);

  const selectedDate   = value ? new Date(value) : null;
  const selectedDateStr = selectedDate
    ? `${selectedDate.getFullYear()}-${String(selectedDate.getMonth()+1).padStart(2,"0")}-${String(selectedDate.getDate()).padStart(2,"0")}`
    : "";
  const selectedTimeStr = selectedDate
    ? `${String(selectedDate.getHours()).padStart(2,"0")}:${String(selectedDate.getMinutes()).padStart(2,"0")}`
    : "";

  const [viewMonth, setViewMonth] = useState(() => {
    const d = selectedDate || new Date();
    return new Date(d.getFullYear(), d.getMonth(), 1);
  });

  const calendarDays = useMemo(() => {
    const y = viewMonth.getFullYear();
    const m = viewMonth.getMonth();
    const firstDay = new Date(y, m, 1).getDay();
    const daysInMonth = new Date(y, m + 1, 0).getDate();
    const days: { date: Date; inMonth: boolean; isPast: boolean; isToday: boolean }[] = [];

    for (let i = 0; i < firstDay; i++) {
      const d = new Date(y, m, -firstDay + i + 1);
      days.push({ date: d, inMonth: false, isPast: d < today, isToday: false });
    }
    for (let i = 1; i <= daysInMonth; i++) {
      const d = new Date(y, m, i);
      days.push({ date: d, inMonth: true, isPast: d < today, isToday: d.getTime() === today.getTime() });
    }
    while (days.length < 42) {
      const d = new Date(y, m + 1, days.length - firstDay - daysInMonth + 1);
      days.push({ date: d, inMonth: false, isPast: d < today, isToday: false });
    }
    return days;
  }, [viewMonth, today]);

  const timeSlots = useMemo(() => {
    const slots: { time: string; label: string; isPast: boolean }[] = [];
    const now = new Date();
    for (let h = workStart; h < workEnd; h++) {
      for (let m = 0; m < 60; m += interval) {
        const time = `${String(h).padStart(2,"0")}:${String(m).padStart(2,"0")}`;
        const h12  = h % 12 || 12;
        const lbl  = `${h12}:${String(m).padStart(2,"0")} ${h >= 12 ? "PM" : "AM"}`;
        let isPast = false;
        if (selectedDateStr) {
          isPast = new Date(`${selectedDateStr}T${time}`) <= now;
        }
        slots.push({ time, label: lbl, isPast });
      }
    }
    return slots;
  }, [workStart, workEnd, interval, selectedDateStr]);

  const handleDate = (date: Date) => {
    if (date < today) return;
    const ds = `${date.getFullYear()}-${String(date.getMonth()+1).padStart(2,"0")}-${String(date.getDate()).padStart(2,"0")}`;
    const ts = selectedTimeStr || `${String(workStart).padStart(2,"0")}:00`;
    onChange(`${ds}T${ts}`);
  };

  const handleTime = (time: string, isPast: boolean) => {
    if (isPast) return;
    const ds = selectedDateStr || `${today.getFullYear()}-${String(today.getMonth()+1).padStart(2,"0")}-${String(today.getDate()).padStart(2,"0")}`;
    onChange(`${ds}T${time}`);
  };

  const canPrev = viewMonth > today;
  const monthLabel = viewMonth.toLocaleDateString("en-US", { month: "long", year: "numeric" });

  const fmtHour = (h: number) => `${h % 12 || 12}:00 ${h >= 12 ? "PM" : "AM"}`;

  return (
    <div className="space-y-4">
      {/* Label */}
      <label className="block text-[11px] uppercase tracking-[0.08em] font-semibold text-[#94a3b8]">{label}</label>

      {/* Hours info pill */}
      <div className="inline-flex items-center gap-2 text-[12px] text-[#64748b] bg-[#f8fafc] border border-[#e2e8f0] rounded-lg px-3 py-2">
        <Clock size={12} className="text-[#4f46e5]" />
        <span>Available <strong className="text-[#0f172a]">{fmtHour(workStart)} – {fmtHour(workEnd)}</strong></span>
      </div>

      {/* Calendar */}
      <div className="rounded-2xl border border-[#e2e8f0] overflow-hidden bg-white">
        {/* Month nav */}
        <div className="flex items-center justify-between px-4 py-3 border-b border-[#f1f5f9] bg-[#fafbff]">
          <button
            type="button"
            onClick={() => setViewMonth(new Date(viewMonth.getFullYear(), viewMonth.getMonth()-1, 1))}
            disabled={!canPrev}
            className="w-7 h-7 rounded-lg flex items-center justify-center text-[#94a3b8] hover:bg-[#eef2ff] hover:text-[#4f46e5] transition-colors disabled:opacity-25 disabled:cursor-not-allowed"
          >
            <ChevronLeft size={16} />
          </button>
          <span className="text-[13px] font-bold text-[#0f172a]">{monthLabel}</span>
          <button
            type="button"
            onClick={() => setViewMonth(new Date(viewMonth.getFullYear(), viewMonth.getMonth()+1, 1))}
            className="w-7 h-7 rounded-lg flex items-center justify-center text-[#94a3b8] hover:bg-[#eef2ff] hover:text-[#4f46e5] transition-colors"
          >
            <ChevronRight size={16} />
          </button>
        </div>

        {/* Day headers */}
        <div className="grid grid-cols-7 border-b border-[#f1f5f9] bg-[#fafbff]">
          {DAYS.map((d) => (
            <div key={d} className="text-center text-[10px] font-bold text-[#94a3b8] uppercase py-2">{d}</div>
          ))}
        </div>

        {/* Days grid */}
        <div className="grid grid-cols-7 p-2 gap-1">
          {calendarDays.map((day, i) => {
            const ds = `${day.date.getFullYear()}-${String(day.date.getMonth()+1).padStart(2,"0")}-${String(day.date.getDate()).padStart(2,"0")}`;
            const isSel = ds === selectedDateStr;
            const disabled = day.isPast || !day.inMonth;

            return (
              <button
                key={i}
                type="button"
                disabled={disabled}
                onClick={() => handleDate(day.date)}
                className={`
                  relative w-full aspect-square flex items-center justify-center rounded-full text-[13px] font-semibold transition-all
                  ${disabled
                    ? "text-[#e2e8f0] cursor-not-allowed"
                    : isSel
                    ? "bg-[#4f46e5] text-white shadow-md shadow-[#4f46e5]/30 font-bold"
                    : day.isToday
                    ? "text-[#4f46e5] font-black ring-2 ring-[#4f46e5]/30 ring-offset-1"
                    : "text-[#475569] hover:bg-[#eef2ff] hover:text-[#4f46e5]"
                  }
                `}
              >
                {day.date.getDate()}
                {/* Today dot */}
                {day.isToday && !isSel && (
                  <span className="absolute bottom-0.5 left-1/2 -translate-x-1/2 w-1 h-1 rounded-full bg-[#4f46e5]" />
                )}
              </button>
            );
          })}
        </div>
      </div>

      {/* Time slots */}
      {selectedDateStr && (
        <div>
          <p className="text-[11px] uppercase tracking-[0.08em] font-semibold text-[#94a3b8] mb-3">
            {selectedDate?.toLocaleDateString("en-US", { weekday: "long", month: "short", day: "numeric" })}
          </p>
          <div className="grid grid-cols-4 gap-1.5 max-h-[192px] overflow-y-auto pr-0.5">
            {timeSlots.map((slot) => {
              const isSel = slot.time === selectedTimeStr;
              return (
                <button
                  key={slot.time}
                  type="button"
                  disabled={slot.isPast}
                  onClick={() => handleTime(slot.time, slot.isPast)}
                  className={`
                    py-2.5 px-1 rounded-xl text-[12px] font-semibold transition-all
                    ${slot.isPast
                      ? "text-[#e2e8f0] cursor-not-allowed bg-[#fafafa]"
                      : isSel
                      ? "bg-[#4f46e5] text-white shadow-md shadow-[#4f46e5]/25"
                      : "bg-[#f8fafc] text-[#475569] hover:bg-[#eef2ff] hover:text-[#4f46e5] border border-[#e2e8f0] hover:border-[#c7d2fe]"
                    }
                  `}
                >
                  {slot.label}
                </button>
              );
            })}
          </div>
        </div>
      )}

      {/* Selected summary chip */}
      {value && selectedDate && selectedTimeStr && (
        <div className="flex items-center gap-2 bg-[#eef2ff] border border-[#c7d2fe] rounded-xl px-4 py-3">
          <div className="w-2 h-2 rounded-full bg-[#4f46e5] shrink-0" />
          <span className="text-[13px] font-bold text-[#4338ca]">
            {selectedDate.toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric" })}
            {" · "}
            {selectedDate.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit", hour12: true })}
          </span>
        </div>
      )}
    </div>
  );
}
