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

interface GenerateGrdModalProps {
  nfs: NotaFiscal[];
  onClose: () => void;
  onGenerate: (selectedNfIds: string[], observacao: string) => void;
}

const GenerateGrdModal: React.FC<GenerateGrdModalProps> = ({ nfs, onClose, onGenerate }) => {
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [observacao, setObservacao] = useState('');

  const availableNFs = nfs.filter(nf => nf.status === NFStatus.CONFERIDO && !nf.grdId);

  const handleToggle = (id: string) => {
    setSelectedIds(prev => {
      const newSet = new Set(prev);
      if (newSet.has(id)) {
        newSet.delete(id);
      } else {
        newSet.add(id);
      }
      return newSet;
    });
  };
  
  const handleToggleAll = () => {
    if(selectedIds.size === availableNFs.length) {
        setSelectedIds(new Set());
    } else {
        setSelectedIds(new Set(availableNFs.map(nf => nf.id)));
    }
  }

  const handleGenerate = () => {
    onGenerate(Array.from(selectedIds), observacao);
  };
  
  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 p-6 sm:p-8 transform transition-all duration-300 scale-95 animate-fade-in-up flex flex-col max-h-[80vh]">
        <div className="flex justify-between items-center mb-6 flex-shrink-0">
          <h2 className="text-2xl font-bold text-white">Gerar GRD</h2>
          <button onClick={onClose} className="text-gray-400 hover:text-white transition-colors text-3xl">&times;</button>
        </div>

        {availableNFs.length > 0 ? (
          <>
            <div className="border-b border-primary-medium/50 pb-4 mb-4 flex-shrink-0">
                <div className="flex items-center">
                    <input
                        type="checkbox"
                        id="selectAll"
                        checked={selectedIds.size > 0 && selectedIds.size === availableNFs.length}
                        onChange={handleToggleAll}
                        className="h-5 w-5 rounded border-gray-300 text-primary-light focus:ring-primary-light bg-primary-dark/50"
                    />
                    <label htmlFor="selectAll" className="ml-3 text-sm font-medium text-white">
                        Selecionar Todos ({selectedIds.size}/{availableNFs.length})
                    </label>
                </div>
            </div>
            <div className="overflow-y-auto space-y-3 pr-2 -mr-4">
              {availableNFs.map(nf => (
                <div key={nf.id} className="flex items-center p-3 bg-primary-medium/20 rounded-lg">
                  <input
                    type="checkbox"
                    id={`nf-${nf.id}`}
                    checked={selectedIds.has(nf.id)}
                    onChange={() => handleToggle(nf.id)}
                    className="h-5 w-5 rounded border-gray-300 text-primary-light focus:ring-primary-light bg-primary-dark/50"
                  />
                  <label htmlFor={`nf-${nf.id}`} className="ml-4 flex-grow cursor-pointer">
                    <p className="font-bold text-white">NF: {nf.numeroNF}</p>
                    <p className="text-sm text-gray-300">{nf.fornecedor}</p>
                    <p className="text-xs text-gray-400">Pedido: {nf.numeroPedido}</p>
                  </label>
                </div>
              ))}
            </div>

            <div className="mt-4 flex-shrink-0">
              <label htmlFor="grd-observacao" className="block text-sm font-medium text-gray-300 mb-1">Observação (Opcional)</label>
              <textarea
                id="grd-observacao"
                value={observacao}
                onChange={(e) => setObservacao(e.target.value)}
                rows={2}
                className="w-full bg-primary-dark/50 border border-primary-medium rounded-lg px-3 py-2 text-white focus:ring-2 focus:ring-primary-light focus:border-primary-light transition"
                placeholder="Esta observação aparecerá para todos os itens no documento GRD."
              ></textarea>
            </div>

            <div className="flex justify-end pt-6 space-x-3 flex-shrink-0">
              <button type="button" onClick={onClose} className="px-6 py-2 rounded-full text-white bg-gray-600 hover:bg-gray-500 transition-colors">Cancelar</button>
              <button 
                type="button" 
                onClick={handleGenerate}
                disabled={selectedIds.size === 0}
                className="px-6 py-2 rounded-full font-semibold text-primary-dark bg-primary-light hover:bg-opacity-90 transition-colors shadow-md shadow-primary-light/20 disabled:bg-gray-500 disabled:cursor-not-allowed disabled:shadow-none"
              >
                Gerar GRD
              </button>
            </div>
          </>
        ) : (
          <div className="text-center py-10">
            <p className="text-gray-400 text-lg">Nenhuma NF conferida está disponível para gerar GRD.</p>
          </div>
        )}
      </div>
    </div>
  );
};

export default GenerateGrdModal;