"use client";

import React, { useState, useRef, useEffect } from "react";
import { ChevronLeft, ChevronRight, Calendar as CalendarIcon } from "lucide-react";

interface CustomDatePickerProps {
  value: string; // YYYY-MM-DD
  onChange: (value: string) => void;
  placeholder?: string;
}

const MONTH_NAMES = [
  "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho",
  "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
];

const DAY_NAMES = ["D", "S", "T", "Q", "Q", "S", "S"];

function getDaysInMonth(year: number, month: number) {
  return new Date(year, month + 1, 0).getDate();
}

function getFirstDayOfMonth(year: number, month: number) {
  return new Date(year, month, 1).getDay();
}

export function CustomDatePicker({ value, onChange, placeholder = "Selecione..." }: CustomDatePickerProps) {
  const [isOpen, setIsOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);
  
  const [viewDate, setViewDate] = useState(() => {
    if (value) {
      const [y, m] = value.split("-").map(Number);
      return new Date(y, m - 1, 1);
    }
    const now = new Date();
    return new Date(now.getFullYear(), now.getMonth(), 1);
  });

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const handlePrevMonth = () => {
    setViewDate(new Date(viewDate.getFullYear(), viewDate.getMonth() - 1, 1));
  };

  const handleNextMonth = () => {
    setViewDate(new Date(viewDate.getFullYear(), viewDate.getMonth() + 1, 1));
  };

  const handleSelectDate = (day: number) => {
    const y = viewDate.getFullYear();
    const m = String(viewDate.getMonth() + 1).padStart(2, "0");
    const d = String(day).padStart(2, "0");
    onChange(`${y}-${m}-${d}`);
    setIsOpen(false);
  };

  const renderCalendar = () => {
    const year = viewDate.getFullYear();
    const month = viewDate.getMonth();
    const daysInMonth = getDaysInMonth(year, month);
    const firstDay = getFirstDayOfMonth(year, month);

    const days = [];
    // Blank spaces for days before the 1st
    for (let i = 0; i < firstDay; i++) {
      days.push(<div key={`empty-${i}`} className="w-8 h-8"></div>);
    }

    // Days of the month
    for (let d = 1; d <= daysInMonth; d++) {
      const isSelected = value === `${year}-${String(month + 1).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
      const isToday = 
        new Date().getFullYear() === year && 
        new Date().getMonth() === month && 
        new Date().getDate() === d;

      days.push(
        <button
          key={d}
          onClick={() => handleSelectDate(d)}
          className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-medium transition-all ${
            isSelected
              ? "bg-[var(--ks-color-primary)] text-white shadow-md shadow-[var(--ks-color-primary-soft)]"
              : isToday
              ? "bg-[var(--ks-color-primary-light)] text-[var(--ks-color-primary)] font-bold"
              : "text-[var(--ks-color-text-primary)] hover:bg-[var(--ks-color-bg-subtle)] hover:text-[var(--ks-color-primary)]"
          }`}
        >
          {d}
        </button>
      );
    }

    return days;
  };

  const formatDisplayValue = (val: string) => {
    if (!val) return placeholder;
    const [y, m, d] = val.split("-");
    return `${d}/${m}/${y}`;
  };

  return (
    <div className="relative w-full" ref={containerRef}>
      {/* Trigger */}
      <div 
        onClick={() => setIsOpen(!isOpen)}
        className={`flex items-center justify-between w-full rounded-lg border bg-[var(--ks-color-bg-subtle)] px-2.5 py-2 text-[11px] font-medium text-[var(--ks-color-text-primary)] cursor-pointer transition-all ${
          isOpen ? "border-[var(--ks-color-primary)] ring-2 ring-[var(--ks-color-primary-soft-strong)]" : "border-[var(--ks-color-border-subtle)] hover:border-gray-300"
        }`}
      >
        <span className={!value ? "text-[var(--ks-color-text-muted)]" : ""}>
          {formatDisplayValue(value)}
        </span>
        <CalendarIcon size={14} className="text-[var(--ks-color-text-muted)]" />
      </div>

      {/* Popover */}
      {isOpen && (
        <div className="absolute top-full mt-2 right-0 z-50 w-[260px] p-4 bg-white rounded-2xl shadow-xl border border-[var(--ks-color-border-subtle)] animate-in fade-in zoom-in-95 origin-top-right">
          
          {/* Header */}
          <div className="flex items-center justify-between mb-4">
            <button 
              onClick={handlePrevMonth}
              className="w-7 h-7 rounded-full flex items-center justify-center text-[var(--ks-color-text-muted)] hover:bg-[var(--ks-color-bg-subtle)] hover:text-[var(--ks-color-text-primary)] transition-colors"
            >
              <ChevronLeft size={16} />
            </button>
            <span className="text-sm font-bold text-[var(--ks-color-text-primary)] capitalize">
              {MONTH_NAMES[viewDate.getMonth()]} {viewDate.getFullYear()}
            </span>
            <button 
              onClick={handleNextMonth}
              className="w-7 h-7 rounded-full flex items-center justify-center text-[var(--ks-color-text-muted)] hover:bg-[var(--ks-color-bg-subtle)] hover:text-[var(--ks-color-text-primary)] transition-colors"
            >
              <ChevronRight size={16} />
            </button>
          </div>

          {/* Days Header */}
          <div className="grid grid-cols-7 gap-1 mb-2">
            {DAY_NAMES.map((day, i) => (
              <div key={i} className="w-8 h-8 flex items-center justify-center text-[10px] font-bold text-[var(--ks-color-text-muted)]">
                {day}
              </div>
            ))}
          </div>

          {/* Calendar Grid */}
          <div className="grid grid-cols-7 gap-1">
            {renderCalendar()}
          </div>

          {/* Footer Actions */}
          <div className="mt-4 pt-3 border-t border-[var(--ks-color-border-subtle)] flex justify-between">
            <button 
              onClick={() => {
                onChange("");
                setIsOpen(false);
              }}
              className="text-[11px] font-semibold text-[var(--ks-color-text-muted)] hover:text-[var(--ks-color-text-primary)]"
            >
              Limpar
            </button>
            <button 
              onClick={() => {
                const now = new Date();
                onChange(`${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`);
                setIsOpen(false);
              }}
              className="text-[11px] font-semibold text-[var(--ks-color-primary)] hover:text-[var(--ks-color-primary-strong)]"
            >
              Hoje
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
