import React, { useEffect, useRef, useState } from 'react';
import { Calendar, ChevronDown } from 'lucide-react';
import { DateRange } from '../types';

interface DateRangePickerProps {
  dateRange: DateRange;
  onChange: (range: DateRange) => void;
}

export const DateRangePicker: React.FC<DateRangePickerProps> = ({ dateRange, onChange }) => {
  const [isOpen, setIsOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);
  const startRef = useRef<HTMLInputElement>(null);
  const endRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    const 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 formatDateForInput = (date: Date) => {
    // Format to local YYYY-MM-DD to avoid timezone shifts
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  const formatShortDate = (date: Date) => {
    return date.toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit', year: '2-digit', timeZone: 'America/Sao_Paulo' });
  };

  const startOfDay = (date: Date) => {
    const result = new Date(date);
    result.setHours(0, 0, 0, 0);
    return result;
  };

  const endOfDay = (date: Date) => {
    const result = new Date(date);
    result.setHours(23, 59, 59, 999);
    return result;
  };

  const setRange = (start: Date, end: Date) => {
    onChange({ start: startOfDay(start), end: endOfDay(end) });
    setIsOpen(false);
  };

  const parseLocalDate = (value: string) => {
    // Split "YYYY-MM-DD" and create date in local timezone to avoid UTC midnight shift
    if (!value) return null;
    const [year, month, day] = value.split('-');
    return new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
  };

  const handleStartChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newStart = parseLocalDate(e.target.value);
    if (newStart && !isNaN(newStart.getTime())) {
      onChange({ ...dateRange, start: startOfDay(newStart) });
    }
  };

  const handleEndChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newEnd = parseLocalDate(e.target.value);
    if (newEnd && !isNaN(newEnd.getTime())) {
      onChange({ ...dateRange, end: endOfDay(newEnd) });
    }
  };

  const openPicker = (ref: React.RefObject<HTMLInputElement>) => {
    if (ref.current) {
      try {
        if ('showPicker' in HTMLInputElement.prototype) {
          ref.current.showPicker();
        } else {
          ref.current.focus();
        }
      } catch (e) {
        ref.current.focus();
      }
    }
  };

  const today = startOfDay(new Date());
  const shortcuts = [
    {
      label: 'Hoje',
      onClick: () => setRange(today, today),
    },
    {
      label: 'Ontem',
      onClick: () => {
        const yesterday = new Date(today);
        yesterday.setDate(today.getDate() - 1);
        setRange(yesterday, yesterday);
      },
    },
    {
      label: 'Últimos 7 dias',
      onClick: () => {
        const start = new Date(today);
        start.setDate(today.getDate() - 6);
        setRange(start, today);
      },
    },
    {
      label: 'Últimos 30 dias',
      onClick: () => {
        const start = new Date(today);
        start.setDate(today.getDate() - 29);
        setRange(start, today);
      },
    },
    {
      label: 'Este Mês',
      onClick: () => setRange(new Date(today.getFullYear(), today.getMonth(), 1), today),
    },
    {
      label: 'Mês Passado',
      onClick: () => setRange(
        new Date(today.getFullYear(), today.getMonth() - 1, 1),
        new Date(today.getFullYear(), today.getMonth(), 0)
      ),
    },
    {
      label: 'Últimos 90 dias',
      onClick: () => {
        const start = new Date(today);
        start.setDate(today.getDate() - 89);
        setRange(start, today);
      },
    },
    {
      label: 'Este Ano',
      onClick: () => setRange(new Date(today.getFullYear(), 0, 1), today),
    },
    {
      label: 'Todo o Período',
      onClick: () => setRange(new Date(0), today),
    },
  ];

  return (
    <div ref={containerRef} className="relative">
      <button
        type="button"
        onClick={() => setIsOpen(open => !open)}
        className="flex min-w-[224px] items-center justify-between gap-2 rounded-lg border border-zinc-200 bg-zinc-50 px-3 py-2 text-sm font-medium text-zinc-700 outline-none transition-all hover:border-zinc-300 focus:ring-2 focus:ring-brand-yellow/20 dark:border-dark-border dark:bg-dark-bg dark:text-zinc-200 dark:hover:border-dark-border"
      >
        <span className="flex items-center gap-2">
          <Calendar size={16} className="text-zinc-500 dark:text-dark-muted shrink-0" />
          <span>{formatShortDate(dateRange.start)} - {formatShortDate(dateRange.end)}</span>
        </span>
        <ChevronDown size={14} className={`text-zinc-400 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
      </button>

      {isOpen && (
        <div className="absolute right-0 top-full z-50 mt-2 w-56 overflow-hidden rounded-xl border border-zinc-200 bg-white shadow-2xl dark:border-dark-border dark:bg-dark-card">
          <div className="p-4">
            <div className="mb-3 text-xs font-bold uppercase tracking-[0.18em] text-zinc-500 dark:text-dark-muted">
              Período Customizado
            </div>

            <div className="space-y-2">
              <div className="grid grid-cols-[26px_1fr] items-center gap-2">
                <label className="text-xs font-medium text-zinc-700 dark:text-dark-text">De:</label>
                <button
                  type="button"
                  onClick={() => openPicker(startRef)}
                  className="relative h-7 rounded-lg border border-zinc-200 bg-zinc-50 px-3 text-center text-xs text-zinc-800 dark:border-dark-border dark:bg-dark-input dark:text-dark-text"
                >
                  {formatShortDate(dateRange.start)}
                  <input
                    ref={startRef}
                    type="date"
                    value={formatDateForInput(dateRange.start)}
                    onChange={handleStartChange}
                    className="absolute inset-0 h-full w-full opacity-0"
                    tabIndex={-1}
                  />
                </button>
              </div>

              <div className="grid grid-cols-[26px_1fr] items-center gap-2">
                <label className="text-xs font-medium text-zinc-700 dark:text-dark-text">Até:</label>
                <button
                  type="button"
                  onClick={() => openPicker(endRef)}
                  className="relative h-7 rounded-lg border border-zinc-200 bg-zinc-50 px-3 text-center text-xs text-zinc-800 dark:border-dark-border dark:bg-dark-input dark:text-dark-text"
                >
                  {formatShortDate(dateRange.end)}
                  <input
                    ref={endRef}
                    type="date"
                    value={formatDateForInput(dateRange.end)}
                    onChange={handleEndChange}
                    className="absolute inset-0 h-full w-full opacity-0"
                    tabIndex={-1}
                  />
                </button>
              </div>
            </div>
          </div>

          <div className="border-t border-zinc-100 p-4 dark:border-dark-border">
            <div className="mb-2 text-xs font-bold uppercase tracking-[0.18em] text-zinc-500 dark:text-dark-muted">
              Atalhos
            </div>
            <div className="space-y-1">
              {shortcuts.map(shortcut => (
                <button
                  key={shortcut.label}
                  type="button"
                  onClick={shortcut.onClick}
                  className="block w-full rounded-lg px-0 py-1.5 text-left text-sm text-zinc-500 transition-colors hover:text-zinc-900 dark:text-dark-muted dark:hover:text-dark-text"
                >
                  {shortcut.label}
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
