
import React from 'react';
import { NotaFiscal, HistoryEntry, NFStatus } from '../types';
import ClipboardListIcon from './icons/ClipboardListIcon';
import BoxIcon from './icons/BoxIcon';
import CheckCircleIcon from './icons/CheckCircleIcon';
import UserIcon from './icons/UserIcon';


interface NFHistoryModalProps {
  nf: NotaFiscal;
  onClose: () => void;
}

const statusIcons = {
    [NFStatus.PENDENTE]: <ClipboardListIcon className="w-6 h-6 text-yellow-400" />,
    [NFStatus.RECEBIDO]: <BoxIcon className="w-6 h-6 text-blue-400" />,
    [NFStatus.CONFERIDO]: <CheckCircleIcon className="w-6 h-6 text-green-400" />,
};

const getLeadTime = (startDate: string, endDate: string) => {
    const start = new Date(startDate).getTime();
    const end = new Date(endDate).getTime();
    const diff = end - start;
    
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    
    let result = '';
    if (days > 0) result += `${days}d `;
    if (hours > 0) result += `${hours}h `;
    if (minutes > 0) result += `${minutes}m`;
    
    return result.trim() || '0m';
};


const NFHistoryModal: React.FC<NFHistoryModalProps> = ({ nf, onClose }) => {
  const recebidoEntry = nf.history.find(h => h.status === NFStatus.RECEBIDO);
  const conferidoEntry = nf.history.find(h => h.status === NFStatus.CONFERIDO);
  
  const leadTime = (recebidoEntry && conferidoEntry) 
    ? getLeadTime(recebidoEntry.date, conferidoEntry.date)
    : null;

  return (
    <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
      <div className="bg-primary-dark border border-primary-medium rounded-2xl shadow-2xl shadow-primary-light/10 w-full max-w-2xl max-h-[90vh] flex flex-col transform transition-all duration-300 scale-95 animate-fade-in-up">
        <div className="p-6 border-b border-primary-medium/50 flex justify-between items-center">
          <h2 className="text-2xl font-bold text-white">Histórico da NF: <span className="text-primary-light">{nf.numeroNF}</span></h2>
          <button onClick={onClose} className="text-gray-400 hover:text-white transition-colors text-3xl font-light">&times;</button>
        </div>
        
        <div className="p-6 overflow-y-auto">
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-6 bg-primary-medium/10 p-4 rounded-lg">
                <InfoDetail label="Pedido" value={nf.numeroPedido} />
                <InfoDetail label="Fornecedor" value={nf.fornecedor} />
                <InfoDetail label="Emissão NF" value={new Date(nf.dataEmissao).toLocaleDateString('pt-BR', { timeZone: 'UTC' })} />
                <InfoDetail label="Prev. Entrega" value={new Date(nf.dataPrevisao).toLocaleDateString('pt-BR', { timeZone: 'UTC' })} />
                {nf.volumesRecebidos !== undefined && <InfoDetail label="Volumes Recebidos" value={String(nf.volumesRecebidos)} />}
                {nf.numeroCTE && <InfoDetail label="CT-e" value={nf.numeroCTE} />}
                {leadTime && <InfoDetail label="Lead Time (Rec ➜ Conf)" value={leadTime} />}
                {nf.grdNumero && <InfoDetail label="GRD Nº" value={String(nf.grdNumero)} />}
                {nf.observacao && <InfoDetail label="Observação" value={nf.observacao} className="sm:col-span-2" />}
            </div>

            <div className="space-y-4">
                {nf.history.map((entry, index) => (
                    <div key={index}>
                        <div className="flex items-center space-x-4">
                             <div className="bg-primary-medium/20 p-3 rounded-full">
                                {statusIcons[entry.status]}
                            </div>
                            <div className="flex-1">
                                <p className="font-bold text-lg text-white">{entry.status}</p>
                                <div className="flex items-center space-x-2 text-sm text-gray-400 mt-1">
                                    <UserIcon className="w-4 h-4" />
                                    <span>{entry.user}</span>
                                    <span>&bull;</span>
                                    <span>{new Date(entry.date).toLocaleString('pt-BR')}</span>
                                </div>
                            </div>
                        </div>
                        
                        {index < nf.history.length - 1 && (
                            <div className="ml-7 mt-2 flex items-center">
                               <div className="h-8 w-px bg-primary-medium/50 mr-4"></div>
                            </div>
                        )}
                    </div>
                ))}
            </div>
        </div>
      </div>
    </div>
  );
};

const InfoDetail: React.FC<{label: string, value: string, className?: string}> = ({ label, value, className }) => (
    <div className={className}>
        <p className="text-sm text-gray-400">{label}</p>
        <p className="font-semibold text-white">{value}</p>
    </div>
);


export default NFHistoryModal;
