"use client";

import * as React from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

export interface CalendarProps {
  selected?: Date | string | null;
  onSelect?: (date: Date) => void;
  minDate?: Date;
  className?: string;
}

const MONTHS = [
  "January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

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

export function Calendar({
  selected,
  onSelect,
  minDate,
  className,
}: CalendarProps) {
  const selectedDate = selected
    ? typeof selected === "string"
      ? new Date(selected)
      : selected
    : null;

  const [currentMonth, setCurrentMonth] = React.useState(
    selectedDate || new Date()
  );

  const year = currentMonth.getFullYear();
  const month = currentMonth.getMonth();

  const firstDayIndex = new Date(year, month, 1).getDay();
  const daysInMonth = new Date(year, month + 1, 0).getDate();

  const handlePrevMonth = () => {
    setCurrentMonth(new Date(year, month - 1, 1));
  };

  const handleNextMonth = () => {
    setCurrentMonth(new Date(year, month + 1, 1));
  };

  const isSameDay = (d1: Date, d2: Date) => {
    return (
      d1.getFullYear() === d2.getFullYear() &&
      d1.getMonth() === d2.getMonth() &&
      d1.getDate() === d2.getDate()
    );
  };

  const isPast = (date: Date) => {
    if (!minDate) return false;
    const startOfMin = new Date(minDate.getFullYear(), minDate.getMonth(), minDate.getDate());
    const startOfDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
    return startOfDate < startOfMin;
  };

  const cells = [];
  // Empty cells for alignment
  for (let i = 0; i < firstDayIndex; i++) {
    cells.push(<div key={`empty-${i}`} className="h-8 w-8" />);
  }

  // Days
  for (let d = 1; d <= daysInMonth; d++) {
    const dayDate = new Date(year, month, d);
    const isSelected = selectedDate ? isSameDay(dayDate, selectedDate) : false;
    const isToday = isSameDay(dayDate, new Date());
    const disabled = isPast(dayDate);

    cells.push(
      <button
        key={`day-${d}`}
        type="button"
        disabled={disabled}
        onClick={() => onSelect?.(dayDate)}
        className={cn(
          "h-8 w-8 rounded-lg text-xs font-medium transition flex items-center justify-center select-none outline-none focus-visible:ring-2 focus-visible:ring-neutral-900 dark:focus-visible:ring-white",
          isSelected
            ? "bg-neutral-900 text-white dark:bg-white dark:text-neutral-900 font-bold shadow-xs"
            : isToday
            ? "border border-neutral-300 dark:border-neutral-700 text-neutral-900 dark:text-white font-semibold"
            : "text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800",
          disabled && "opacity-30 cursor-not-allowed hover:bg-transparent"
        )}
      >
        {d}
      </button>
    );
  }

  return (
    <div className={cn("w-64 p-3 bg-white dark:bg-neutral-900 rounded-xl border border-neutral-200 dark:border-neutral-800", className)}>
      {/* Month & Year Header */}
      <div className="flex items-center justify-between pb-3 border-b border-neutral-100 dark:border-neutral-800">
        <span className="text-xs font-bold text-neutral-900 dark:text-white">
          {MONTHS[month]} {year}
        </span>
        <div className="flex items-center gap-1">
          <Button
            type="button"
            variant="ghost"
            size="sm"
            onClick={handlePrevMonth}
            className="h-7 w-7 p-0 text-neutral-500 hover:text-neutral-900 dark:hover:text-white"
          >
            <ChevronLeft className="h-4 w-4" />
          </Button>
          <Button
            type="button"
            variant="ghost"
            size="sm"
            onClick={handleNextMonth}
            className="h-7 w-7 p-0 text-neutral-500 hover:text-neutral-900 dark:hover:text-white"
          >
            <ChevronRight className="h-4 w-4" />
          </Button>
        </div>
      </div>

      {/* Weekday Labels */}
      <div className="grid grid-cols-7 gap-1 pt-2 pb-1 text-center text-[10px] font-bold text-neutral-400">
        {DAYS.map((day) => (
          <div key={day} className="h-6 flex items-center justify-center">
            {day}
          </div>
        ))}
      </div>

      {/* Days Grid */}
      <div className="grid grid-cols-7 gap-1">{cells}</div>
    </div>
  );
}
