import React, { useState, useEffect, useMemo } from 'react';
import { 
  ArrowLeft, 
  FileText, 
  FileCheck, 
  CheckCircle, 
  XCircle, 
  Save, 
  ChevronRight,
  ShieldAlert,
  Car,
  CreditCard,
  Building,
  ExternalLink,
  Archive
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useGrStore } from '../services/useGrStore';
import * as grService from '../services/grService';

export const GrRegistrationDetails = ({ 
  data, 
  onClose, 
  onSave, 
  onNext, 
  onApprove, 
  onReject,
  onArchive,
  isReadOnly = false
}) => {

  if (!data) return null;

  const [activeDoc, setActiveDoc] = useState(null);
  const [formData, setFormData] = useState({});
  const [bases, setBases] = useState([]);
  const { userData } = useGrStore();
  const currentUser = userData?.usuario;

  useEffect(() => {
    if (data) {
      // Helper to convert DD/MM/YYYY to YYYY-MM-DD for input[type="date"]
      const parseDate = (dateStr) => {
        if (!dateStr) return '';
        if (dateStr.includes('/')) {
          const parts = dateStr.split('/');
          if (parts.length === 3) {
            // Assumes DD/MM/YYYY
            return `${parts[2]}-${parts[1]}-${parts[0]}`;
          }
        }
        return dateStr;
      };

      setFormData({
        ...data,
        data_nascimento: parseDate(data.data_nascimento),
        validade_cnh: parseDate(data.validade_cnh),
        // Base comes only from existing record data, no auto-fill from user
        base: data.base || ''
      });
    }
  }, [data, currentUser]);

  useEffect(() => {
    const fetchBases = async () => {
      try {
        const response = await grService.getBases();
        const basesList = response.Base_Dados_API || response.dados || response || [];
        setBases(Array.isArray(basesList) ? basesList : []);
      } catch (error) {
        console.error("Error fetching bases:", error);
      }
    };
    fetchBases();
  }, []);

  const filteredBases = useMemo(() => {
    if (!bases) return [];

    // Admin or explicit 'Todas' access gets all bases
    const isAdmin = currentUser?.grupo === 'Administrador';
    const hasFullAccess = currentUser?.base === 'Todas' || currentUser?.base?.includes('Todas');

    if (isAdmin || hasFullAccess) {
        return bases;
    }

    if (!currentUser?.base) return bases || [];
    
    const userAllowedBases = currentUser.base.split(',').map(b => b.trim());
    return bases.filter(b => userAllowedBases.includes((b.base || b.nome)?.trim()));
  }, [bases, currentUser]);

  // Determine available documents based on real API fields
  const documents = [
    { id: 'cnh', label: 'CNH (Frente e Verso)', icon: CreditCard, available: !!data?.cnh_frente || !!data?.cnh_verso },
    { id: 'comprovante', label: 'Comprovante de Residência', icon: Building, available: !!data?.comprovante_residencia },
    { id: 'veiculo', label: 'Documentação do Veículo', icon: Car, available: !!data?.crlv },
    { id: 'cnpj', label: 'CNPJ', icon: FileText, available: !!data?.cartao_cnpj },
    { id: 'antt', label: 'ANTT', icon: FileText, available: !!data?.antt },
    { id: 'direcao', label: 'Direção Defensiva', icon: FileCheck, available: !!data?.direcao_defensiva },
    { id: 'toxico', label: 'Exame Toxicológico', icon: ShieldAlert, available: !!data?.exame_toxico },
    { id: 'owner_cnh_file', label: 'CNH Responsável', icon: CreditCard, available: !!data?.owner_cnh_file },
  ];

  const handleInputChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const getDocFiles = (docId) => {
    switch(docId) {
      case 'cnh': return [data?.cnh_frente, data?.cnh_verso].filter(Boolean);
      case 'comprovante': return [data?.comprovante_residencia].filter(Boolean);
      case 'veiculo': return [data?.crlv].filter(Boolean);
      case 'cnpj': return [data?.cartao_cnpj].filter(Boolean);
      case 'antt': return [data?.antt].filter(Boolean);
      case 'direcao': return [data?.direcao_defensiva].filter(Boolean);
      case 'toxico': return [data?.exame_toxico].filter(Boolean);
      case 'owner_cnh_file': return [data?.owner_cnh_file].filter(Boolean);
      default: return [];
    }
  };

   const isReviewMode = ['Em Análise', 'Pendências / Revisão'].includes(data?.global_status);

  return (
    <div className="flex flex-col h-full bg-slate-50 dark:bg-[#141414]">
      {/* Header */}
      <header className="h-16 px-6 bg-white dark:bg-[#1a1a1a] border-b border-slate-200 dark:border-white/5 flex items-center justify-between shrink-0">
        <div className="flex items-center gap-4">
          <button 
            onClick={onClose}
            className="p-2 hover:bg-slate-100 dark:hover:bg-white/5 rounded-full transition-colors text-slate-500"
          >
            <ArrowLeft size={20} />
          </button>
          <div className="flex flex-col">
            <h2 className="text-sm font-bold text-slate-800 dark:text-white uppercase tracking-wide flex items-center gap-2">
              Análise de Candidato: <span className="text-[var(--gr-primary)]">{data.nome_completo}</span>
            </h2>
          </div>
        </div>

        <div className="flex items-center gap-4">
            <div className="text-right mr-4 hidden md:block">
              <span className="text-[10px] uppercase font-bold text-slate-400 block">Status Atual</span>
              <span className={cn(
                "text-sm font-bold",
                formData.global_status === 'Aprovado' ? "text-emerald-500" : 
                formData.global_status === 'Recusado' ? "text-red-500" : 
                formData.global_status === 'Pendências / Revisão' ? "text-orange-500" :
                "text-amber-500"
              )}>{formData.global_status}</span>
           </div>

           {!isReadOnly && isReviewMode && (
             <div className="flex items-center gap-2">
               <button 
                 onClick={() => onApprove(data)}
                 className="flex items-center gap-2 px-4 py-2 bg-emerald-500 hover:bg-emerald-600 text-white rounded-lg text-xs font-bold uppercase tracking-wider transition-all shadow-lg shadow-emerald-500/20 active:scale-95"
               >
                 <CheckCircle size={16} />
                 Aprovado
               </button>
               <button 
                onClick={() => onReject(data)}
                 className="flex items-center gap-2 px-4 py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg text-xs font-bold uppercase tracking-wider transition-all shadow-lg shadow-red-500/20 active:scale-95"
               >
                 <XCircle size={16} />
                 Reprovado
               </button>
             </div>
           )}

        </div>
      </header>

      {/* Main Layout */}
      <div className="flex-1 overflow-hidden flex flex-col lg:flex-row">
        
        {/* Left Sidebar - Documents */}
        <div className="w-full lg:w-64 bg-white dark:bg-[#1a1a1a] border-r border-slate-200 dark:border-white/5 flex flex-col shrink-0">
           <div className="p-4 border-b border-slate-200 dark:border-white/5">
              <h3 className="text-xs font-bold text-slate-400 uppercase tracking-widest">Documentos</h3>
           </div>
           
           <div className="flex-1 overflow-y-auto p-3 space-y-2">
             {documents.filter(d => d.available).map((doc) => (
               <button
                 key={doc.id}
                 onClick={() => setActiveDoc(doc.id)}
                 className={cn(
                   "w-full flex items-center gap-3 p-3 rounded-xl transition-all text-left group",
                   activeDoc === doc.id 
                     ? "bg-[var(--gr-primary)]/10 text-[var(--gr-primary)] border border-[var(--gr-primary)]/20" 
                     : "hover:bg-slate-50 dark:hover:bg-white/5 text-slate-600 dark:text-slate-400 border border-transparent"
                 )}
               >
                 <div className={cn(
                   "w-8 h-8 rounded-lg flex items-center justify-center transition-colors",
                   activeDoc === doc.id ? "bg-[var(--gr-primary)] text-white" : "bg-slate-100 dark:bg-white/5 text-slate-400 group-hover:bg-slate-200"
                 )}>
                   <doc.icon size={16} />
                 </div>
                 <span className="text-[10px] font-bold uppercase tracking-wide flex-1 leading-tight">{doc.label}</span>
               </button>
             ))}
             
             {documents.filter(d => d.available).length === 0 && (
                <div className="p-4 text-center text-slate-400 text-xs italic">
                    Nenhum documento disponível.
                </div>
             )}
           </div>
        </div>

        {/* Center - Preview */}
        <div className="flex-1 bg-slate-100 dark:bg-[#0f0f0f] relative flex flex-col min-h-[400px]">
           {activeDoc ? (
             <div className="flex-1 p-4 md:p-8 flex flex-col items-center justify-start overflow-auto">
                <div className="w-full max-w-4xl space-y-4">
                    {getDocFiles(activeDoc).map((url, idx) => {
                        const isPdf = url.toLowerCase().endsWith('.pdf');
                        return (
                            <div key={idx} className="bg-white dark:bg-[#1a1a1a] shadow-xl rounded-xl overflow-hidden border border-slate-200 dark:border-white/5">
                                <div className="p-3 border-b border-slate-100 dark:border-white/5 flex items-center justify-between">
                                    <span className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Página {idx + 1}</span>
                                    <a 
                                      href={url} 
                                      target="_blank" 
                                      rel="noopener noreferrer"
                                      className="p-1.5 hover:bg-slate-100 dark:hover:bg-white/5 rounded-lg text-[var(--gr-primary)] transition-colors"
                                    >
                                        <ExternalLink size={14} />
                                    </a>
                                </div>
                                <div className="p-4 flex items-center justify-center bg-slate-50 dark:bg-black/20">
                                    {isPdf ? (
                                        <iframe 
                                            src={url} 
                                            className="w-full aspect-[1/1.4] rounded-lg shadow-sm"
                                            title={`Document ${idx}`}
                                        />
                                    ) : (
                                        <img 
                                            src={url} 
                                            alt={`Document ${idx}`} 
                                            className="max-w-full h-auto rounded-lg shadow-sm"
                                        />
                                    )}
                                </div>
                            </div>
                        );
                    })}
                </div>
             </div>
           ) : (
             <div className="flex-1 flex flex-col items-center justify-center text-slate-400">
               <FileText size={48} className="mb-4 opacity-20" />
               <p className="text-sm font-medium">Selecione um documento para visualizar</p>
             </div>
           )}
        </div>

        {/* Right Sidebar - Form */}
        <div className="w-full lg:w-[450px] bg-white dark:bg-[#1a1a1a] border-l border-slate-200 dark:border-white/5 flex flex-col shrink-0">
          <div className="p-4 border-b border-slate-200 dark:border-white/5 bg-slate-50/50 dark:bg-white/[0.02]">
             <h3 className="text-xs font-bold text-slate-400 uppercase tracking-widest flex items-center gap-2">
               <FileText size={14} className="text-[var(--gr-primary)]" />
               Dados do Candidato
             </h3>
           </div>

           <div className="flex-1 overflow-y-auto p-6 space-y-8 custom-scrollbar">
              {/* Seção: Informações Básicas */}
              <div className="space-y-4">
                  <h4 className="text-[10px] font-bold text-[var(--gr-primary)] uppercase tracking-[0.2em] border-b border-slate-100 dark:border-white/5 pb-1">Básico & Status</h4>
                  <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-1">
                          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Modalidade</label>
                          <select 
                            value={formData.modalidade || ''}
                            onChange={(e) => handleInputChange('modalidade', e.target.value)}
                            disabled={isReadOnly}
                          >
                              <option value="" className="bg-white dark:bg-[#1a1a1a]">-- Selecione --</option>
                              <option value="Agregado" className="bg-white dark:bg-[#1a1a1a]">Agregado</option>
                              <option value="Rentals" className="bg-white dark:bg-[#1a1a1a]">Rentals</option>
                              <option value="Frota Fixa Diarista" className="bg-white dark:bg-[#1a1a1a]">Frota Fixa Diarista</option>
                              <option value="Frota Fixa Mensal" className="bg-white dark:bg-[#1a1a1a]">Frota Fixa Mensal</option>
                          </select>
                      </div>
                      <div className="space-y-1">
                          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Origem</label>
                          <input 
                            type="text" 
                            disabled
                            value={formData.interno_externo || 'Não informado'}
                            className="w-full p-2.5 bg-slate-100 dark:bg-white/[0.02] border border-slate-200 dark:border-white/10 rounded-lg text-sm font-medium text-slate-400 focus:outline-none cursor-not-allowed"
                          />
                      </div>
                  </div>

                  <div className="space-y-1">
                      <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Nome Completo</label>
                      <input 
                        type="text" 
                        value={formData.nome_completo || ''} 
                        onChange={(e) => handleInputChange('nome_completo', e.target.value)}
                        className="w-full p-2.5 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-lg text-sm font-medium text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)] transition-all"
                      />
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-1">
                          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">CPF</label>
                          <input 
                            type="text" 
                            value={formData.cpf || ''}
                            onChange={(e) => handleInputChange('cpf', e.target.value)}
                            disabled={isReadOnly}
                            className="w-full p-2.5 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-lg text-sm font-medium text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)]"
                          />
                      </div>
                      <div className="space-y-1">
                          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Data Nasc.</label>
                          <input 
                            type="date" 
                            value={formData.data_nascimento || ''}
                            onChange={(e) => handleInputChange('data_nascimento', e.target.value)}
                            disabled={isReadOnly}
                            className="w-full p-2.5 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-lg text-sm font-medium text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)]"
                          />
                      </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-1">
                          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">CNH</label>
                          <input 
                            type="text" 
                            value={formData.cnh || ''}
                            onChange={(e) => handleInputChange('cnh', e.target.value)}
                            disabled={isReadOnly}
                            className="w-full p-2.5 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-lg text-sm font-medium text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)]"
                          />
                      </div>
                      <div className="space-y-1">
                          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Validade CNH</label>
                          <input 
                            type="date" 
                            value={formData.validade_cnh || ''}
                            onChange={(e) => handleInputChange('validade_cnh', e.target.value)}
                            disabled={isReadOnly}
                            className="w-full p-2.5 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-lg text-sm font-medium text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)]"
                          />
                      </div>
                  </div>
              </div>

              {/* Seção: Contato */}
              <div className="space-y-4">
                  <h4 className="text-[10px] font-bold text-[var(--gr-primary)] uppercase tracking-[0.2em] border-b border-slate-100 dark:border-white/5 pb-1">Contato</h4>
                  <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-1">
                          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Telefone</label>
                          <input 
                            type="text" 
                            value={formData.telefone || ''}
                            onChange={(e) => handleInputChange('telefone', e.target.value)}
                            disabled={isReadOnly}
                            className="w-full p-2.5 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-lg text-sm font-medium text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)]"
                          />
                      </div>
                      <div className="space-y-1">
                          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">E-mail</label>
                          <input 
                            type="email" 
                            value={formData.email || ''}
                            onChange={(e) => handleInputChange('email', e.target.value)}
                            disabled={isReadOnly}
                            className="w-full p-2.5 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-lg text-sm font-medium text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)]"
                          />
                      </div>
                  </div>
              </div>

              {/* Seção: Endereço */}
              <div className="space-y-4">
                  <h4 className="text-[10px] font-bold text-[var(--gr-primary)] uppercase tracking-[0.2em] border-b border-slate-100 dark:border-white/5 pb-1">Localização</h4>
                  <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-1">
                          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">CEP</label>
                          <input 
                            type="text" 
                            value={formData.cep || ''}
                            onChange={(e) => handleInputChange('cep', e.target.value)}
                            disabled={isReadOnly}
                            className="w-full p-2.5 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-lg text-sm font-medium text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)]"
                          />
                      </div>
                      <div className="space-y-1">
                          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Base</label>
                          <select 
                            value={formData.base || ''}
                            onChange={(e) => handleInputChange('base', e.target.value)}
                            disabled={isReadOnly}
                            className="w-full p-2.5 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-lg text-sm font-medium text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)]"
                          >
                            <option value="">Selecione a base</option>
                            {filteredBases.map((b) => (
                              <option key={b.idbase || b.id} value={b.base || b.nome}>
                                {b.base || b.nome}
                              </option>
                            ))}
                          </select>
                      </div>
                  </div>
                  <div className="space-y-1">
                      <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Logradouro</label>
                      <input 
                        type="text" 
                        value={formData.endereco || ''}
                        onChange={(e) => handleInputChange('endereco', e.target.value)}
                        className="w-full p-2.5 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-lg text-sm font-medium text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)]"
                      />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-1">
                          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Bairro</label>
                          <input 
                            type="text" 
                            value={formData.bairro || ''}
                            onChange={(e) => handleInputChange('bairro', e.target.value)}
                            disabled={isReadOnly}
                            className="w-full p-2.5 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-lg text-sm font-medium text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)]"
                          />
                      </div>
                      <div className="space-y-1">
                          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Cidade</label>
                          <input 
                            type="text" 
                            value={formData.cidade || ''}
                            onChange={(e) => handleInputChange('cidade', e.target.value)}
                            disabled={isReadOnly}
                            className="w-full p-2.5 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-lg text-sm font-medium text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)]"
                          />
                      </div>
                  </div>
              </div>

              {/* Seção: Veículo */}
              <div className="space-y-4">
                  <h4 className="text-[10px] font-bold text-[var(--gr-primary)] uppercase tracking-[0.2em] border-b border-slate-100 dark:border-white/5 pb-1">Veículo</h4>
                  <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-1">
                          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Placa</label>
                          <input 
                            type="text" 
                            value={formData.placa_veiculo || ''}
                            onChange={(e) => handleInputChange('placa_veiculo', e.target.value)}
                            className="w-full p-2.5 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-lg text-sm font-bold text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)] uppercase"
                          />
                      </div>
                      <div className="space-y-1">
                          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Tipo Veículo</label>
                          <select 
                            value={formData.tipo_veiculo || ''}
                            onChange={(e) => handleInputChange('tipo_veiculo', e.target.value)}
                            disabled={isReadOnly}
                            className="w-full p-2.5 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-lg text-sm text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)]"
                          >
                              <option value="" className="bg-white dark:bg-[#1a1a1a]">-- Selecione --</option>
                              <option value="carro_passeio" className="bg-white dark:bg-[#1a1a1a]">Carro de Passeio</option>
                              <option value="utilitario" className="bg-white dark:bg-[#1a1a1a]">Utilitário</option>
                              <option value="caminhao" className="bg-white dark:bg-[#1a1a1a]">Caminhão</option>
                              <option value="cavalo" className="bg-white dark:bg-[#1a1a1a]">Cavalo</option>
                              <option value="carreta" className="bg-white dark:bg-[#1a1a1a]">Carreta</option>
                              <option value="moto" className="bg-white dark:bg-[#1a1a1a]">Moto</option>
                          </select>
                      </div>
                  </div>
                  <div className="space-y-1">
                      <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Forma de Trabalho</label>
                      <select 
                        value={formData.forma_trabalho || ''}
                        onChange={(e) => handleInputChange('forma_trabalho', e.target.value)}
                        className="w-full p-2.5 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-lg text-sm text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)]"
                      >
                          <option value="" className="bg-white dark:bg-[#1a1a1a]">-- Selecione --</option>
                          <option value="veiculo_proprio" className="bg-white dark:bg-[#1a1a1a]">Veículo Próprio</option>
                          <option value="terceiro" className="bg-white dark:bg-[#1a1a1a]">De Terceiros</option>
                          <option value="empresa" className="bg-white dark:bg-[#1a1a1a]">Empresa</option>
                      </select>
                  </div>
              </div>

              {/* Seção: Gestão */}
              <div className="space-y-4">
                  <h4 className="text-[10px] font-bold text-[var(--gr-primary)] uppercase tracking-[0.2em] border-b border-slate-100 dark:border-white/5 pb-1">Gestão Interna</h4>
                  <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-1">
                          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Coordenador</label>
                          <input 
                            type="text" 
                            value={formData.coordenador || ''}
                            onChange={(e) => handleInputChange('coordenador', e.target.value)}
                            disabled={isReadOnly}
                            className="w-full p-2.5 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-lg text-sm font-medium text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)]"
                          />
                      </div>
                      <div className="space-y-1">
                          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Despachante</label>
                          <input 
                            type="text" 
                            value={formData.despachante || ''}
                            onChange={(e) => handleInputChange('despachante', e.target.value)}
                            className="w-full p-2.5 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-lg text-sm font-medium text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)]"
                          />
                      </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4 pb-4">
                      {/* <div className="space-y-1 col-span-2">
                          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Status Global</label>
                          <select 
                            value={formData.global_status || ''}
                            onChange={(e) => handleInputChange('global_status', e.target.value)}
                            disabled={isReadOnly}
                            className="w-full p-2.5 bg-amber-50 dark:bg-amber-500/5 border border-amber-200 dark:border-amber-500/20 rounded-lg text-sm font-bold text-amber-700 dark:text-amber-400 focus:outline-none focus:border-amber-500 transition-all"
                          >
                             <option value="Aguardando Análise GR">Aguardando Análise GR</option>
                             <option value="Em Análise">Em Análise</option>
                             <option value="Pendências / Revisão">Pendências / Revisão</option>
                             <option value="Aprovado">Aprovado</option>
                             <option value="Recusado">Recusado</option>
                          </select>
                      </div> */}
                  </div>
                  <div className="space-y-1">
                      <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Observações do Cliente</label>
                      <textarea 
                        rows={3}
                        value={formData.obs_cliente || ''}
                        onChange={(e) => handleInputChange('obs_cliente', e.target.value)}
                            disabled={isReadOnly}
                            className="w-full p-2.5 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-lg text-sm font-medium text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)] resize-none"
                        placeholder="Insira notas adicionais..."
                      />
                  </div>
                  <div className="space-y-1 mt-4">
                      <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Obs. Retorno</label>
                      <textarea 
                        rows={3}
                        value={formData.obs_retorno || ''}
                        onChange={(e) => handleInputChange('obs_retorno', e.target.value)}
                            disabled={isReadOnly}
                            className="w-full p-2.5 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-lg text-sm font-medium text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)] resize-none"
                        placeholder="Observações de retorno para o cliente..."
                      />
                  </div>
              </div>
                  <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-1">
                          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Status Doc. Motorista</label>
                          <select 
                            value={formData.status_doc_motorista || ''}
                            onChange={(e) => handleInputChange('status_doc_motorista', e.target.value)}
                            disabled={isReadOnly}
                            className="w-full p-2.5 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-lg text-sm font-medium text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)]"
                          >
                               <option value="" className="bg-white dark:bg-[#1a1a1a]">-- Selecione --</option>
                               <option value="Aprovado" className="bg-white dark:bg-[#1a1a1a]">Aprovado</option>
                               <option value="Reprovado" className="bg-white dark:bg-[#1a1a1a]">Reprovado</option>
                          </select>
                      </div>
                      <div className="space-y-1">
                          <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Status Doc. Carro</label>
                          <select 
                            value={formData.status_doc_carro || ''}
                            onChange={(e) => handleInputChange('status_doc_carro', e.target.value)}
                            disabled={isReadOnly}
                            className="w-full p-2.5 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-lg text-sm font-medium text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)]"
                          >
                               <option value="" className="bg-white dark:bg-[#1a1a1a]">-- Selecione --</option>
                               <option value="Aprovado" className="bg-white dark:bg-[#1a1a1a]">Aprovado</option>
                               <option value="Reprovado" className="bg-white dark:bg-[#1a1a1a]">Reprovado</option>
                          </select>
                      </div>
                  </div>
           </div>
 
           {/* Footer Actions */}
           {!isReadOnly && (
             <div className="p-6 border-t border-slate-200 dark:border-white/5 bg-slate-50 dark:bg-white/[0.02] grid grid-cols-1 sm:grid-cols-3 gap-4">
                {onArchive && (
                  <button
                    onClick={() => onArchive(formData)}
                    className="py-3.5 bg-slate-200 hover:bg-slate-300 text-slate-800 rounded-[20px] text-[11px] font-bold uppercase tracking-widest transition-all flex items-center justify-center gap-2 shadow-xl shadow-slate-400/10 active:scale-95"
                  >
                    <Archive size={16} /> Arquivar
                  </button>
                )}
                <button 
                  onClick={() => onSave(formData)}
                  className="py-3.5 bg-slate-800 hover:bg-slate-900 text-white rounded-[20px] text-[11px] font-bold uppercase tracking-widest transition-all flex items-center justify-center gap-2 shadow-xl shadow-slate-900/10 active:scale-95"
                >
                  <Save size={16} /> Salvar
                </button>
                <button 
                  onClick={onNext}
                  className="py-3.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-[20px] text-[11px] font-bold uppercase tracking-widest transition-all flex items-center justify-center gap-2 shadow-xl shadow-emerald-600/10 active:scale-95 group"
                >
                  Próximo 
                  <ChevronRight size={16} className="group-hover:translate-x-1 transition-transform" />
                </button>
             </div>
           )}

        </div>

      </div>
    </div>
  );
};
