import React, { useEffect, useState, useMemo, useRef } from 'react';
import { useMaintenance } from '../hooks/useMaintenance';
import { useVehicles } from '../hooks/useVehicles';
import { useWorkshops } from '../hooks/useWorkshops';
import { useFleetLists } from '../hooks/useFleetLists';
import AutocompleteInput from '../components/AutocompleteInput';
import ExcelTable from '../components/ExcelTable';
import { Plus, Search, Edit2, Trash2, Wrench, CheckCircle, Truck, Lock, Unlock, FileText } from 'lucide-react';
import { 
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription 
} from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useFeedback, useFeedbackStore } from '../components/FeedbackNotification';
import { LoadingOverlay } from '../../../components/shared/LoadingOverlay';

// --- Helpers: datas e moeda ---
const DATE_KEYS = ['data_solicitacao', 'data_agendamento', 'data_parada_veiculo', 'previsao_entrega', 'data_finalizacao', 'data_retirada'];

const normalizeDateForInput = (v) => {
  if (v == null || v === '') return '';
  const s = String(v).trim();
  if (!s) return '';
  const iso = s.includes('T') ? s.split('T')[0] : null;
  if (iso && /^\d{4}-\d{2}-\d{2}$/.test(iso)) return iso;
  const ddmmyyyy = s.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
  if (ddmmyyyy) return `${ddmmyyyy[3]}-${ddmmyyyy[2].padStart(2, '0')}-${ddmmyyyy[1].padStart(2, '0')}`;
  if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return s;
  return s;
};

const formatCurrency = (v) => {
  if (v == null || v === '') return 'R$ 0,00';
  const n = typeof v === 'string' ? parseCurrency(v) : Number(v);
  return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(n || 0);
};

// Parse currency: BR (1.234,56 / 2.222.222.222,00) ou US (20.25). Evita "2.222.222.222" virar 2,22.
const parseCurrency = (s) => {
  if (s == null || s === '') return '';
  let t = String(s).trim().replace(/\s/g, '').replace(/R\$\s?/gi, '');
  if (!t) return '';
  // Com vírgula = BR: pontos são milhares, vírgula é decimal
  if (t.includes(',')) {
    t = t.replace(/\./g, '').replace(',', '.');
  } else if (t.includes('.')) {
    // Sem vírgula mas com ponto: "2.222.222.222" (BR milhares) vs "20.25" (US decimal)
    const lastDot = t.lastIndexOf('.');
    const afterDot = t.slice(lastDot + 1);
    const isLikelyUsDecimal = afterDot.length === 2 && /^\d\d$/.test(afterDot) && (t.match(/\./g) || []).length === 1;
    if (!isLikelyUsDecimal) {
      t = t.replace(/\./g, '');
    }
  }
  const n = parseFloat(t);
  return isNaN(n) ? '' : n;
};

// Sempre com vírgula e 2 decimais para ao focar/blur não quebrar (ex.: 2222222222 -> "2.222.222.222,00")
const formatCurrencyForInput = (v) => {
  if (v == null || v === '') return '';
  const n = Number(v);
  if (isNaN(n)) return '';
  return n.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};

const toNumber = (v) => {
  if (v == null || v === '') return '';
  const n = Number(v);
  return isNaN(n) ? '' : n;
};

// Reusing styled components locally or moving to a shared file in future
const DarkInput = ({ label, readOnly, className = '', ...props }) => (
  <div className="space-y-1.5">
    {label && <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider ml-1">{label}</label>}
    <input 
      readOnly={readOnly}
      className={`w-full bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl px-3 py-2 text-sm text-slate-700 dark:text-slate-200 focus:outline-none focus:border-orange-500 focus:ring-1 focus:ring-orange-500 transition-all placeholder:text-slate-400 dark:placeholder:text-slate-700 ${readOnly ? 'cursor-not-allowed opacity-80 bg-slate-100 dark:bg-[#1a1a1a]' : ''} ${className}`}
      {...props}
    />
  </div>
);

const DarkSelect = ({ label, options, value, onChange }) => (
  <div className="space-y-1.5">
    {label && <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider ml-1">{label}</label>}
    <select 
      value={value} 
      onChange={e => onChange(e.target.value)}
      className="w-full bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl px-3 py-2 text-sm text-slate-700 dark:text-slate-200 focus:outline-none focus:border-orange-500 focus:ring-1 focus:ring-orange-500 transition-all cursor-pointer"
    >
      <option value="">Selecione...</option>
      {options.map(opt => (
        <option key={opt} value={opt}>{opt}</option>
      ))}
    </select>
  </div>
);

const DarkButton = ({ children, variant = 'primary', className = '', ...props }) => {
  const baseClass = "px-4 py-2 rounded-xl font-bold text-sm transition-all shadow-lg active:scale-95 flex items-center justify-center gap-2";
  const variants = {
    primary: "bg-orange-600 hover:bg-orange-500 text-white shadow-orange-500/10",
    secondary: "bg-slate-100 dark:bg-[#2a2a2a] hover:bg-slate-200 dark:hover:bg-[#333] text-slate-700 dark:text-slate-200 border border-slate-200 dark:border-[#333]",
    ghost: "bg-transparent hover:bg-slate-100 dark:hover:bg-[#2a2a2a] text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-white"
  };
  
  return (
    <button className={`${baseClass} ${variants[variant]} ${className}`} {...props}>
      {children}
    </button>
  );
};

const CurrencyInput = ({ label, value, onChange, ...props }) => {
  const [focused, setFocused] = useState(false);
  const [local, setLocal] = useState('');
  const isEmpty = value === '' || value == null;
  const display = focused ? local : (isEmpty ? '' : formatCurrency(value));
  return (
    <div className="space-y-1.5">
      {label && <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider ml-1">{label}</label>}
      <input
        type="text"
        inputMode="decimal"
        className="w-full bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl px-3 py-2 text-sm text-slate-700 dark:text-slate-200 focus:outline-none focus:border-orange-500 focus:ring-1 focus:ring-orange-500 transition-all placeholder:text-slate-400 dark:placeholder:text-slate-700"
        placeholder="R$ 0,00"
        value={display}
        onFocus={() => { setFocused(true); setLocal(isEmpty ? '' : formatCurrencyForInput(value)); }}
        onBlur={() => {
          const n = parseCurrency(local);
          onChange(n === '' ? '' : n);
          setFocused(false);
        }}
        onChange={(e) => setLocal(e.target.value)}
        {...props}
      />
    </div>
  );
};

// --- Inline Status Editor for Maintenance ---
const MaintenanceStatusCell = ({ currentStatus, id, options, onUpdate }) => {
  const [isEditing, setIsEditing] = useState(false);
  const [tempValue, setTempValue] = useState(currentStatus);

  useEffect(() => {
    setTempValue(currentStatus);
  }, [currentStatus]);

  const handleBlur = () => {
    setIsEditing(false);
    if (tempValue !== currentStatus) {
      onUpdate(id, tempValue);
    }
  };

  const handleChange = (e) => {
    setTempValue(e.target.value);
  };

  if (isEditing) {
    return (
      <select 
        autoFocus
        value={tempValue}
        onChange={handleChange}
        onBlur={handleBlur}
        className="w-full bg-slate-50 dark:bg-[#141414] border border-orange-500 rounded px-1 py-0.5 text-[10px] uppercase font-bold text-slate-700 dark:text-slate-200 focus:outline-none"
        onClick={(e) => e.stopPropagation()} 
      >
        <option value="">Selecione...</option>
        {options.map(opt => (
          <option key={opt} value={opt}>{opt}</option>
        ))}
      </select>
    );
  }

  return (
    <div 
      onClick={(e) => { e.stopPropagation(); setIsEditing(true); }}
      className={`inline-flex items-center px-2 py-0.5 rounded cursor-pointer hover:opacity-80 transition-opacity text-[9px] font-bold uppercase tracking-wider border ${
        currentStatus?.includes('Pendente') ? 'bg-yellow-500/10 text-yellow-500 border-yellow-500/20' : 
        currentStatus === 'Aprovado' ? 'bg-orange-500/10 text-orange-500 border-orange-500/20' :
        currentStatus === 'Concluído' ? 'bg-orange-500/10 text-orange-500 border-orange-500/20' :
        'bg-slate-700/30 text-slate-400 border-slate-600/30'
      }`}
    >
      {currentStatus || 'Pendente'}
    </div>
  );
};

import { prafrotStatisticsService } from '../services/prafrotStatisticsService';

// Helper function to determine if a maintenance is closed
const isMaintenanceClosed = (status) => {
  if (!status) return false;
  const statusLower = status.toLowerCase();
  const closedStatuses = ['concluído', 'concluido', 'finalizado', 'fechado', 'encerrado', 'cancelado'];
  return closedStatuses.some(closed => statusLower.includes(closed));
};

const DATE_LABELS = {
  data_solicitacao: 'Data Solicitação',
  data_agendamento: 'Data Agendamento',
  data_parada_veiculo: 'Data Parada',
  previsao_entrega: 'Previsão Entrega',
  data_finalizacao: 'Data Finalização',
  data_retirada: 'Data Retirada'
};

const CONDICAO_OPCOES = ['À vista', 'Parcelado'];
const PARCELAS_OPCOES = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

// URL do host atual = arquivo interno (salvo pelo backend); caso contrário = externo (ex.: Google Drive)
const isInternalFileUrl = (url) => {
  if (!url || typeof url !== 'string') return false;
  try {
    const u = new URL(url);
    return u.origin === window.location.origin;
  } catch {
    return false;
  }
};

const DetailSection = ({ title, children }) => (
  <div className="space-y-4">
    <h3 className="text-xs font-bold text-orange-600 dark:text-orange-500 uppercase tracking-[0.2em] border-b border-orange-500/10 pb-2">{title}</h3>
    {children}
  </div>
);

function FileLink({ label, url }) {
  if (!url) return null;
  const isInternal = isInternalFileUrl(url);
  
  return (
    <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4 flex flex-col gap-1 transition-all hover:border-orange-500/30 group">
      <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider font-mono block mb-0.5">{label}</label>
      {isInternal ? (
        <a 
          href={url} 
          target="_blank" 
          rel="noreferrer" 
          className="text-blue-500 hover:text-blue-600 underline font-bold text-sm inline-flex items-center gap-1.5"
        >
          <FileText size={14} className="group-hover:scale-110 transition-transform" />
          Abrir documento
        </a>
      ) : (
        <a 
          href={url} 
          target="_blank" 
          rel="noreferrer" 
          className="text-blue-500 hover:text-blue-600 underline font-bold text-xs break-all line-clamp-2"
          title={url}
        >
          {url}
        </a>
      )}
    </div>
  );
}

const missingDatesForClose = (m) => {
  if (!m) return DATE_KEYS.map(k => DATE_LABELS[k]);
  return DATE_KEYS.filter(k => {
    const v = m[k];
    return v == null || String(v).trim() === '';
  }).map(k => DATE_LABELS[k]);
};

export default function MaintenanceView() {
  const { 
    maintenances, 
    loading: maintenanceLoading,
    fetchMaintenances, 
    refreshMaintenances,
    createMaintenance, 
    updateMaintenance, 
    updateMaintenanceBatch, 
    deleteMaintenance,
    calcularDifOrcamento,
    fecharManutencao,
    abrirManutencao,
    getAbertoFechado,
    getHistoricoCompleto,
    getHistoricoDetalhado,
    getHistoricoEstatisticas,
    getHistoricoPeriodo,
    getHistoricoTop
  } = useMaintenance();
  const { deleteVehicle } = useVehicles();
  const { workshops, fetchWorkshops } = useWorkshops();
  const { fetchListsConfig, statusManutencaoOptions, motivoAtendimentoOptions, responsaveisOptions, validacaoOptions, aprovacaoOptions } = useFleetLists();
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState('total'); // 'total', 'fechada', 'aberta'
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingItem, setEditingItem] = useState(null);
  const [statusStats, setStatusStats] = useState([]);
  const [selectedStatusRecords, setSelectedStatusRecords] = useState(null);
  const [isRecordsModalOpen, setIsRecordsModalOpen] = useState(false);
  const [selectedMaintenance, setSelectedMaintenance] = useState(null);
  const [isDetailPanelOpen, setIsDetailPanelOpen] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [historicoData, setHistoricoData] = useState({
    completo: null,
    detalhado: [],
    estatisticas: null,
    top: []
  });
  const [loadingHistorico, setLoadingHistorico] = useState(false);
  const [topMaintenances, setTopMaintenances] = useState([]);
  const [abertoFechadoData, setAbertoFechadoData] = useState(null);

  const initialFormState = {
    ano_entrada: '', ano_saida: '', atendimento: '', base_frota: '', cidade: '',
    condicao_pagamento: '', data_agendamento: '', data_finalizacao: '', data_parada_veiculo: '',
    data_retirada: '', data_solicitacao: '', dif_orcamento: '', endereco_prestador: '',
    idmanutencao_frota: '', manutencao: '', mes_entrada: '', mes_saida: '', modelo: '',
    motivo_atendimento: '', obs: '', oficina: '', orcamento_final: '', orcamento_inicial: '',
    pdf_orcamento: '', nota_fiscal: '', placa: '', placa_reserva: '', previsao_entrega: '', proprietario: '',
    resp_aprovacao: '', responsavel: '',
    status: 'Pendente', uf: '', validacao_financeiro: '', qtd_parcelas_condicao_pag: ''
  };
  const [formData, setFormData] = useState(initialFormState);
  const [vehicleSelectedFromPlaca, setVehicleSelectedFromPlaca] = useState(false);
  const [filePdfOrcamento, setFilePdfOrcamento] = useState(null);
  const [fileNotaFiscal, setFileNotaFiscal] = useState(null);
  const difOrcamentoTimerRef = useRef(null);

  const { vehicles, fetchVehicles } = useVehicles();

  // Atualiza Dif. Orçamento em tempo real via API quando orçamento inicial/final mudam
  useEffect(() => {
    if (!isModalOpen) return;
    const inicial = formData.orcamento_inicial;
    const final = formData.orcamento_final;
    if (difOrcamentoTimerRef.current) clearTimeout(difOrcamentoTimerRef.current);
    difOrcamentoTimerRef.current = setTimeout(async () => {
      const hasVal = (inicial !== '' && inicial != null) || (final !== '' && final != null);
      if (!hasVal) {
        setFormData(prev => ({ ...prev, dif_orcamento: '' }));
        return;
      }
      const valor = await calcularDifOrcamento(inicial === '' || inicial == null ? null : Number(inicial), final === '' || final == null ? null : Number(final));
      if (valor != null) setFormData(prev => ({ ...prev, dif_orcamento: valor }));
    }, 500);
    return () => { if (difOrcamentoTimerRef.current) clearTimeout(difOrcamentoTimerRef.current); };
  }, [isModalOpen, formData.orcamento_inicial, formData.orcamento_final]);


  useEffect(() => {
    // Carrega a rota inicial baseada no filtro
    if (statusFilter === 'total') {
      fetchMaintenances('total');
    } else {
      getAbertoFechado();
    }
    
    fetchVehicles();
    fetchWorkshops();
    fetchListsConfig();

    // Fetch Status Stats
    prafrotStatisticsService.getPlacasPorStatus().then(data => {
      if (Array.isArray(data)) setStatusStats(data);
    });

    // Top manutenções (visão geral, cards na tela)
    getHistoricoTop().then(data => {
      const lista = Array.isArray(data) ? data : (data?.data || []);
      const comPosicao = lista.map((item, index) => ({
        ...item,
        posicao: index + 1,
      }));
      setTopMaintenances(comPosicao);
    }).catch((error) => {
      console.error('Erro ao carregar top manutenções:', error);
    });
  }, [statusFilter]); // Dependência adicionada para recarregar ao trocar o filtro

  // Carrega dados de aberto/fechado quando o filtro não é "total"
  useEffect(() => {
    if (statusFilter === 'total') {
      setAbertoFechadoData(null);
      return;
    }

    let isCancelled = false;
    (async () => {
      try {
        const data = await getAbertoFechado();
        if (!isCancelled) {
          setAbertoFechadoData(data);
        }
      } catch (error) {
        console.error('Erro ao carregar dados de aberto/fechado:', error);
      }
    })();

    return () => {
      isCancelled = true;
    };
  }, [statusFilter, getAbertoFechado]);

  const getStatusData = (status) => {
    return statusStats.find(item => {
      const itemStatus = (item.status || item.status_frota || '');
      return itemStatus.trim().toLowerCase() === status?.trim().toLowerCase();
    });
  };

  const handleStatusClick = (status) => {
    const data = getStatusData(status);
    if (data && data.registros) {
      setSelectedStatusRecords({
        title: status,
        records: JSON.parse(data.registros).filter(r => r !== null)
      });
      setIsRecordsModalOpen(true);
    }
  };

  const handleVehicleSelect = (vehicle) => {
    if (!vehicle) return;
    setVehicleSelectedFromPlaca(true);
    setFormData(prev => ({
      ...prev,
      placa: vehicle.placa || prev.placa,
      placa_reserva: vehicle.placa_reserva || prev.placa_reserva,
      modelo: vehicle.modelo || vehicle.mod_veiculo || prev.modelo,
      base_frota: vehicle.base || prev.base_frota,
      uf: vehicle.uf || prev.uf,
      proprietario: vehicle.proprietario || prev.proprietario,
      cidade: vehicle.cidade || prev.cidade,
    }));
  };

  const handleWorkshopSelect = (workshop) => {
    if (!workshop) return;
    setFormData(prev => ({
      ...prev,
      oficina: workshop.nome_reduzido || prev.oficina,
      cidade: workshop.cidade || prev.cidade,
      uf: workshop.uf || prev.uf,
      endereco_prestador: workshop.endereco || prev.endereco_prestador,
    }));
  };

  const handleOpenModal = (item = null) => {
    setFilePdfOrcamento(null);
    setFileNotaFiscal(null);
    if (item) {
      setEditingItem(item);
      const base = { ...initialFormState, ...item };
      base.previsao_entrega = item.previsao_entrega ?? item.previcao_entrega ?? base.previsao_entrega;
      DATE_KEYS.forEach(k => {
        if (base[k] != null && base[k] !== '') base[k] = normalizeDateForInput(base[k]) || base[k];
      });
      ['orcamento_inicial', 'orcamento_final', 'dif_orcamento'].forEach(k => {
        if (base[k] != null && base[k] !== '') base[k] = parseCurrency(base[k]);
      });
      setFormData(base);
      setVehicleSelectedFromPlaca(true);
    } else {
      setEditingItem(null);
      setFormData(initialFormState);
      setVehicleSelectedFromPlaca(false);
    }
    setIsModalOpen(true);
  };

  const { notifyFields } = useFeedback();

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // Validação de campos obrigatórios mais abrangente para evitar 400 do backend
    const requiredFields = [];
    if (!formData.placa) requiredFields.push('Placa');
    if (!formData.oficina) requiredFields.push('Oficina');
    if (!formData.responsavel) requiredFields.push('Responsável');
    if (!formData.modelo) requiredFields.push('Modelo');
    if (!formData.motivo_atendimento) requiredFields.push('Motivo Atendimento');
    if (!formData.proprietario) requiredFields.push('Proprietário');
    if (!formData.base_frota) requiredFields.push('Base Frota');
    if (!formData.data_parada_veiculo) requiredFields.push('Data de Parada');
    if (!formData.manutencao) requiredFields.push('Descrição da Manutenção');
    
    if (requiredFields.length > 0) {
      notifyFields(requiredFields);
      return;
    }

    // Limpeza do payload: remove strings vazias que podem causar erro no backend
    const payload = {};
    Object.keys(formData).forEach(key => {
      if (formData[key] !== '' && formData[key] !== null) {
        payload[key] = formData[key];
      }
    });

    // Mesma tratativa de moeda na criação e na edição: normalizar orçamentos para número
    ['orcamento_inicial', 'orcamento_final', 'dif_orcamento'].forEach(k => {
      if (payload[k] != null && payload[k] !== '') {
        const parsed = parseCurrency(payload[k]);
        payload[k] = parsed === '' ? payload[k] : parsed;
      }
    });

    // Na edição: preservar datas existentes quando o formulário estiver vazio (evitar limpar no backend)
    if (editingItem) {
      DATE_KEYS.forEach(k => {
        const formVal = formData[k];
        const existing = k === 'previsao_entrega' ? (editingItem.previsao_entrega ?? editingItem.previcao_entrega) : editingItem[k];
        if ((formVal === '' || formVal == null) && existing != null && existing !== '') {
          const normalized = normalizeDateForInput(existing);
          if (normalized) payload[k] = normalized;
        }
      });
    }

    // Tratativa especial para Condição de Pagamento e Parcelas
    const condRaw = (formData.condicao_pagamento || '').trim();
    if (condRaw.toLowerCase().includes('parcelado') || /^\d+x$/i.test(condRaw)) {
      payload.condicao_pagamento = 'Parcelado';
      // Extrai o número de parcelas (ex: "3x" -> 3)
      const match = condRaw.match(/(\d+)/);
      payload.qtd_parcelas_condicao_pag = match ? match[1] : (formData.qtd_parcelas_condicao_pag || '2');
    } else {
      payload.condicao_pagamento = condRaw || 'À vista';
      payload.qtd_parcelas_condicao_pag = '';
    }

    const files = {};
    if (filePdfOrcamento instanceof File) {
      files.pdf_orcamento = filePdfOrcamento;
      delete payload.pdf_orcamento;
    }
    if (fileNotaFiscal instanceof File) {
      files.nota_fiscal = fileNotaFiscal;
      delete payload.nota_fiscal;
    }

    const hasFiles = Object.keys(files).length > 0;
    
    setIsSubmitting(true);
    try {
      let success;
      if (editingItem) {
        success = await updateMaintenance(editingItem.idmanutencao_frota, payload, hasFiles ? files : null);
      } else {
        success = await createMaintenance(payload, hasFiles ? files : null);
      }
      if (success) {
        setFilePdfOrcamento(null);
        setFileNotaFiscal(null);
        setIsModalOpen(false);
        // Atualiza os dados respeitando o filtro ativo
        await refreshMaintenances(statusFilter);
        
        // Se estiver com o painel de detalhes aberto, atualiza o item selecionado para refletir as mudanças
        if (isDetailPanelOpen && selectedMaintenance && editingItem && selectedMaintenance.idmanutencao_frota === editingItem.idmanutencao_frota) {
          // Busca o item atualizado da lista de manutenções
          const updated = (maintenances || []).find(m => m.idmanutencao_frota === editingItem.idmanutencao_frota);
          if (updated) setSelectedMaintenance(updated);
        }
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  const [selectedIds, setSelectedIds] = useState([]);

  const handleStatusUpdate = async (id, newStatus) => {
    setIsSubmitting(true);
    try {
      // Se o item que está sendo editado faz parte da seleção, aplica em massa
      if (selectedIds.includes(id)) {
          // Confirmação simples
          const confirmUpdate = window.confirm(`Você selecionou ${selectedIds.length} itens. Deseja atualizar o status de TODOS eles para "${newStatus}"?`);
          
          if (confirmUpdate) {
              const success = await updateMaintenanceBatch(selectedIds, newStatus);
              if (success) {
                  setSelectedIds([]); // Limpa a seleção
                  await refreshMaintenances(statusFilter);
              }
          }
      } else {
          // Single Update (using batch route as requested)
          await updateMaintenanceBatch([id], newStatus);
          await refreshMaintenances(statusFilter);
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  // Filter logic
  const filteredData = useMemo(() => {
    if (!Array.isArray(maintenances)) return [];
    
    // Base list:
    // - total: usa a rota padrão /manutencao_frota/apresentar
    // - fechada/aberta: usa /manutencao_frota/aberto_fechado/apresentar (grupos separados)
    let baseList = maintenances;

    if (statusFilter !== 'total' && abertoFechadoData) {
      const lower = {};
      Object.keys(abertoFechadoData || {}).forEach((key) => {
        lower[key.toLowerCase()] = abertoFechadoData[key];
      });

      const abertas =
        lower.abertas ||
        lower.aberto ||
        lower.abertos ||
        [];
      const fechadas =
        lower.fechadas ||
        lower.fechado ||
        lower.fechados ||
        [];

      if (statusFilter === 'fechada') {
        baseList = Array.isArray(fechadas) ? fechadas : [];
      } else if (statusFilter === 'aberta') {
        baseList = Array.isArray(abertas) ? abertas : [];
      }
    }

    let filtered = baseList.filter(item => 
      item.placa?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.oficina?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      String(item.idmanutencao_frota || '').toLowerCase().includes(searchTerm.toLowerCase())
    );

    return filtered;
  }, [maintenances, searchTerm, statusFilter, abertoFechadoData]);

  // Get status options for open/close
  const getOpenStatus = () => {
    // Find first non-closed status from options, or default to 'Pendente'
    const openStatus = statusManutencaoOptions.find(opt => !isMaintenanceClosed(opt));
    return openStatus || 'Pendente';
  };

  const getCloseStatus = () => {
    // Find first closed status from options, or default to 'Concluído'
    const closedStatus = statusManutencaoOptions.find(opt => isMaintenanceClosed(opt));
    return closedStatus || 'Concluído';
  };

  const notifyMaintenance = (type, title, message) => {
    useFeedbackStore.getState().notify(type, title, message, 12000);
  };

  // Handle open/close maintenance
  const handleToggleMaintenanceStatus = async () => {
    if (selectedIds.length === 0) {
      notifyMaintenance('warning', 'Seleção necessária', 'Selecione pelo menos uma manutenção para abrir/fechar.');
      return;
    }

    const firstItem = maintenances.find(m => selectedIds.includes(m.idmanutencao_frota));
    const isCurrentlyClosed = firstItem ? isMaintenanceClosed(firstItem.status) : false;
    const willClose = !isCurrentlyClosed;

    if (willClose) {
      const toClose = filteredData.filter(m => selectedIds.includes(m.idmanutencao_frota));
      const withMissing = toClose.map(m => ({ m, missing: missingDatesForClose(m) })).filter(({ missing }) => missing.length > 0);
      if (withMissing.length > 0) {
        const list = withMissing.map(({ m, missing }) => `• ${m.placa || m.idmanutencao_frota}: ${missing.join(', ')}`).join('\n');
        notifyMaintenance('warning', 'Não é possível fechar', `Todas as datas devem estar preenchidas:\n\n${list}\n\nEdite os registros e preencha as datas antes de fechar.`);
        return;
      }
    }

    const newStatus = isCurrentlyClosed ? getOpenStatus() : getCloseStatus();
    const action = isCurrentlyClosed ? 'abrir' : 'fechar';
    const confirmMessage = `Deseja ${action} ${selectedIds.length} manutenção(ões) selecionada(s)?`;
    
    if (window.confirm(confirmMessage)) {
      const success = await updateMaintenanceBatch(selectedIds, newStatus);
      if (success) {
        setSelectedIds([]);
        await refreshMaintenances(statusFilter);
      }
    }
  };

  // Calculate button state for open/close
  const firstSelectedMaintenance = selectedIds.length > 0 
    ? maintenances.find(m => selectedIds.includes(m.idmanutencao_frota))
    : null;
  const isSelectedClosed = firstSelectedMaintenance 
    ? isMaintenanceClosed(firstSelectedMaintenance.status) 
    : false;

  // Handler para abrir painel de detalhamento
  const handleOpenDetailPanel = async (maintenance) => {
    setSelectedMaintenance(maintenance);
    // Limpa dados de histórico anteriores para evitar "lixo" visual ao trocar de manutenção
    setHistoricoData({
      completo: null,
      detalhado: [],
      estatisticas: null,
      top: []
    });
    setIsDetailPanelOpen(true);
  };

  // Handler para fechar/abrir manutenção individual
  const handleToggleMaintenanceIndividual = async (maintenance) => {
    if (!maintenance) return;
    
    // A regra de aberto/fechado vem do campo `manutencao` (Aberto / Fechado)
    const manutencaoLabel = (maintenance.manutencao || '').trim().toLowerCase();
    const isClosedByLabel = manutencaoLabel === 'fechado' || manutencaoLabel === 'fechada';

    const willOpen = isClosedByLabel;
    const action = willOpen ? 'abrir' : 'fechar';

    if (!willOpen) {
      const missing = missingDatesForClose(maintenance);
      if (missing.length > 0) {
        notifyMaintenance('warning', 'Não é possível fechar a manutenção', `Preencha todas as datas:\n\n• ${missing.join('\n• ')}\n\nEdite o registro e preencha as datas antes de fechar.`);
        return;
      }
    }
    
    if (window.confirm(`Deseja ${action} esta manutenção?`)) {
      setIsSubmitting(true);
      try {
        if (willOpen) {
          await abrirManutencao(maintenance.idmanutencao_frota);
        } else {
          await fecharManutencao(maintenance.idmanutencao_frota);
        }
        
        // Atualiza o estado local se o painel estiver aberto
        if (isDetailPanelOpen && selectedMaintenance?.idmanutencao_frota === maintenance.idmanutencao_frota) {
          setSelectedMaintenance(prev => ({ ...prev, manutencao: willOpen ? 'Aberto' : 'Fechado' }));
        }
        await refreshMaintenances(statusFilter);
      } finally {
        setIsSubmitting(false);
      }
    }
  };

  // Handler para carregar histórico por aba
  const handleLoadHistorico = async (tipo) => {
    if (!selectedMaintenance?.placa) return;
    const placa = String(selectedMaintenance.placa || '').trim();
    
    setLoadingHistorico(true);
    try {
      let data = [];
      switch (tipo) {
        case 'completo':
          data = await getHistoricoCompleto();
          // /historico/completo -> filtra apenas a placa selecionada
          {
            const lista = Array.isArray(data) ? data : (data?.data || []);
            const resumoPlaca = lista.find(
              (item) => String(item.placa || '').trim() === placa
            ) || null;
            setHistoricoData(prev => ({ ...prev, completo: resumoPlaca }));
          }
          break;
        case 'detalhado':
          data = await getHistoricoDetalhado();
          // /historico/detalhado -> lista de manutenções, filtra pela placa
          {
            const lista = Array.isArray(data) ? data : (data?.data || []);
            const detalhesPlaca = lista.filter(
              (item) => String(item.placa || '').trim() === placa
            );
            setHistoricoData(prev => ({ ...prev, detalhado: detalhesPlaca }));
          }
          break;
        case 'estatisticas':
          {
            const statsRaw = await getHistoricoEstatisticas();
            const lista = Array.isArray(statsRaw) ? statsRaw : (statsRaw?.data || []);
            const statsPlaca = lista.find(
              (item) => String(item.placa || '').trim() === placa
            ) || null;
            setHistoricoData(prev => ({ ...prev, estatisticas: statsPlaca }));
          }
          break;
        default:
          break;
      }
    } catch (error) {
      console.error(`Erro ao carregar histórico ${tipo}:`, error);
    } finally {
      setLoadingHistorico(false);
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col md:flex-row justify-between items-end md:items-center gap-4">
        <div>
          <h1 className="text-2xl font-bold text-slate-800 dark:text-white tracking-tight">Manutenção de Frota</h1>
          <p className="text-slate-500 text-sm">Controle de oficinas, orçamentos e agendamentos.</p>
        </div>
          <div className="flex items-center gap-3 w-full md:w-auto flex-wrap">
          <div className="relative flex-1 md:flex-none">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500" size={16} />
            <input 
              className="bg-white dark:bg-[#1c1c1c] border border-slate-200 dark:border-[#2a2a2a] text-slate-700 dark:text-slate-200 pl-10 pr-4 py-2 rounded-xl text-sm focus:outline-none focus:border-orange-500 w-full md:w-64"
              placeholder="Buscar por ID, placa ou oficina..." 
              value={searchTerm}
              onChange={e => setSearchTerm(e.target.value)}
            />
          </div>
          {selectedIds.length > 0 && (
            <DarkButton 
              onClick={handleToggleMaintenanceStatus}
              variant="secondary"
              className="flex items-center gap-2"
            >
              {isSelectedClosed ? (
                <>
                  <Unlock size={16} />
                  Abrir Manutenções
                </>
              ) : (
                <>
                  <Lock size={16} />
                  Fechar Manutenções
                </>
              )}
            </DarkButton>
          )}
          <DarkButton onClick={() => handleOpenModal()}>
            <Plus size={18} /> Nova Solicitação
          </DarkButton>
        </div>
      </div>

      {/* Status Highlights for Maintenance */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {[
          { label: 'Oficina - Externo', status: 'Em Oficina - Externo', color: 'bg-orange-500/10 text-orange-600', icon: <Wrench size={20} />, hover: 'hover:border-orange-500/30' },
          { label: 'Oficina - Rentals', status: 'Em Oficina - Rentals', color: 'bg-purple-500/10 text-purple-600', icon: <Wrench size={20} />, hover: 'hover:border-purple-500/30' },
          { label: 'Oficina - Trois', status: 'Em Oficina - Trois', color: 'bg-pink-500/10 text-pink-600', icon: <Wrench size={20} />, hover: 'hover:border-pink-500/30' },
          { label: 'Pra Reboque', status: 'Pra Reboque', color: 'bg-rose-500/10 text-rose-600', icon: <Wrench size={20} />, hover: 'hover:border-rose-500/30' }
        ].map((item, idx) => (
          <div 
            key={idx} 
            onClick={() => handleStatusClick(item.status)}
            className={`bg-white dark:bg-[#1c1c1c] border border-slate-200 dark:border-[#2a2a2a] rounded-xl p-4 shadow-sm hover:shadow-md transition-all flex flex-col items-center justify-center text-center group cursor-pointer ${item.hover}`}
          >
             <div className={`p-2.5 rounded-lg ${item.color} group-hover:scale-110 transition-transform mb-2`}>
                {item.icon}
             </div>
             <span className="text-[10px] font-bold uppercase tracking-wider text-slate-500 dark:text-slate-400 leading-tight mb-1">{item.label}</span>
             <div className="text-xl font-bold text-slate-800 dark:text-white">
               {getStatusData(item.status)?.total || 0}
             </div>
          </div>
        ))}
      </div>

      {/* Top Manutenções - Visão Geral (cards) */}
      {topMaintenances && topMaintenances.length > 0 && (
        <div className="mt-2">
          <h2 className="text-xs font-bold uppercase tracking-[0.18em] text-slate-500 dark:text-slate-400 mb-2">
            Top Manutenções (Visão Geral da Frota)
          </h2>
          <div className="grid grid-cols-1 md:grid-cols-3 xl:grid-cols-4 gap-3">
            {topMaintenances.slice(0, 4).map((item) => (
              <div
                key={`${item.placa}-${item.posicao}`}
                className="bg-white dark:bg-[#111111] border border-slate-200 dark:border-[#272727] rounded-2xl p-4 shadow-sm hover:shadow-md transition-all cursor-default"
              >
                <div className="mb-2">
                  <div className="text-[10px] font-bold uppercase tracking-[0.18em] text-slate-500 dark:text-slate-400 mb-1">
                    #{item.posicao} • {item.modelo || '-'}
                  </div>
                  <div className="text-[10px] font-bold text-slate-400 dark:text-slate-500">
                    {item.total_manutencoes ?? 0} manutenções
                  </div>
                </div>
                <div className="flex items-baseline justify-between mb-3">
                  <span className="text-sm font-bold text-orange-600 dark:text-orange-400 font-mono">
                    {item.placa || '-'}
                  </span>
                  <span className="text-[11px] text-slate-500 dark:text-slate-400">
                    Última: {item.ultima_manutencao || 'não informado'}
                  </span>
                </div>
                <div className="flex items-center justify-between text-[11px] text-slate-500 dark:text-slate-400">
                  <span>Concluídas: <span className="font-bold">{item.concluidas ?? 0}</span></span>
                  <span>Em andamento: <span className="font-bold">{item.em_andamento ?? 0}</span></span>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Seletor de Filtro Aberto/Fechado - Destacado acima da tabela */}
      <div className="bg-gradient-to-r from-orange-500/10 via-blue-500/10 to-orange-500/10 border-2 border-orange-500/30 dark:border-orange-500/20 rounded-2xl p-4 shadow-lg">
        <div className="flex items-center justify-between gap-4">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-orange-500/20 rounded-xl">
              <Lock size={20} className="text-orange-600 dark:text-orange-400" />
            </div>
            <div>
              <label className="text-xs font-bold uppercase tracking-wider text-slate-600 dark:text-slate-300 block mb-1">
                Filtrar por Status de Manutenção
              </label>
              <p className="text-[10px] text-slate-500 dark:text-slate-400">
                Visualize todas as manutenções, apenas as abertas ou apenas as fechadas
              </p>
            </div>
          </div>
          <select
            value={statusFilter}
            onChange={e => setStatusFilter(e.target.value)}
            className="bg-white dark:bg-[#1c1c1c] border-2 border-orange-500/50 dark:border-orange-500/30 text-slate-700 dark:text-slate-200 px-6 py-3 rounded-xl text-sm font-bold focus:outline-none focus:border-orange-500 focus:ring-2 focus:ring-orange-500/20 cursor-pointer shadow-md hover:shadow-lg transition-all min-w-[180px]"
          >
            <option value="total">📊 Total</option>
            <option value="aberta">🔓 Aberta</option>
            <option value="fechada">🔒 Fechada</option>
          </select>
        </div>
      </div>

      <div className="h-[600px] w-full max-w-full overflow-hidden min-w-0">
        {/* Colunas alinhadas ao contrato: docs/PADROES_ROTAS_APRESENTACAO.md § GET /manutencao_frota/apresentar */}
        <ExcelTable 
           data={filteredData}
           selectedIds={selectedIds}
           onSelectionChange={setSelectedIds}
           rowKey="idmanutencao_frota"
           columns={[
             { header: 'ID', field: 'idmanutencao_frota', width: '80px' },
             { header: 'ATENDIMENTO', field: 'atendimento', width: '100px' },
             { header: 'PLACA', field: 'placa', width: '100px', className: 'font-mono font-bold text-orange-600 dark:text-orange-500' },
             { header: 'PLACA RESERVA', field: 'placa_reserva', width: '100px' },
             { header: 'MODELO', field: 'modelo', width: '110px' },
             { header: 'OFICINA', field: 'oficina', width: '160px' },
             { header: 'BASE FROTA', field: 'base_frota', width: '100px' },
             { header: 'CIDADE', field: 'cidade', width: '120px' },
             { header: 'UF', field: 'uf', width: '60px' },
             { header: 'PROPRIETÁRIO', field: 'proprietario', width: '110px' },
             { header: 'RESPONSÁVEL', field: 'responsavel', width: '120px' },
             { header: 'MOTIVO ATEND.', field: 'motivo_atendimento', width: '120px' },
             { header: 'STATUS', field: 'status', width: '140px', render: (row) => (
                <MaintenanceStatusCell 
                  currentStatus={row.status} 
                  id={row.idmanutencao_frota} 
                  options={statusManutencaoOptions} 
                  onUpdate={handleStatusUpdate} 
                />
             )},
             { header: 'MANUTENÇÃO', field: 'manutencao', width: '90px' },
             { header: 'STATUS FROTA', field: 'status_frota_veiculo', width: '120px' },
             { header: 'DATA SOLIC.', field: 'data_solicitacao', width: '100px' },
             { header: 'DATA AGEND.', field: 'data_agendamento', width: '100px' },
             { header: 'DATA PARADA', field: 'data_parada_veiculo', width: '100px' },
             { header: 'PREV. ENTREGA', field: 'previsao_entrega', width: '100px' },
             { header: 'DATA FINAL.', field: 'data_finalizacao', width: '100px' },
             { header: 'DATA RETIRADA', field: 'data_retirada', width: '100px' },
             { header: 'ORÇ. INICIAL', field: 'orcamento_inicial', width: '110px', className: 'font-mono text-orange-600 dark:text-orange-400', render: (row) => formatCurrency(row.orcamento_inicial) },
             { header: 'ORÇ. FINAL', field: 'orcamento_final', width: '110px', className: 'font-mono text-orange-600 dark:text-orange-400', render: (row) => formatCurrency(row.orcamento_final) },
             { header: 'DIF. ORÇ.', field: 'dif_orcamento', width: '100px', className: 'font-mono', render: (row) => formatCurrency(row.dif_orcamento) },
             { header: 'COND. PAG.', field: 'condicao_pagamento', width: '120px', render: (row) => (
               <span>
                 {row.condicao_pagamento}
                 {row.condicao_pagamento === 'Parcelado' && row.qtd_parcelas_condicao_pag && (
                   <span className="ml-1 text-orange-500 font-bold">({row.qtd_parcelas_condicao_pag}x)</span>
                 )}
               </span>
             )},
             { header: 'VALID. FINANC.', field: 'validacao_financeiro', width: '110px' },
             { header: 'RESP. APROV.', field: 'resp_aprovacao', width: '110px' },
             { header: 'SLA OFICINA', field: 'sla_oficina', width: '100px' },
             { header: 'SLA PÓS-OF.', field: 'sla_pos_oficina', width: '100px' },
             { header: 'OBS', field: 'obs', width: '180px' },
             { header: 'END. PRESTADOR', field: 'endereco_prestador', width: '180px' },
             { header: 'PDF ORÇAMENTO', field: 'pdf_orcamento_link', width: '100px', render: (row) => (row.pdf_orcamento_link || row.pdf_orcamento) ? <a href={row.pdf_orcamento_link || row.pdf_orcamento} target="_blank" rel="noreferrer" className="underline text-blue-500 font-bold">Abrir</a> : '-' },
             { header: 'NOTA FISCAL', field: 'nota_fiscal', width: '100px', render: (row) => row.nota_fiscal ? <a href={row.nota_fiscal} target="_blank" rel="noreferrer" className="underline text-blue-500 font-bold">Abrir</a> : '-' },
           ]}
            filterDefs={[
                { field: 'placa', label: 'Placa', type: 'text', placeholder: 'Buscar placa...' },
                { field: 'oficina', label: 'Oficina', type: 'select' },
                { field: 'status', label: 'Status', type: 'select' },
                { field: 'motivo_atendimento', label: 'Motivo Atendimento', type: 'select' },
                { field: 'responsavel', label: 'Responsável', type: 'select' },
                { field: 'cidade', label: 'Cidade', type: 'select' },
            ]}
           onRowClick={handleOpenDetailPanel}
           // Coluna de ações comentada - botões movidos para o painel de detalhamento
           // onEdit={handleOpenModal}
           // onDelete={(item) => deleteMaintenance(item.idmanutencao_frota)}
         />
      </div>

      <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
        <DialogContent className="w-[90vw] max-w-4xl max-h-[85vh] bg-white dark:bg-[#1c1c1c] border-slate-200 dark:border-[#2a2a2a] text-slate-700 dark:text-slate-200 p-0 overflow-hidden shadow-2xl flex flex-col">
            <LoadingOverlay isLoading={isSubmitting} message="Salvando alterações..." variant="minimal" />
            <DialogHeader className="p-4 md:p-6 border-b border-slate-200 dark:border-[#2a2a2a] bg-slate-50 dark:bg-[#1c1c1c] shrink-0">
                <DialogTitle className="text-lg md:text-xl font-bold text-slate-800 dark:text-white uppercase tracking-tight">
                    {editingItem ? 'Editar Manutenção' : 'Nova Solicitação de Manutenção'}
                </DialogTitle>
                <DialogDescription className="text-xs md:text-sm text-slate-500 dark:text-stone-500">
                    Registre os detalhes da manutenção, orçamentos e prazos do veículo.
                </DialogDescription>
            </DialogHeader>
           
           <form onSubmit={handleSubmit} className="px-4 md:px-6 py-4 overflow-y-auto custom-scrollbar flex-1">
               <Tabs defaultValue="basicos" className="w-full">
                  <TabsList className="bg-slate-100 dark:bg-[#141414] border border-slate-200 dark:border-[#2a2a2a] w-full justify-start p-1 h-auto mb-4">
                    {['basicos', 'orcamentos', 'datas'].map(tab => (
                        <TabsTrigger 
                        key={tab} 
                        value={tab}
                        className="data-[state=active]:bg-orange-600 data-[state=active]:text-white text-slate-500 dark:text-stone-400 text-[10px] uppercase font-bold px-4 py-2"
                        >
                        {tab}
                        </TabsTrigger>
                    ))}
                  </TabsList>

                  <TabsContent value="basicos" className="space-y-4 m-0 pb-4">
                     <div className="grid grid-cols-3 gap-4">
                        <AutocompleteInput 
                            label="Placa" 
                            value={formData.placa} 
                            onChange={v => setFormData({...formData, placa: v})} 
                            options={vehicles}
                            displayKey="placa"
                            valueKey="placa"
                            searchKeys={['placa']}
                            onSelect={handleVehicleSelect}
                            required 
                         />
                        <DarkInput label="Placa Reserva" value={formData.placa_reserva} onChange={e => setFormData({...formData, placa_reserva: e.target.value})} />
                        <DarkInput label="Modelo" value={formData.modelo} onChange={e => setFormData({...formData, modelo: e.target.value})} readOnly={vehicleSelectedFromPlaca} />
                     </div>
                     <div className="grid grid-cols-2 gap-4">
                        <AutocompleteInput 
                            label="Oficina" 
                            value={formData.oficina} 
                            onChange={v => setFormData({...formData, oficina: v})} 
                            options={workshops}
                            displayKey="nome_reduzido"
                            valueKey="nome_reduzido"
                            searchKeys={['nome_reduzido', 'razao_social', 'cnpj']}
                            onSelect={handleWorkshopSelect}
                            required 
                         />
                        <DarkSelect 
                            label="Responsável" 
                            options={responsaveisOptions} 
                            value={formData.responsavel} 
                            onChange={v => setFormData({...formData, responsavel: v})} 
                        />
                     </div>
                     <div className="grid grid-cols-3 gap-4">
                        <DarkSelect 
                            label="Status manutenção" 
                            options={statusManutencaoOptions} 
                            value={formData.status} 
                            onChange={v => setFormData({...formData, status: v})} 
                        />
                        <DarkInput label="Atendimento" value={formData.atendimento} onChange={e => setFormData({...formData, atendimento: e.target.value})} />
                        <DarkInput label="Base Frota" value={formData.base_frota} onChange={e => setFormData({...formData, base_frota: e.target.value})} readOnly={vehicleSelectedFromPlaca} />
                     </div>
                     <div className="grid grid-cols-2 gap-4">
                        <DarkInput label="Cidade" value={formData.cidade} onChange={e => setFormData({...formData, cidade: e.target.value})} readOnly={vehicleSelectedFromPlaca} />
                        <DarkInput label="UF" value={formData.uf} onChange={e => setFormData({...formData, uf: e.target.value})} maxLength={2} readOnly={vehicleSelectedFromPlaca} />
                     </div>
                     <DarkInput label="Endereço Prestador" value={formData.endereco_prestador} onChange={e => setFormData({...formData, endereco_prestador: e.target.value})} />
                  </TabsContent>

                  <TabsContent value="orcamentos" className="space-y-4 m-0 pb-4">
                      <div className="grid grid-cols-2 gap-4">
                        <CurrencyInput label="Orçamento Inicial" value={formData.orcamento_inicial} onChange={v => setFormData(prev => ({ ...prev, orcamento_inicial: v }))} />
                        <CurrencyInput label="Orçamento Final" value={formData.orcamento_final} onChange={v => setFormData(prev => ({ ...prev, orcamento_final: v }))} />
                      </div>
                      <div className="grid grid-cols-2 gap-4">
                        <DarkInput
                          label="Dif. Orçamento"
                          readOnly
                          value={formData.dif_orcamento === '' || formData.dif_orcamento == null ? '' : formatCurrency(formData.dif_orcamento)}
                          className="font-mono text-orange-600 dark:text-orange-400"
                        />
                      </div>
                      <div className="space-y-3">
                        {(() => {
                          const condicaoRaw = (formData.condicao_pagamento || '').trim();
                          const isCurrentlyParcelado = condicaoRaw === 'Parcelado' || /^\d+x$/i.test(condicaoRaw);
                          
                          // Determina o valor das parcelas para exibição
                          let nrParcelas = 2;
                          if (/^\d+x$/i.test(condicaoRaw)) {
                            nrParcelas = parseInt(condicaoRaw, 10) || 2;
                          } else if (formData.qtd_parcelas_condicao_pag) {
                            nrParcelas = parseInt(formData.qtd_parcelas_condicao_pag, 10) || 2;
                          }

                          const valorFinal = formData.orcamento_final !== '' && formData.orcamento_final != null ? Number(formData.orcamento_final) : null;
                          const valorParcela = isCurrentlyParcelado && valorFinal != null && valorFinal > 0 ? valorFinal / nrParcelas : null;
                          
                          return (
                            <>
                              <DarkSelect
                                label="Cond. Pagamento"
                                options={CONDICAO_OPCOES}
                                value={isCurrentlyParcelado ? 'Parcelado' : (condicaoRaw || 'À vista')}
                                onChange={(v) => {
                                  if (v === 'Parcelado') {
                                    setFormData(prev => ({ 
                                      ...prev, 
                                      condicao_pagamento: 'Parcelado',
                                      qtd_parcelas_condicao_pag: prev.qtd_parcelas_condicao_pag || '2' 
                                    }));
                                  } else {
                                    setFormData(prev => ({ 
                                      ...prev, 
                                      condicao_pagamento: 'À vista',
                                      qtd_parcelas_condicao_pag: '' 
                                    }));
                                  }
                                }}
                              />
                              {isCurrentlyParcelado && (
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                  <DarkSelect
                                    label="Nº de parcelas"
                                    options={PARCELAS_OPCOES.map(n => `${n}x`)}
                                    value={formData.qtd_parcelas_condicao_pag ? `${formData.qtd_parcelas_condicao_pag}x` : '2x'}
                                    onChange={(v) => {
                                      const n = v.replace('x', '');
                                      setFormData(prev => ({ 
                                        ...prev, 
                                        condicao_pagamento: 'Parcelado',
                                        qtd_parcelas_condicao_pag: n 
                                      }));
                                    }}
                                  />
                                  {valorParcela != null && (
                                    <div className="bg-orange-500/10 dark:bg-orange-500/20 border border-orange-500/30 rounded-xl px-3 py-2 flex flex-col justify-end">
                                      <span className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Valor por parcela</span>
                                      <p className="text-sm font-bold text-orange-700 dark:text-orange-400 font-mono mt-0.5">{formatCurrency(valorParcela)}</p>
                                    </div>
                                  )}
                                </div>
                              )}
                            </>
                          );
                        })()}
                      </div>
                      <div className="grid grid-cols-2 gap-4">
                        <DarkSelect 
                            label="Validação Financeiro" 
                            options={validacaoOptions} 
                            value={formData.validacao_financeiro} 
                            onChange={v => setFormData({...formData, validacao_financeiro: v})} 
                        />
                        <DarkSelect 
                            label="Resp. Aprovação" 
                            options={aprovacaoOptions} 
                            value={formData.resp_aprovacao} 
                            onChange={v => setFormData({...formData, resp_aprovacao: v})} 
                        />
                      </div>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div className="space-y-1.5">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider ml-1 block">Anexar PDF Orçamento</label>
                          <input
                            type="file"
                            accept=".pdf,application/pdf"
                            className="w-full text-sm text-slate-600 dark:text-slate-300 file:mr-3 file:py-2 file:px-4 file:rounded-xl file:border-0 file:bg-orange-500/20 file:text-orange-600 dark:file:text-orange-400 file:font-bold file:cursor-pointer hover:file:bg-orange-500/30"
                            onChange={(e) => setFilePdfOrcamento(e.target.files?.[0] ?? null)}
                          />
                          {(filePdfOrcamento || formData.pdf_orcamento) && (
                            <div className="flex items-center gap-2 mt-1.5 text-xs">
                              {filePdfOrcamento ? (
                                <span className="text-slate-600 dark:text-slate-400 truncate">{filePdfOrcamento.name}</span>
                              ) : (
                                <a href={formData.pdf_orcamento} target="_blank" rel="noreferrer" className="text-blue-500 hover:underline truncate">Documento atual</a>
                              )}
                              <button type="button" onClick={() => { setFilePdfOrcamento(null); setFormData(prev => ({ ...prev, pdf_orcamento: '' })); }} className="text-rose-500 hover:underline font-medium">Remover</button>
                            </div>
                          )}
                          <DarkInput label="Ou link PDF Orçamento" value={formData.pdf_orcamento} onChange={e => setFormData({...formData, pdf_orcamento: e.target.value})} placeholder="https://..." />
                        </div>
                        <div className="space-y-1.5">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider ml-1 block">Anexar Nota Fiscal</label>
                          <input
                            type="file"
                            accept=".pdf,application/pdf,image/*"
                            className="w-full text-sm text-slate-600 dark:text-slate-300 file:mr-3 file:py-2 file:px-4 file:rounded-xl file:border-0 file:bg-orange-500/20 file:text-orange-600 dark:file:text-orange-400 file:font-bold file:cursor-pointer hover:file:bg-orange-500/30"
                            onChange={(e) => setFileNotaFiscal(e.target.files?.[0] ?? null)}
                          />
                          {(fileNotaFiscal || formData.nota_fiscal) && (
                            <div className="flex items-center gap-2 mt-1.5 text-xs">
                              {fileNotaFiscal ? (
                                <span className="text-slate-600 dark:text-slate-400 truncate">{fileNotaFiscal.name}</span>
                              ) : (
                                <a href={formData.nota_fiscal} target="_blank" rel="noreferrer" className="text-blue-500 hover:underline truncate">Documento atual</a>
                              )}
                              <button type="button" onClick={() => { setFileNotaFiscal(null); setFormData(prev => ({ ...prev, nota_fiscal: '' })); }} className="text-rose-500 hover:underline font-medium">Remover</button>
                            </div>
                          )}
                          <DarkInput label="Ou link Nota Fiscal" value={formData.nota_fiscal} onChange={e => setFormData({...formData, nota_fiscal: e.target.value})} placeholder="https://..." />
                        </div>
                      </div>
                  </TabsContent>

                  <TabsContent value="datas" className="space-y-4 m-0 pb-4">
                      <div className="grid grid-cols-3 gap-4">
                        <DarkInput type="date" label="Data Solicitação" value={normalizeDateForInput(formData.data_solicitacao)} onChange={e => setFormData({...formData, data_solicitacao: e.target.value})} />
                        <DarkInput type="date" label="Data Agendamento" value={normalizeDateForInput(formData.data_agendamento)} onChange={e => setFormData({...formData, data_agendamento: e.target.value})} />
                        <DarkInput type="date" label="Data Parada" value={normalizeDateForInput(formData.data_parada_veiculo)} onChange={e => setFormData({...formData, data_parada_veiculo: e.target.value})} />
                      </div>
                      <div className="grid grid-cols-3 gap-4">
                        <DarkInput type="date" label="Previsão Entrega" value={normalizeDateForInput(formData.previsao_entrega)} onChange={e => setFormData({...formData, previsao_entrega: e.target.value})} />
                        <DarkInput type="date" label="Data Finalização" value={normalizeDateForInput(formData.data_finalizacao)} onChange={e => setFormData({...formData, data_finalizacao: e.target.value})} />
                        <DarkInput type="date" label="Data Retirada" value={normalizeDateForInput(formData.data_retirada)} onChange={e => setFormData({...formData, data_retirada: e.target.value})} />
                      </div>
                      <div className="grid grid-cols-4 gap-4">
                        {/* Campos de mês e ano comentados para escrita e envio ao back conforme solicitado */}
                        {/* <DarkInput label="Mês Ent." value={formData.mes_entrada} onChange={e => setFormData({...formData, mes_entrada: e.target.value})} />
                        <DarkInput label="Ano Ent." value={formData.ano_entrada} onChange={e => setFormData({...formData, ano_entrada: e.target.value})} />
                        <DarkInput label="Mês Saí." value={formData.mes_saida} onChange={e => setFormData({...formData, mes_saida: e.target.value})} />
                        <DarkInput label="Ano Saí." value={formData.ano_saida} onChange={e => setFormData({...formData, ano_saida: e.target.value})} /> */}
                      </div>
                  </TabsContent>
               </Tabs>
               
               {/* Campos adicionais fora das tabs */}
               <div className="space-y-4 pt-4 pb-4 border-t border-slate-200 dark:border-[#2a2a2a]">
                  <div className="grid grid-cols-2 gap-4">
                    <DarkSelect 
                        label="Motivo Atendimento" 
                        options={motivoAtendimentoOptions} 
                        value={formData.motivo_atendimento} 
                        onChange={v => setFormData({...formData, motivo_atendimento: v})} 
                    />
                    <DarkInput label="Proprietário" value={formData.proprietario} onChange={e => setFormData({...formData, proprietario: e.target.value})} readOnly={vehicleSelectedFromPlaca} />
                  </div>
               </div>
               
               <div className="space-y-4 pb-4">
                  <div className="gap-4">
                      <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-stone-400 tracking-wider ml-1">Descrição da Manutenção</label>
                      <textarea 
                        className="w-full bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-lg px-3 py-2 text-sm text-slate-700 dark:text-slate-200 focus:outline-none focus:border-orange-500 transition-all placeholder:text-slate-400 min-h-[60px]"
                        value={formData.manutencao}
                        onChange={e => setFormData({...formData, manutencao: e.target.value})}
                      />
                  </div>
                  <div className="gap-4">
                      <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-stone-400 tracking-wider ml-1">Observações</label>
                      <textarea 
                        className="w-full bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-lg px-3 py-2 text-sm text-slate-700 dark:text-slate-200 focus:outline-none focus:border-orange-500 transition-all placeholder:text-slate-400 min-h-[60px]"
                        value={formData.obs}
                        onChange={e => setFormData({...formData, obs: e.target.value})}
                      />
                  </div>
               </div>
           </form>

           <DialogFooter className="bg-slate-50 dark:bg-[#1c1c1c] border-t border-slate-200 dark:border-[#2a2a2a] p-4 gap-2">
               <DarkButton type="button" variant="ghost" onClick={() => setIsModalOpen(false)}>Cancelar</DarkButton>
               <DarkButton type="submit" onClick={handleSubmit}>
                   {editingItem ? 'Salvar Alterações' : 'Criar Solicitação'}
               </DarkButton>
           </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Painel de Detalhamento de Manutenção */}
      <Dialog open={isDetailPanelOpen} onOpenChange={setIsDetailPanelOpen}>
        <DialogContent className="w-[90vw] h-[85vh] max-w-6xl bg-white dark:bg-[#0f0f0f] border-slate-200 dark:border-[#2a2a2a] p-0 overflow-hidden shadow-2xl flex flex-col !outline-none">
          <LoadingOverlay isLoading={isSubmitting} message="Atualizando manutenção..." variant="minimal" />
          <DialogHeader className="p-4 md:p-6 border-b border-slate-200 dark:border-[#2a2a2a] shrink-0 bg-slate-50/50 dark:bg-[#0f0f0f]">
            <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
              <div className="flex items-start md:items-center gap-3 md:gap-4">
                <div className="p-3 md:p-4 bg-orange-500/10 rounded-2xl text-orange-600 shadow-inner shrink-0">
                  <Wrench size={24} className="md:w-7 md:h-7" />
                </div>
                <div className="min-w-0">
                  <DialogTitle className="text-lg md:text-2xl font-bold text-slate-800 dark:text-white uppercase tracking-tight truncate">
                    Detalhes da Manutenção #{selectedMaintenance?.idmanutencao_frota}
                  </DialogTitle>
                  <DialogDescription className="text-slate-500 dark:text-slate-400 font-medium text-xs md:text-sm flex flex-wrap items-center gap-y-1 gap-x-2">
                    <span className="whitespace-nowrap">
                      Placa: <span className="text-orange-500 font-bold">{selectedMaintenance?.placa}</span>
                    </span>
                    <span className="hidden md:inline text-slate-400">|</span>
                    <span className="whitespace-nowrap">
                      Status: <span className="font-bold">{selectedMaintenance?.status}</span>
                    </span>
                    {selectedMaintenance && (
                      <>
                        <span className="hidden md:inline text-slate-400">|</span>
                        <span className="inline-flex items-center gap-1">
                          Situação:
                          <span
                            className={`px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider ${
                              (selectedMaintenance.manutencao || '').toLowerCase().startsWith('abert')
                                ? 'bg-orange-500/10 text-orange-400 border border-orange-500/30'
                                : (selectedMaintenance.manutencao || '').toLowerCase().startsWith('fech')
                                ? 'bg-slate-500/10 text-slate-300 border border-slate-500/40'
                                : 'bg-slate-700/20 text-slate-300 border border-slate-600/40'
                            }`}
                          >
                            {selectedMaintenance.manutencao || 'Sem informação'}
                          </span>
                        </span>
                      </>
                    )}
                  </DialogDescription>
                </div>
              </div>
              <div className="flex flex-wrap items-center gap-2">
                <DarkButton 
                  variant="secondary"
                  onClick={() => handleToggleMaintenanceIndividual(selectedMaintenance)}
                  className="flex items-center gap-2 h-9 text-xs md:text-sm px-3"
                >
                  {(() => {
                    const manutLabel = (selectedMaintenance?.manutencao || '').trim().toLowerCase();
                    const isClosed = manutLabel === 'fechado' || manutLabel === 'fechada';
                    if (isClosed) return <><Unlock size={14} /> Abrir Manutenção</>;
                    return <><Lock size={14} /> Fechar Manutenção</>;
                  })()}
                </DarkButton>
                <DarkButton 
                  variant="secondary"
                  onClick={() => {
                    handleOpenModal(selectedMaintenance);
                    setIsDetailPanelOpen(false);
                  }}
                  className="flex items-center gap-2 h-9 text-xs md:text-sm px-3"
                >
                  <Edit2 size={14} />
                  Editar
                </DarkButton>
                <DarkButton 
                  variant="secondary"
                  onClick={() => {
                    if (window.confirm('Tem certeza que deseja excluir esta manutenção?')) {
                      deleteMaintenance(selectedMaintenance.idmanutencao_frota);
                      setIsDetailPanelOpen(false);
                    }
                  }}
                  className="flex items-center gap-2 h-9 text-xs md:text-sm px-3 text-rose-600 hover:text-rose-700 hover:bg-rose-500/10"
                >
                  <Trash2 size={14} />
                  Excluir
                </DarkButton>
              </div>
            </div>
          </DialogHeader>

          <div className="flex-1 overflow-hidden p-6 bg-white dark:bg-[#1c1c1c]">
            <Tabs defaultValue="detalhes" className="w-full h-full flex flex-col">
              <TabsList className="bg-slate-100 dark:bg-[#141414] border border-slate-200 dark:border-[#2a2a2a] w-full justify-start p-1 h-auto mb-4 shrink-0">
                <TabsTrigger value="detalhes" className="data-[state=active]:bg-orange-600 data-[state=active]:text-white text-slate-500 dark:text-stone-400 text-[10px] uppercase font-bold px-4 py-2">
                  Detalhes
                </TabsTrigger>
                <TabsTrigger 
                  value="completo" 
                  className="data-[state=active]:bg-orange-600 data-[state=active]:text-white text-slate-500 dark:text-stone-400 text-[10px] uppercase font-bold px-4 py-2"
                  onClick={() => handleLoadHistorico('completo')}
                >
                  Histórico Completo
                </TabsTrigger>
                <TabsTrigger 
                  value="detalhado" 
                  className="data-[state=active]:bg-orange-600 data-[state=active]:text-white text-slate-500 dark:text-stone-400 text-[10px] uppercase font-bold px-4 py-2"
                  onClick={() => handleLoadHistorico('detalhado')}
                >
                  Histórico Detalhado
                </TabsTrigger>
                <TabsTrigger 
                  value="estatisticas" 
                  className="data-[state=active]:bg-orange-600 data-[state=active]:text-white text-slate-500 dark:text-stone-400 text-[10px] uppercase font-bold px-4 py-2"
                  onClick={() => handleLoadHistorico('estatisticas')}
                >
                  Estatísticas
                </TabsTrigger>
                {(selectedMaintenance?.pdf_orcamento || selectedMaintenance?.nota_fiscal) && (
                  <TabsTrigger 
                    value="documentos" 
                    className="data-[state=active]:bg-orange-600 data-[state=active]:text-white text-slate-500 dark:text-stone-400 text-[10px] uppercase font-bold px-4 py-2 flex items-center gap-1.5"
                  >
                    <FileText size={14} />
                    Documentos
                  </TabsTrigger>
                )}
              </TabsList>

              <TabsContent value="detalhes" className="flex-1 overflow-y-auto custom-scrollbar m-0">
                {selectedMaintenance && (
                  <div className="space-y-8">
                    <DetailSection title="Identificação e veículo">
                      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">ID Manutenção</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.idmanutencao_frota ?? '-'}</p>
                        </div>
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Atendimento</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.atendimento ?? '-'}</p>
                        </div>
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Placa</label>
                          <p className="text-sm font-bold text-orange-600 dark:text-orange-500 mt-1 font-mono">{selectedMaintenance.placa ?? '-'}</p>
                        </div>
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Placa Reserva</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.placa_reserva ?? '-'}</p>
                        </div>
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Modelo</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.modelo ?? '-'}</p>
                        </div>
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Proprietário</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.proprietario ?? '-'}</p>
                        </div>
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Base Frota</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.base_frota ?? '-'}</p>
                        </div>
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Manutenção (Situação)</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.manutencao ?? '-'}</p>
                        </div>
                      </div>
                    </DetailSection>

                    <DetailSection title="Status e oficina">
                      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Status</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.status ?? '-'}</p>
                        </div>
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Status Frota Veículo</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.status_frota_veiculo ?? '-'}</p>
                        </div>
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Motivo Atendimento</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.motivo_atendimento ?? '-'}</p>
                        </div>
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Oficina</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.oficina ?? '-'}</p>
                        </div>
                      </div>
                    </DetailSection>

                    <DetailSection title="Localização">
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Endereço Prestador</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.endereco_prestador ?? '-'}</p>
                        </div>
                        <div className="grid grid-cols-2 gap-4">
                          <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                            <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Cidade</label>
                            <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.cidade ?? '-'}</p>
                          </div>
                          <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                            <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">UF</label>
                            <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.uf ?? '-'}</p>
                          </div>
                        </div>
                      </div>
                    </DetailSection>

                    <DetailSection title="Responsáveis e financeiro">
                      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Responsável</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.responsavel ?? '-'}</p>
                        </div>
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Resp. Aprovação</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.resp_aprovacao ?? '-'}</p>
                        </div>
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Validação Financeiro</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.validacao_financeiro ?? '-'}</p>
                        </div>
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Cond. Pagamento</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">
                            {selectedMaintenance.condicao_pagamento ?? '-'}
                            {selectedMaintenance.condicao_pagamento === 'Parcelado' && selectedMaintenance.qtd_parcelas_condicao_pag && (
                              <span className="ml-1 text-orange-500">({selectedMaintenance.qtd_parcelas_condicao_pag}x)</span>
                            )}
                          </p>
                        </div>
                      </div>
                    </DetailSection>

                    <DetailSection title="Orçamentos">
                      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Orçamento Inicial</label>
                          <p className="text-sm font-bold text-orange-600 dark:text-orange-500 mt-1 font-mono">{formatCurrency(selectedMaintenance.orcamento_inicial)}</p>
                        </div>
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Orçamento Final</label>
                          <p className="text-sm font-bold text-orange-600 dark:text-orange-500 mt-1 font-mono">{formatCurrency(selectedMaintenance.orcamento_final)}</p>
                        </div>
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Dif. Orçamento</label>
                          <p className="text-sm font-bold text-orange-600 dark:text-orange-500 mt-1 font-mono">{formatCurrency(selectedMaintenance.dif_orcamento)}</p>
                        </div>
                        {selectedMaintenance.condicao_pagamento === 'Parcelado' && selectedMaintenance.qtd_parcelas_condicao_pag && (
                          <div className="bg-orange-500/5 dark:bg-orange-500/10 border border-orange-500/20 rounded-xl p-4">
                            <label className="text-[10px] uppercase font-bold text-orange-600 dark:text-orange-400 tracking-wider">Valor da Parcela</label>
                            <p className="text-sm font-bold text-orange-600 dark:text-orange-400 mt-1 font-mono">
                              {(() => {
                                const total = parseCurrency(selectedMaintenance.orcamento_final);
                                const parcelas = parseInt(selectedMaintenance.qtd_parcelas_condicao_pag, 10);
                                if (total && parcelas > 0) return formatCurrency(total / parcelas);
                                return 'R$ 0,00';
                              })()}
                            </p>
                          </div>
                        )}
                        <FileLink label="PDF Orçamento" url={selectedMaintenance.pdf_orcamento_link || selectedMaintenance.pdf_orcamento} />
                        <FileLink label="Nota Fiscal" url={selectedMaintenance.nota_fiscal} />
                      </div>
                    </DetailSection>

                    <DetailSection title="Datas">
                      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Data Solicitação</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.data_solicitacao ?? '-'}</p>
                        </div>
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Data Agendamento</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.data_agendamento ?? '-'}</p>
                        </div>
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Data Parada</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.data_parada_veiculo ?? '-'}</p>
                        </div>
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Previsão Entrega</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.previsao_entrega ?? selectedMaintenance.previcao_entrega ?? '-'}</p>
                        </div>
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Data Finalização</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.data_finalizacao ?? '-'}</p>
                        </div>
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Data Retirada</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.data_retirada ?? '-'}</p>
                        </div>
                      </div>
                    </DetailSection>

                    <DetailSection title="SLA">
                      <div className="grid grid-cols-2 gap-4">
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">SLA Oficina</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.sla_oficina ?? '-'}</p>
                        </div>
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">SLA Pós-Oficina</label>
                          <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">{selectedMaintenance.sla_pos_oficina ?? '-'}</p>
                        </div>
                      </div>
                    </DetailSection>

                    <DetailSection title="Descrição e observações">
                      <div className="grid grid-cols-1 gap-4">
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Descrição da Manutenção</label>
                          <p className="text-sm text-slate-800 dark:text-white mt-1 whitespace-pre-wrap">{selectedMaintenance.manutencao ?? '-'}</p>
                        </div>
                        <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                          <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Observações</label>
                          <p className="text-sm text-slate-800 dark:text-white mt-1 whitespace-pre-wrap">{selectedMaintenance.obs ?? '-'}</p>
                        </div>
                      </div>
                    </DetailSection>
                  </div>
                )}
              </TabsContent>

              <TabsContent value="completo" className="flex-1 overflow-y-auto custom-scrollbar m-0">
                {loadingHistorico ? (
                  <div className="flex items-center justify-center h-full">
                    <div className="text-slate-500">Carregando histórico completo...</div>
                  </div>
                ) : (
                  <div className="space-y-4">
                    {historicoData.completo ? (
                      <>
                        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                          <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                            <span className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Total Manutenções</span>
                            <p className="text-2xl font-bold text-slate-800 dark:text-white mt-1">
                              {historicoData.completo.total_manutencoes ?? 0}
                            </p>
                          </div>
                          <div className="bg-orange-50 dark:bg-orange-900/20 border border-orange-200 dark:border-orange-800 rounded-xl p-4">
                            <span className="text-[10px] uppercase font-bold text-orange-700 dark:text-orange-300 tracking-wider">Concluídas</span>
                            <p className="text-2xl font-bold text-orange-700 dark:text-orange-300 mt-1">
                              {historicoData.completo.manutencoes_concluidas ?? 0}
                            </p>
                          </div>
                          <div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-xl p-4">
                            <span className="text-[10px] uppercase font-bold text-amber-700 dark:text-amber-300 tracking-wider">Em Andamento</span>
                            <p className="text-2xl font-bold text-amber-700 dark:text-amber-300 mt-1">
                              {historicoData.completo.manutencoes_em_andamento ?? 0}
                            </p>
                          </div>
                          <div className="bg-rose-50 dark:bg-rose-900/20 border border-rose-200 dark:border-rose-800 rounded-xl p-4">
                            <span className="text-[10px] uppercase font-bold text-rose-700 dark:text-rose-300 tracking-wider">Canceladas</span>
                            <p className="text-2xl font-bold text-rose-700 dark:text-rose-300 mt-1">
                              {historicoData.completo.manutencoes_canceladas ?? 0}
                            </p>
                          </div>
                        </div>

                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                          <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                            <span className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Primeira Manutenção</span>
                            <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">
                              {historicoData.completo.primeira_manutencao || '-'}
                            </p>
                          </div>
                          <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                            <span className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Última Manutenção</span>
                            <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">
                              {historicoData.completo.ultima_manutencao || '-'}
                            </p>
                          </div>
                          <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                            <span className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Modelo</span>
                            <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">
                              {historicoData.completo.modelo || '-'}
                            </p>
                          </div>
                        </div>
                      </>
                    ) : (
                      <div className="text-center text-slate-500 py-8">
                        Nenhum histórico completo encontrado para esta placa.
                      </div>
                    )}
                  </div>
                )}
              </TabsContent>

              <TabsContent value="detalhado" className="flex-1 overflow-y-auto custom-scrollbar m-0">
                {loadingHistorico ? (
                  <div className="flex items-center justify-center h-full">
                    <div className="text-slate-500">Carregando histórico detalhado...</div>
                  </div>
                ) : (
                  <div className="space-y-4">
                    {historicoData.detalhado.length > 0 ? (
                      <ExcelTable 
                        data={historicoData.detalhado}
                        columns={[
                          { header: 'ID Manutenção', field: 'idmanutencao_frota', width: '120px' },
                          { header: 'Placa', field: 'placa', width: '100px', className: 'font-mono font-bold text-orange-600 dark:text-orange-500' },
                          { header: 'Modelo', field: 'modelo', width: '140px' },
                          { header: 'Oficina', field: 'oficina', width: '180px' },
                          { header: 'Motivo', field: 'motivo_atendimento', width: '140px' },
                          { header: 'Status', field: 'status', width: '160px' },
                          { header: 'Situação', field: 'situacao', width: '120px' },
                          { header: 'Dias em Manutenção', field: 'dias_em_manutencao', width: '160px' },
                          { header: 'Orçamento Inicial', field: 'orcamento_inicial', width: '140px', render: (row) => formatCurrency(row.orcamento_inicial) },
                          { header: 'Orçamento Final', field: 'orcamento_final', width: '140px', render: (row) => formatCurrency(row.orcamento_final) },
                          { header: 'Dif. Orçamento', field: 'dif_orcamento', width: '140px', render: (row) => formatCurrency(row.dif_orcamento) },
                          { header: 'Data Solicitação', field: 'data_solicitacao', width: '140px' },
                          { header: 'Data Agendamento', field: 'data_agendamento', width: '140px' },
                          { header: 'Data Parada', field: 'data_parada_veiculo', width: '140px' },
                          { header: 'Data Finalização', field: 'data_finalizacao', width: '140px' },
                          { header: 'Data Retirada', field: 'data_retirada', width: '140px' },
                        ]}
                      />
                    ) : (
                      <div className="text-center text-slate-500 py-8">Nenhum histórico detalhado encontrado</div>
                    )}
                  </div>
                )}
              </TabsContent>

              <TabsContent value="estatisticas" className="flex-1 overflow-y-auto custom-scrollbar m-0">
                {loadingHistorico ? (
                  <div className="flex items-center justify-center h-full">
                    <div className="text-slate-500">Carregando estatísticas...</div>
                  </div>
                ) : (
                  <div className="space-y-4">
                    {historicoData.estatisticas ? (
                      <>
                        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                          <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                            <span className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">
                              Total Registros
                            </span>
                            <p className="text-2xl font-bold text-slate-800 dark:text-white mt-1">
                              {historicoData.estatisticas.total_registros ?? 0}
                            </p>
                          </div>
                          <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                            <span className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">
                              Oficinas Diferentes
                            </span>
                            <p className="text-2xl font-bold text-slate-800 dark:text-white mt-1">
                              {historicoData.estatisticas.total_oficinas_diferentes ?? 0}
                            </p>
                          </div>
                          <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                            <span className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">
                              Tipos de Problemas
                            </span>
                            <p className="text-2xl font-bold text-slate-800 dark:text-white mt-1">
                              {historicoData.estatisticas.tipos_problemas_diferentes ?? 0}
                            </p>
                          </div>
                          <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                            <span className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">
                              Valor Total Gasto
                            </span>
                            <p className="text-2xl font-bold text-orange-700 dark:text-orange-300 mt-1">
                              {formatCurrency(historicoData.estatisticas.valor_total_gasto)}
                            </p>
                          </div>
                        </div>

                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                          <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                            <span className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">
                              Valor Médio Manutenção
                            </span>
                            <p className="text-sm font-bold text-orange-700 dark:text-orange-300 mt-1">
                              {formatCurrency(historicoData.estatisticas.valor_medio_manutencao)}
                            </p>
                          </div>
                          <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                            <span className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">
                              Principais Motivos
                            </span>
                            <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">
                              {historicoData.estatisticas.principais_motivos || '-'}
                            </p>
                          </div>
                          <div className="bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-xl p-4">
                            <span className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">
                              Status Encontrados
                            </span>
                            <p className="text-sm font-bold text-slate-800 dark:text-white mt-1">
                              {historicoData.estatisticas.status_encontrados || '-'}
                            </p>
                          </div>
                        </div>
                      </>
                    ) : (
                      <div className="text-center text-slate-500 py-8">Nenhuma estatística disponível</div>
                    )}
                  </div>
                )}
              </TabsContent>

              <TabsContent value="documentos" className="flex-1 overflow-hidden flex flex-col m-0 pt-2">
                {selectedMaintenance && (selectedMaintenance.pdf_orcamento || selectedMaintenance.nota_fiscal) && (
                  <Tabs defaultValue={selectedMaintenance.pdf_orcamento ? "pdf" : "nota"} className="w-full h-full flex flex-col">
                    <TabsList className="bg-slate-100/50 dark:bg-orange-500/5 border border-slate-200 dark:border-orange-500/20 w-fit p-1 h-auto mb-4 shrink-0 self-center md:self-start">
                      {selectedMaintenance.pdf_orcamento && (
                        <TabsTrigger 
                          value="pdf" 
                          className="data-[state=active]:bg-orange-600 data-[state=active]:text-white text-slate-500 dark:text-stone-400 text-[10px] uppercase font-bold px-6 py-2"
                        >
                          PDF Orçamento
                        </TabsTrigger>
                      )}
                      {selectedMaintenance.nota_fiscal && (
                        <TabsTrigger 
                          value="nota" 
                          className="data-[state=active]:bg-orange-600 data-[state=active]:text-white text-slate-500 dark:text-stone-400 text-[10px] uppercase font-bold px-6 py-2"
                        >
                          Nota Fiscal
                        </TabsTrigger>
                      )}
                    </TabsList>

                    <TabsContent value="pdf" className="flex-1 overflow-hidden m-0">
                      <div className="w-full h-full bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-2xl overflow-hidden flex flex-col shadow-sm">
                        <div className="p-3 border-b border-slate-200 dark:border-[#333] flex items-center justify-between bg-white dark:bg-[#1a1a1a]">
                          <div className="flex items-center gap-2">
                            <FileText size={16} className="text-orange-500" />
                            <span className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Visualização: PDF Orçamento</span>
                          </div>
                          <a href={selectedMaintenance.pdf_orcamento} target="_blank" rel="noreferrer" className="text-[10px] uppercase font-bold text-blue-500 hover:underline">Abrir em nova aba</a>
                        </div>
                        <div className="flex-1 bg-slate-100 dark:bg-[#0a0a0a]">
                          {isInternalFileUrl(selectedMaintenance.pdf_orcamento) ? (
                            <iframe src={selectedMaintenance.pdf_orcamento} title="PDF Orçamento" className="w-full h-full border-0" />
                          ) : (
                            <div className="p-8 flex flex-col items-center justify-center h-full text-center space-y-4">
                              <div className="p-6 bg-blue-500/10 rounded-full text-blue-500"><Search size={48} /></div>
                              <div className="space-y-2">
                                <h4 className="font-bold text-slate-800 dark:text-white">Documento Externo</h4>
                                <p className="text-sm text-slate-500 dark:text-slate-400 max-w-md">Este arquivo está hospedado em um servidor externo e não pode ser visualizado diretamente aqui por questões de segurança.</p>
                              </div>
                              <a href={selectedMaintenance.pdf_orcamento} target="_blank" rel="noreferrer" className="px-6 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-xl font-bold text-sm shadow-lg shadow-blue-500/20 transition-all flex items-center gap-2">
                                Abrir Documento Externo <Search size={16} />
                              </a>
                            </div>
                          )}
                        </div>
                      </div>
                    </TabsContent>

                    <TabsContent value="nota" className="flex-1 overflow-hidden m-0">
                      <div className="w-full h-full bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-2xl overflow-hidden flex flex-col shadow-sm">
                        <div className="p-3 border-b border-slate-200 dark:border-[#333] flex items-center justify-between bg-white dark:bg-[#1a1a1a]">
                          <div className="flex items-center gap-2">
                            <FileText size={16} className="text-orange-500" />
                            <span className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider">Visualização: Nota Fiscal</span>
                          </div>
                          <a href={selectedMaintenance.nota_fiscal} target="_blank" rel="noreferrer" className="text-[10px] uppercase font-bold text-blue-500 hover:underline">Abrir em nova aba</a>
                        </div>
                        <div className="flex-1 bg-slate-100 dark:bg-[#0a0a0a]">
                          {isInternalFileUrl(selectedMaintenance.nota_fiscal) ? (
                            <iframe src={selectedMaintenance.nota_fiscal} title="Nota Fiscal" className="w-full h-full border-0" />
                          ) : (
                            <div className="p-8 flex flex-col items-center justify-center h-full text-center space-y-4">
                              <div className="p-6 bg-amber-500/10 rounded-full text-amber-500"><Search size={48} /></div>
                              <div className="space-y-2">
                                <h4 className="font-bold text-slate-800 dark:text-white">Documento Externo</h4>
                                <p className="text-sm text-slate-500 dark:text-slate-400 max-w-md">Este arquivo está hospedado em um servidor externo e não pode ser visualizado diretamente aqui.</p>
                              </div>
                              <a href={selectedMaintenance.nota_fiscal} target="_blank" rel="noreferrer" className="px-6 py-2.5 bg-amber-600 hover:bg-amber-700 text-white rounded-xl font-bold text-sm shadow-lg shadow-amber-500/20 transition-all flex items-center gap-2">
                                Abrir Documento Externo <Search size={16} />
                              </a>
                            </div>
                          )}
                        </div>
                      </div>
                    </TabsContent>
                  </Tabs>
                )}
              </TabsContent>

            </Tabs>
          </div>

          <DialogFooter className="p-4 border-t border-slate-200 dark:border-[#2a2a2a] bg-slate-50/50 dark:bg-[#1c1c1c] shrink-0">
            <DarkButton variant="secondary" onClick={() => setIsDetailPanelOpen(false)}>
              Fechar
            </DarkButton>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Records Detail Modal */}
      <Dialog open={isRecordsModalOpen} onOpenChange={setIsRecordsModalOpen}>
        <DialogContent className="max-w-7xl w-[95vw] h-[90vh] bg-white dark:bg-[#0f0f0f] border-slate-200 dark:border-[#2a2a2a] p-0 overflow-hidden shadow-2xl flex flex-col !outline-none">
            <DialogHeader className="p-6 border-b border-slate-200 dark:border-[#2a2a2a] shrink-0 bg-slate-50/50 dark:bg-[#0f0f0f]">
                <div className="flex items-center gap-4">
                  <div className="p-4 bg-indigo-500/10 rounded-2xl text-indigo-600 shadow-inner">
                    <Wrench size={28} />
                  </div>
                  <div>
                    <DialogTitle className="text-2xl font-bold text-slate-800 dark:text-white uppercase tracking-tight">
                      Veículos: {selectedStatusRecords?.title}
                    </DialogTitle>
                    <DialogDescription className="text-slate-500 dark:text-slate-400 font-medium text-sm">
                      Listagem técnica dos {selectedStatusRecords?.records?.length || 0} veículos com status <span className="text-orange-500 font-bold">"{selectedStatusRecords?.title}"</span>.
                    </DialogDescription>
                  </div>
                </div>
            </DialogHeader>

            <div className="flex-1 overflow-hidden p-6 bg-white dark:bg-[#1c1c1c]">
                <div className="h-full w-full rounded-2xl border border-slate-200 dark:border-[#2a2a2a] overflow-hidden shadow-sm">
                  <ExcelTable 
                    data={selectedStatusRecords?.records || []}
                    columns={[
                      { header: 'Placa', field: 'placa', width: '100px', className: 'font-mono font-bold text-orange-600 dark:text-orange-500' },
                      { header: 'Modelo', field: 'modelo', width: '150px' },
                      { header: 'Unidade', field: 'base', width: '120px' },
                      { header: 'Motorista', field: 'motorista', width: '180px' },
                      { header: 'Status', field: 'status', width: '140px' },
                      { header: 'Manutenção', field: 'manutencao', width: '120px' },
                      { header: 'Atuação', field: 'atuacao', width: '140px' },
                      { header: 'Proprietário', field: 'proprietario', width: '140px' },
                      { header: 'VecFleet', field: 'vecfleet', width: '140px' },
                      { header: 'OBS', field: 'obs', width: '250px' },
                    ]}
                    filterDefs={[
                      { field: 'placa', label: 'Placa', type: 'text' },
                      { field: 'motorista', label: 'Motorista', type: 'text' },
                      { field: 'base', label: 'Unidade', type: 'select' }
                    ]}
                    onDelete={(item) => deleteVehicle(item.idveiculo_frota)}
                  />
                </div>
            </div>

            <DialogFooter className="p-4 border-t border-slate-200 dark:border-[#2a2a2a] bg-slate-50/50 dark:bg-[#1c1c1c]">
                <DarkButton variant="secondary" onClick={() => setIsRecordsModalOpen(false)}>
                  Fechar Listagem
                </DarkButton>
            </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}



