
import React, { useState, useMemo } from 'react';
import { NotaFiscal, NFStatus } from '../types';

interface CalendarViewProps {
  nfs: NotaFiscal[];
  onShowHistory: (id: string) => void;
}

// Helper to check if an NF is overdue
const isOverdue = (nf: NotaFiscal): boolean => {
    if (nf.status !== NFStatus.PENDENTE) return false;
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const [year, month, day] = nf.dataPrevisao.split('-').map(Number);
    const previsionDate = new Date(year, month - 1, day);
    return previsionDate < today;
};

const CalendarView: React.FC<CalendarViewProps> = ({ nfs, onShowHistory }) => {
  const [currentDate, setCurrentDate] = useState(new Date());

  const nfsByDate = useMemo(() => {
    const map = new Map<string, NotaFiscal[]>();
    nfs.forEach(nf => {
      const date = nf.dataPrevisao;
      if (!map.has(date)) {
        map.set(date, []);
      }
      map.get(date)!.push(nf);
    });
    return map;
  }, [nfs]);

  const startOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
  const endOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);
  const startDate = new Date(startOfMonth);
  startDate.setDate(startDate.getDate() - startOfMonth.getDay());
  const endDate = new Date(endOfMonth);
  endDate.setDate(endDate.getDate() + (6 - endOfMonth.getDay()));

  const days = [];
  let day = new Date(startDate);
  while (day <= endDate) {
    days.push(new Date(day));
    day.setDate(day.getDate() + 1);
  }

  const changeMonth = (offset: number) => {
    setCurrentDate(prev => new Date(prev.getFullYear(), prev.getMonth() + offset, 1));
  };
  
  const statusColor = (nf: NotaFiscal) => {
      if(isOverdue(nf)) return 'bg-red-500';
      switch(nf.status) {
          case NFStatus.PENDENTE: return 'bg-yellow-500';
          case NFStatus.RECEBIDO: return 'bg-blue-500';
          case NFStatus.CONFERIDO: return 'bg-green-500';
          default: return 'bg-gray-500';
      }
  }

  const today = new Date();
  today.setHours(0,0,0,0);

  return (
    <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-8 animate-fade-in-up">
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-3xl font-bold text-white">
          {currentDate.toLocaleDateString('pt-BR', { month: 'long', year: 'numeric' })}
        </h2>
        <div className="flex space-x-2">
          <button onClick={() => changeMonth(-1)} className="p-2 rounded-full bg-primary-medium/20 hover:bg-primary-medium/50 transition-colors">
            &lt;
          </button>
          <button onClick={() => changeMonth(1)} className="p-2 rounded-full bg-primary-medium/20 hover:bg-primary-medium/50 transition-colors">
            &gt;
          </button>
        </div>
      </div>

      <div className="grid grid-cols-7 gap-px bg-primary-medium/50 border border-primary-medium/50 rounded-lg overflow-hidden">
        {['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'].map(dayName => (
          <div key={dayName} className="text-center font-bold text-sm py-2 bg-primary-dark text-gray-300">{dayName}</div>
        ))}

        {days.map(d => {
          const dateString = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
          const nfsForDay = nfsByDate.get(dateString) || [];
          const isCurrentMonth = d.getMonth() === currentDate.getMonth();
          const isToday = d.getTime() === today.getTime();

          return (
            <div key={d.toString()} className={`p-2 h-48 flex flex-col ${isCurrentMonth ? 'bg-primary-dark/50' : 'bg-primary-dark/20'} relative`}>
              <span className={`font-bold ${isToday ? 'bg-primary-light text-primary-dark rounded-full w-7 h-7 flex items-center justify-center' : ''} ${isCurrentMonth ? 'text-white' : 'text-gray-600'}`}>
                {d.getDate()}
              </span>
              <div className="mt-1 space-y-1 overflow-y-auto pr-1">
                {nfsForDay.map(nf => (
                  <button key={nf.id} onClick={() => onShowHistory(nf.id)}
                    className={`w-full text-left p-1.5 rounded-md text-xs transition-colors duration-200 ${ isOverdue(nf) ? 'bg-red-500/20 hover:bg-red-500/40 border-l-4 border-red-500' : 'bg-primary-medium/20 hover:bg-primary-medium/40 border-l-4 border-primary-light'}`}
                  >
                    <div className="flex items-start gap-2">
                        <div className={`w-2 h-2 rounded-full mt-1 flex-shrink-0 ${statusColor(nf)}`}></div>
                        <div>
                            <p className="font-bold text-white truncate">NF: {nf.numeroNF}</p>
                            <p className="text-gray-400 truncate">{nf.fornecedor}</p>
                        </div>
                    </div>
                  </button>
                ))}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default CalendarView;
