'use client';

import { useState, useEffect } from 'react';
import { Button } from '../primitives';
import { ChevronLeft, ChevronRight, Calendar } from 'lucide-react';
import { cn } from '../lib/cn';

const MESES = [
  'Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun',
  'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'
];

function getMonthRange(year: number, month: number) {
  const start = `${year}-${String(month).padStart(2, '0')}-01`;
  const lastDay = new Date(year, month, 0).getDate();
  const end = `${year}-${String(month).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}`;
  return { start, end };
}

function getRange(startYear: number, startMonth: number, endYear: number, endMonth: number) {
  const start = getMonthRange(startYear, startMonth).start;
  const end = getMonthRange(endYear, endMonth).end;
  return { start, end };
}

function parseDate(dateStr: string) {
  const d = new Date(dateStr + 'T00:00:00');
  return { year: d.getFullYear(), month: d.getMonth() + 1 };
}

interface PeriodSelectorProps {
  fechaInicio: string;
  fechaFin: string;
  onChange: (fechaInicio: string, fechaFin: string) => void;
}

export function PeriodSelector({ fechaInicio, fechaFin, onChange }: PeriodSelectorProps) {
  const [pickerOpen, setPickerOpen] = useState(false);
  const [pickerYear, setPickerYear] = useState(new Date().getFullYear());
  const [selecting, setSelecting] = useState<'idle' | 'from'>('idle');
  const [tempFrom, setTempFrom] = useState<{ year: number; month: number } | null>(null);

  const startParsed = parseDate(fechaInicio);
  const endParsed = parseDate(fechaFin);
  const totalMonths = (endParsed.year - startParsed.year) * 12 + (endParsed.month - startParsed.month) + 1;

  const handlePrev = () => {
    let sm = startParsed.month - totalMonths;
    let sy = startParsed.year;
    while (sm < 1) { sm += 12; sy--; }
    let em = endParsed.month - totalMonths;
    let ey = endParsed.year;
    while (em < 1) { em += 12; ey--; }
    const r = getRange(sy, sm, ey, em);
    onChange(r.start, r.end);
  };

  const handleNext = () => {
    let sm = startParsed.month + totalMonths;
    let sy = startParsed.year;
    while (sm > 12) { sm -= 12; sy++; }
    let em = endParsed.month + totalMonths;
    let ey = endParsed.year;
    while (em > 12) { em -= 12; ey++; }
    const r = getRange(sy, sm, ey, em);
    onChange(r.start, r.end);
  };

  const handleMonthClick = (month: number) => {
    if (selecting === 'idle') {
      // First click: set start month
      setTempFrom({ year: pickerYear, month });
      setSelecting('from');
    } else {
      // Second click: set end month, apply range
      let fy = tempFrom!.year;
      let fm = tempFrom!.month;
      let ty = pickerYear;
      let tm = month;

      // Ensure from <= to
      if (ty < fy || (ty === fy && tm < fm)) {
        [fy, fm, ty, tm] = [ty, tm, fy, fm];
      }

      const r = getRange(fy, fm, ty, tm);
      onChange(r.start, r.end);
      setSelecting('idle');
      setTempFrom(null);
      setPickerOpen(false);
    }
  };

  const openPicker = () => {
    setPickerYear(startParsed.year);
    setSelecting('idle');
    setTempFrom(null);
    setPickerOpen(!pickerOpen);
  };

  const isInRange = (month: number) => {
    const v = pickerYear * 12 + month;
    const sv = startParsed.year * 12 + startParsed.month;
    const ev = endParsed.year * 12 + endParsed.month;
    return v >= sv && v <= ev;
  };

  const isStart = (month: number) =>
    pickerYear === startParsed.year && month === startParsed.month;

  const isEnd = (month: number) =>
    pickerYear === endParsed.year && month === endParsed.month;

  const isTempFrom = (month: number) =>
    selecting === 'from' && tempFrom?.year === pickerYear && tempFrom?.month === month;

  const getDisplayText = () => {
    const sm = MESES[startParsed.month - 1];
    const em = MESES[endParsed.month - 1];
    if (startParsed.year === endParsed.year && startParsed.month === endParsed.month) {
      return `${sm} ${startParsed.year}`;
    }
    if (startParsed.year === endParsed.year) {
      return `${sm} – ${em} ${startParsed.year}`;
    }
    return `${sm} ${startParsed.year} – ${em} ${endParsed.year}`;
  };

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      const target = e.target as HTMLElement;
      if (!target.closest('.period-selector-popup')) {
        setPickerOpen(false);
        setSelecting('idle');
        setTempFrom(null);
      }
    };
    document.addEventListener('click', handler);
    return () => document.removeEventListener('click', handler);
  }, []);

  return (
    <div className="period-selector-popup relative flex items-center gap-1">
      <Button variant="ghost" size="icon" className="h-8 w-8" onClick={handlePrev}>
        <ChevronLeft className="h-4 w-4" />
      </Button>

      <button
        onClick={openPicker}
        className={cn(
          'flex items-center gap-2 text-sm font-medium px-3 py-1.5 rounded-md transition-colors whitespace-nowrap',
          pickerOpen ? 'bg-primary/10 text-primary' : 'hover:bg-accent'
        )}
      >
        <Calendar className="h-4 w-4 flex-shrink-0" />
        {getDisplayText()}
      </button>

      <Button variant="ghost" size="icon" className="h-8 w-8" onClick={handleNext}>
        <ChevronRight className="h-4 w-4" />
      </Button>

      {pickerOpen && (
        <div className="absolute top-full left-0 mt-2 w-64 rounded-lg border bg-card shadow-lg z-50 p-4 space-y-3">
          {/* Year selector */}
          <div className="flex items-center justify-between">
            <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => setPickerYear(pickerYear - 1)}>
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <span className="text-sm font-semibold">{pickerYear}</span>
            <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => setPickerYear(pickerYear + 1)}>
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>

          {/* Month grid */}
          <div className="grid grid-cols-4 gap-1">
            {MESES.map((m, i) => {
              const mo = i + 1;
              const tempSelected = isTempFrom(mo);

              // When selecting (first click made), only show tempFrom — hide previous range
              const showRange = selecting === 'idle';
              const start = showRange && isStart(mo);
              const end = showRange && isEnd(mo);
              const inRange = showRange && isInRange(mo);

              return (
                <button
                  key={m}
                  onClick={() => handleMonthClick(mo)}
                  className={cn(
                    'text-xs py-2 px-2 rounded-md transition-colors',
                    tempSelected
                      ? 'bg-primary text-primary-foreground'
                      : start || end
                        ? 'bg-primary text-primary-foreground'
                        : inRange
                          ? 'bg-primary/15 text-primary'
                          : 'hover:bg-accent'
                  )}
                >
                  {m}
                </button>
              );
            })}
          </div>

          {/* Status + shortcut */}
          <div className="flex items-center justify-between text-xs text-muted-foreground pt-1 border-t">
            <span>
              {selecting === 'from'
                ? `Desde: ${MESES[tempFrom!.month - 1]} ${tempFrom!.year} → elige fin`
                : 'Clic en mes inicio'}
            </span>
            <Button
              variant="ghost"
              size="sm"
              className="text-xs h-6"
              onClick={() => {
                const now = new Date();
                const r = getMonthRange(now.getFullYear(), now.getMonth() + 1);
                onChange(r.start, r.end);
                setPickerOpen(false);
                setSelecting('idle');
              }}
            >
              Hoy
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
