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

interface DashboardProps {
  nfs: NotaFiscal[];
  userRole: UserRole;
  onUpdateStatus: (id: string, newStatus: NFStatus) => void;
  onRequestRecebimento: (id: string) => void;
  onShowHistory: (id: string) => void;
  onOpenGrdModal: () => void;
}

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;
};

type FilterType = NFStatus | 'Todos' | 'Atrasado';

const Dashboard: React.FC<DashboardProps> = ({ nfs, userRole, onUpdateStatus, onRequestRecebimento, onShowHistory, onOpenGrdModal }) => {
  const [activeFilter, setActiveFilter] = useState<FilterType>('Todos');
  const [searchQuery, setSearchQuery] = useState<string>('');

  const filters: FilterType[] = ['Todos', NFStatus.PENDENTE, 'Atrasado', NFStatus.RECEBIDO, NFStatus.CONFERIDO];

  const filteredNFs = useMemo(() => {
    const lowercasedQuery = searchQuery.toLowerCase().trim();
    
    let results = nfs;

    if (activeFilter !== 'Todos') {
      if (activeFilter === 'Atrasado') {
        results = results.filter(nf => isOverdue(nf));
      } else if (activeFilter === NFStatus.PENDENTE) {
        results = results.filter(nf => nf.status === NFStatus.PENDENTE && !isOverdue(nf));
      } else {
        results = results.filter((nf) => nf.status === activeFilter);
      }
    }

    if (lowercasedQuery) {
      results = results.filter(nf => 
        nf.numeroNF.toLowerCase().includes(lowercasedQuery) ||
        nf.fornecedor.toLowerCase().includes(lowercasedQuery) ||
        nf.numeroPedido.toLowerCase().includes(lowercasedQuery)
      );
    }
    
    results.sort((a, b) => {
        const aIsOverdue = isOverdue(a);
        const bIsOverdue = isOverdue(b);
        if (aIsOverdue && !bIsOverdue) return -1;
        if (!aIsOverdue && bIsOverdue) return 1;
        return new Date(b.dataEmissao).getTime() - new Date(a.dataEmissao).getTime();
    });

    return results;
  }, [nfs, activeFilter, searchQuery]);

  return (
    <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div className="flex flex-col sm:flex-row items-center justify-between gap-4 mb-8">
         <div className="w-full sm:max-w-xs">
           <input
            type="text"
            placeholder="Buscar por NF, Fornecedor, Pedido..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full bg-primary-dark/50 border border-primary-medium rounded-full px-4 py-2.5 text-white placeholder-gray-400 focus:ring-2 focus:ring-primary-light focus:border-primary-light transition"
          />
        </div>
        <div className="flex items-center gap-4">
            <div className="flex items-center space-x-2 bg-primary-medium/20 p-1 rounded-full">
            {filters.map((filter) => (
                <button
                key={filter}
                onClick={() => setActiveFilter(filter)}
                className={`px-4 py-2 text-sm font-semibold rounded-full transition-all duration-300 ${
                    activeFilter === filter
                    ? filter === 'Atrasado' ? 'bg-red-500 text-white shadow-md' : 'bg-primary-light text-primary-dark shadow-md'
                    : 'text-gray-300 hover:bg-primary-medium/50 hover:text-white'
                }`}
                >
                {filter}
                </button>
            ))}
            </div>
            {userRole === UserRole.CONFERENTE && (
            <button
                onClick={onOpenGrdModal}
                className="flex items-center justify-center gap-2 px-5 py-2 font-semibold text-primary-dark bg-primary-light rounded-full hover:bg-opacity-90 transition-colors shadow-md shadow-primary-light/20"
            >
                <DocumentDuplicateIcon className="w-5 h-5" />
                <span>Gerar GRD</span>
            </button>
            )}
        </div>
      </div>

      {/* Perfil foi movido para modal acionado pelo ícone no Header */}

      {filteredNFs.length > 0 ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
          {filteredNFs.map((nf) => (
            <NFCard key={nf.id} nf={nf} userRole={userRole} onUpdateStatus={onUpdateStatus} onRequestRecebimento={onRequestRecebimento} onShowHistory={onShowHistory} />
          ))}
        </div>
      ) : (
        <div className="text-center py-16">
            <p className="text-gray-400 text-lg">Nenhuma Nota Fiscal encontrada para este filtro.</p>
        </div>
      )}
    </div>
  );
};

export default Dashboard;
