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

interface NFCardProps {
  nf: NotaFiscal;
  userRole: UserRole;
  onUpdateStatus: (id: string, newStatus: NFStatus) => void;
  onRequestRecebimento: (id: string) => void;
  onShowHistory: (id: string) => void;
}

const statusConfig = {
  [NFStatus.PENDENTE]: {
    label: 'Pendente',
    color: 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30',
    icon: <ClipboardListIcon className="w-5 h-5" />,
    actionText: 'Confirmar Recebimento',
    nextStatus: NFStatus.RECEBIDO,
    allowedRole: UserRole.ALMOXARIFE,
  },
  [NFStatus.RECEBIDO]: {
    label: 'Recebido',
    color: 'bg-blue-500/20 text-blue-400 border-blue-500/30',
    icon: <BoxIcon className="w-5 h-5" />,
    actionText: 'Confirmar Conferência',
    nextStatus: NFStatus.CONFERIDO,
    allowedRole: UserRole.CONFERENTE,
  },
  [NFStatus.CONFERIDO]: {
    label: 'Conferido',
    color: 'bg-green-500/20 text-green-400 border-green-500/30',
    icon: <CheckCircleIcon className="w-5 h-5" />,
    actionText: '',
    nextStatus: null,
    allowedRole: null,
  },
};

const NFCard: React.FC<NFCardProps> = ({ nf, userRole, onUpdateStatus, onRequestRecebimento, onShowHistory }) => {
  const isOverdue = React.useMemo(() => {
    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;
  }, [nf.status, nf.dataPrevisao]);

  let config;
  if (isOverdue) {
    config = {
      label: 'Atrasado',
      color: 'bg-red-500/20 text-red-400 border-red-500/30',
      icon: <ExclamationTriangleIcon className="w-5 h-5" />,
      actionText: 'Confirmar Recebimento',
      nextStatus: NFStatus.RECEBIDO,
      allowedRole: UserRole.ALMOXARIFE,
    };
  } else {
    config = statusConfig[nf.status];
  }

  const formatDate = (dateString?: string) => {
    if (!dateString) return 'N/A';
    // Handles both YYYY-MM-DD and ISO strings
    return new Date(dateString).toLocaleDateString('pt-BR', { timeZone: 'UTC' });
  };
  
  const handleActionClick = () => {
      if (!config.nextStatus) return;

      if(config.nextStatus === NFStatus.RECEBIDO) {
        onRequestRecebimento(nf.id);
      } else if (config.nextStatus === NFStatus.CONFERIDO) {
        onUpdateStatus(nf.id, config.nextStatus);
      }
  };

  return (
    <div className={`bg-primary-medium/20 border rounded-2xl p-4 shadow-lg hover:shadow-primary-light/20 transition-all duration-300 flex flex-col justify-between ${isOverdue ? 'border-red-500/50 hover:border-red-400/50' : 'border-primary-medium/50 hover:border-primary-light/50'}`}>
      <div>
        <div className="flex justify-between items-start mb-2">
          <p className="text-sm text-gray-400">Pedido: {nf.numeroPedido}</p>
          <div className={`flex items-center space-x-2 text-sm font-semibold px-3 py-1 rounded-full border ${config.color}`}>
            {config.icon}
            <span>{config.label}</span>
          </div>
        </div>
        <button onClick={() => onShowHistory(nf.id)} className="text-left w-full group">
            <h3 className="text-xl font-bold text-white mb-1 group-hover:text-primary-light transition-colors">NF: {nf.numeroNF}</h3>
        </button>
        <p className="text-primary-light font-medium mb-3">{nf.fornecedor}</p>
        
        <div className="grid grid-cols-2 gap-x-4 gap-y-2 text-sm text-gray-300">
            <InfoItem label="Prev. Entrega" value={formatDate(nf.dataPrevisao)} />
            <InfoItem label="Recebimento" value={formatDate(nf.dataRecebimento)} />
            <InfoItem label="Conferência" value={formatDate(nf.dataConferencia)} />
            {nf.volumesRecebidos !== undefined && <InfoItem label="Volumes" value={String(nf.volumesRecebidos)} />}
            {nf.numeroCTE && <InfoItem label="CT-e" value={nf.numeroCTE} />}
        </div>

      </div>

      <div className="mt-4">
        {userRole === config.allowedRole && config.nextStatus && (
          <button
            onClick={handleActionClick}
            className="w-full bg-primary-light text-primary-dark font-bold py-2 px-4 rounded-lg hover:bg-opacity-90 transition-transform duration-200 transform hover:scale-105 shadow-md shadow-primary-light/20"
          >
            {config.actionText}
          </button>
        )}
      </div>
    </div>
  );
};

const InfoItem: React.FC<{ label: string; value: string }> = ({ label, value }) => (
    <div>
        <span className="text-gray-500 font-medium">{label}: </span>
        <span>{value}</span>
    </div>
);

export default NFCard;
