
import React, { useState } from 'react';
import { GRD, NotaFiscal } from '../types';
import GrdDetailModal from './GrdDetailModal';
import DocumentDuplicateIcon from './icons/DocumentDuplicateIcon';

interface GrdViewProps {
  grds: GRD[];
  nfs: NotaFiscal[];
}

const GrdView: React.FC<GrdViewProps> = ({ grds, nfs }) => {
  const [viewingGrd, setViewingGrd] = useState<GRD | null>(null);

  const handleViewGrd = (grdId: string) => {
    const grd = grds.find(g => g.id === grdId);
    if (grd) {
      setViewingGrd(grd);
    }
  };

  return (
    <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-8 animate-fade-in-up">
      <h2 className="text-3xl font-bold text-white mb-8">Documentos GRD Emitidos</h2>
      {grds.length > 0 ? (
        <div className="bg-primary-medium/20 border border-primary-medium/50 rounded-2xl shadow-lg">
          <ul className="divide-y divide-primary-medium/50">
            {grds.map((grd) => (
              <li key={grd.id}>
                <button 
                    onClick={() => handleViewGrd(grd.id)}
                    className="w-full flex justify-between items-center p-4 sm:p-6 hover:bg-primary-medium/30 transition-colors duration-200 text-left"
                >
                    <div className="flex items-center gap-4">
                        <div className="bg-primary-light/20 p-3 rounded-full text-primary-light">
                            <DocumentDuplicateIcon className="w-6 h-6" />
                        </div>
                        <div>
                            <p className="font-bold text-xl text-white">GRD Nº {grd.numeroGRD}</p>
                            <p className="text-sm text-gray-400">
                                Emitido em: {new Date(grd.dataEmissao).toLocaleDateString('pt-BR')}
                            </p>
                        </div>
                    </div>
                    <div className="text-right">
                        <p className="font-bold text-lg text-white">{grd.nfIds.length} NFs</p>
                        <p className="text-sm text-gray-400">incluídas</p>
                    </div>
                </button>
              </li>
            ))}
          </ul>
        </div>
      ) : (
        <div className="text-center py-20 bg-primary-medium/10 rounded-2xl">
            <DocumentDuplicateIcon className="w-16 h-16 mx-auto text-primary-medium" />
            <h3 className="mt-4 text-xl font-semibold text-white">Nenhum GRD emitido</h3>
            <p className="mt-2 text-gray-400">Documentos gerados pelo Conferente aparecerão aqui.</p>
        </div>
      )}

      {viewingGrd && (
        <GrdDetailModal 
            grd={viewingGrd}
            relatedNFs={nfs.filter(nf => viewingGrd.nfIds.includes(nf.id))}
            onClose={() => setViewingGrd(null)}
        />
      )}
    </div>
  );
};

export default GrdView;
