import React, { useState } from 'react';
import { ClipboardCheck, Truck, Clock, ShieldCheck, Filter, Search, Plus, Calendar, AlertTriangle, RefreshCw, Wrench, X, CheckCircle2, LayoutDashboard } from 'lucide-react';
import { useChecklist } from '../hooks/useChecklist';
import { VehicleFormModal } from '../components/VehicleFormModal';
import ExcelTable from '../components/ExcelTable';
import { GrKanbanBoard } from '../components/GrKanbanBoard';
import { useGrStore } from '../services/useGrStore';

const Modal = ({ isOpen, onClose, title, children }) => {
  if (!isOpen) return null;
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm animate-in fade-in duration-300">
      <div className="bg-white dark:bg-[#1b1b1b] w-full max-w-xl rounded-[32px] border border-slate-200 dark:border-white/5 shadow-2xl overflow-hidden animate-in zoom-in-95 duration-300">
        <div className="flex items-center justify-between p-6 border-b border-slate-100 dark:border-white/5">
          <h3 className="text-xl font-bold text-slate-800 dark:text-white">{title}</h3>
          <button onClick={onClose} className="p-2 hover:bg-slate-100 dark:hover:bg-white/5 rounded-full transition-colors text-slate-400">
            <X size={20} />
          </button>
        </div>
        <div className="p-8 max-h-[80vh] overflow-y-auto">
          {children}
        </div>
      </div>
    </div>
  );
};

const GrChecklistView = () => {
  const { userData } = useGrStore();
  const userRole = userData?.usuario?.grupo || 'Administrador';
  const [activeTab, setActiveTab] = useState('checklist'); // checklist, os
  const [activeClient, setActiveClient] = useState('ALL');
  const [viewMode, setViewMode] = useState('grid'); // grid, table, kanban
  const [osViewMode, setOsViewMode] = useState('grid'); // grid, table, kanban
  const [searchTerm, setSearchTerm] = useState('');
  const [osSearchTerm, setOsSearchTerm] = useState('');
  const [osStatusFilter, setOsStatusFilter] = useState('ALL');
  const [isOSModalOpen, setIsOSModalOpen] = useState(false);
  const [isVehicleModalOpen, setIsVehicleModalOpen] = useState(false);
  const [selectedVehicleId, setSelectedVehicleId] = useState(null);
  const [bases, setBases] = useState([]);
  const [osForm, setOsForm] = useState({ type: 'SENSOR', description: '', sensor: '', osNumber: '' });
  
  const { vehicles, maintenanceOrders, stats, loading, error, refresh, renewChecklist, createMaintenanceOrder } = useChecklist({
    client: activeClient === 'ALL' ? undefined : activeClient
  });

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

  const filteredVehicles = vehicles.filter(vehicle => 
    vehicle.plate.toLowerCase().includes(searchTerm.toLowerCase()) ||
    (vehicle.driver && vehicle.driver.toLowerCase().includes(searchTerm.toLowerCase()))
  );

  const filteredOS = maintenanceOrders.filter(os => {
    const matchesSearch = os.plate.toLowerCase().includes(osSearchTerm.toLowerCase()) || 
                          os.osNumber.toLowerCase().includes(osSearchTerm.toLowerCase());
    const matchesStatus = osStatusFilter === 'ALL' || os.status === osStatusFilter;
    return matchesSearch && matchesStatus;
  });

  const clients = ['ALL', 'PRALOG', 'PROFARMA', 'PETY', 'MERCADO_LIVRE'];

  const getStatusStyle = (status) => {
    switch (status) {
      case 'VALID': return 'bg-emerald-500/10 text-emerald-500 border-emerald-500/20';
      case 'WARNING': return 'bg-amber-500/10 text-amber-500 border-amber-500/20';
      case 'EXPIRED': return 'bg-red-500/10 text-red-500 border-red-500/20';
      default: return 'bg-slate-500/10 text-slate-500 border-slate-500/20';
    }
  };

  const handleRenew = async (vehicleId) => {
    try {
      await renewChecklist(vehicleId);
      alert('Checklist renovado com sucesso! (+30 dias)');
    } catch (err) {
      alert(`Erro ao renovar: ${err.message}`);
    }
  };

  const handleOpenOS = (id) => {
    setSelectedVehicleId(id);
    setIsOSModalOpen(true);
  };

  const handleCreateOS = async (e) => {
    e.preventDefault();
    try {
      const vehicle = vehicles.find(v => v.id === selectedVehicleId);
      await createMaintenanceOrder({
        vehicleId: selectedVehicleId,
        plate: vehicle.plate,
        ...osForm,
        createdBy: 'Operador Atual'
      });
      alert('Ordem de Serviço criada com sucesso!');
      setIsOSModalOpen(false);
      setOsForm({ type: 'SENSOR', description: '', sensor: 'Baú' });
    } catch (err) {
      alert(err.message);
    }
  };

  return (
    <div className="flex flex-col gap-8 p-6 md:p-10 animate-in fade-in slide-in-from-bottom-4 duration-700">
      <header className="flex flex-col md:flex-row md:items-end justify-between gap-6">
        <div className="space-y-4">
          <h1 className="text-4xl md:text-6xl font-bold text-slate-800 dark:text-white tracking-tighter leading-none">
            {activeTab === 'checklist' ? 'Saúde da' : 'Acompanhamento de'} <span className="text-[var(--gr-primary)]">{activeTab === 'checklist' ? 'Frota' : 'Manutenções'}</span>
          </h1>
          
          <div className="flex p-1.5 bg-slate-100 dark:bg-[#141414] rounded-2xl border border-slate-200 dark:border-white/5 w-fit">
            <button
              onClick={() => setActiveTab('checklist')}
              className={`px-6 py-2 rounded-xl text-[10px] font-bold uppercase tracking-widest transition-all ${
                activeTab === 'checklist' 
                ? 'bg-white dark:bg-[#1b1b1b] text-slate-900 dark:text-white shadow-md' 
                : 'text-slate-400 hover:text-slate-600 dark:hover:text-slate-200'
              }`}
            >
              Frota
            </button>
            <button
              onClick={() => setActiveTab('os')}
              className={`px-6 py-2 rounded-xl text-[10px] font-bold uppercase tracking-widest transition-all ${
                activeTab === 'os' 
                ? 'bg-white dark:bg-[#1b1b1b] text-slate-900 dark:text-white shadow-md' 
                : 'text-slate-400 hover:text-slate-600 dark:hover:text-slate-200'
              }`}
            >
              Manutenções
            </button>
          </div>
        </div>

        <div className="flex gap-3">
          <button
            onClick={refresh}
            disabled={loading}
            className="flex items-center gap-2 px-6 py-3 bg-slate-100 dark:bg-[#141414] text-slate-800 dark:text-white rounded-full font-bold text-[10px] uppercase tracking-widest hover:bg-slate-200 dark:hover:bg-[#1f1f1f] transition-all disabled:opacity-50"
          >
            <RefreshCw size={16} className={loading ? 'animate-spin' : ''} />
            Atualizar
          </button>
          <button 
             onClick={() => setIsVehicleModalOpen(true)}
             className="flex items-center gap-2 px-6 py-3 bg-[var(--gr-primary)] text-white rounded-full font-bold text-[10px] uppercase tracking-widest hover:bg-[var(--gr-primary)]/90 transition-all shadow-lg shadow-[var(--gr-primary)]/20"
          >
            <Plus size={16} />
            Novo Veículo
          </button>
        </div>
      </header>

      {/* Stats Cards - Mostrados apenas na aba correta para clareza */}
      {stats && activeTab === 'checklist' && (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div className="p-4 bg-white dark:bg-[#1b1b1b] rounded-2xl border border-slate-200 dark:border-white/5">
            <div className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-2">Total Frota</div>
            <div className="text-3xl font-bold text-slate-800 dark:text-white">{vehicles.length}</div>
          </div>
          <div className="p-4 bg-white dark:bg-[#1b1b1b] rounded-2xl border border-slate-200 dark:border-white/5">
            <div className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-2">Válidos</div>
            <div className="text-3xl font-bold text-green-600">{stats.valid}</div>
          </div>
          <div className="p-4 bg-white dark:bg-[#1b1b1b] rounded-2xl border border-slate-200 dark:border-white/5">
            <div className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-2">Atenção</div>
            <div className="text-3xl font-bold text-yellow-600">{stats.warning}</div>
          </div>
          <div className="p-4 bg-white dark:bg-[#1b1b1b] rounded-2xl border border-slate-200 dark:border-white/5">
            <div className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-2">Expirados</div>
            <div className="text-3xl font-bold text-red-600">{stats.expired}</div>
          </div>
        </div>
      )}

      {stats && activeTab === 'os' && (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div className="p-4 bg-white dark:bg-[#1b1b1b] rounded-2xl border border-slate-200 dark:border-white/5">
            <div className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-2">Total OS</div>
            <div className="text-3xl font-bold text-slate-800 dark:text-white">{maintenanceOrders.length}</div>
          </div>
          <div className="p-4 bg-white dark:bg-[#1b1b1b] rounded-2xl border border-slate-200 dark:border-white/5">
            <div className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-2">Abertas</div>
            <div className="text-3xl font-bold text-orange-600">{maintenanceOrders.filter(os => os.status === 'ABERTO').length}</div>
          </div>
          <div className="p-4 bg-white dark:bg-[#1b1b1b] rounded-2xl border border-slate-200 dark:border-white/5">
            <div className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-2">Em Análise</div>
            <div className="text-3xl font-bold text-blue-600">{maintenanceOrders.filter(os => os.status === 'EM_ANALISE').length}</div>
          </div>
          <div className="p-4 bg-white dark:bg-[#1b1b1b] rounded-2xl border border-slate-200 dark:border-white/5">
            <div className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-2">Concluídas</div>
            <div className="text-3xl font-bold text-emerald-600">{maintenanceOrders.filter(os => os.status === 'CONCLUIDO').length}</div>
          </div>
        </div>
      )}

      {/* Tabs / Filters */}
      <div className="flex flex-wrap gap-4 items-center justify-between bg-white dark:bg-[#1b1b1b] p-4 rounded-[32px] border border-slate-200 dark:border-white/5 shadow-sm">
        <div className="flex gap-2 p-1.5 bg-slate-100 dark:bg-[#141414] rounded-2xl border border-slate-200 dark:border-white/5 shadow-inner">
          {activeTab === 'checklist' ? clients.map(client => (
            <button
              key={client}
              onClick={() => setActiveClient(client)}
              className={`px-5 py-1.5 rounded-xl text-[10px] font-bold uppercase tracking-widest transition-all whitespace-nowrap ${
                activeClient === client 
                ? 'bg-white dark:bg-[#1b1b1b] text-slate-900 dark:text-white shadow-md' 
                : 'text-slate-400 hover:text-slate-600 dark:hover:text-slate-200'
              }`}
            >
              {client === 'ALL' ? 'Todos' : client.replace('_', ' ')}
            </button>
          )) : (
            <div className="px-5 py-1.5 text-[10px] font-bold text-slate-400 uppercase tracking-widest">Filtros de Manutenção</div>
          )}
        </div>

        <div className="flex items-center gap-6">
          <div className="flex p-1 bg-slate-100 dark:bg-[#141414] rounded-xl border border-slate-200 dark:border-white/5 overflow-hidden">
            <button 
              onClick={() => activeTab === 'checklist' ? setViewMode('grid') : setOsViewMode('grid')}
              className={`p-2 rounded-lg transition-all ${ (activeTab === 'checklist' ? viewMode : osViewMode) === 'grid' ? 'bg-white dark:bg-[#1b1b1b] text-[var(--gr-primary)] shadow-sm' : 'text-slate-400 hover:text-slate-600'}`}
              title="Grade"
            >
              <LayoutDashboard size={18} />
            </button>
            <button 
              onClick={() => activeTab === 'checklist' ? setViewMode('table') : setOsViewMode('table')}
              className={`p-2 rounded-lg transition-all ${ (activeTab === 'checklist' ? viewMode : osViewMode) === 'table' ? 'bg-white dark:bg-[#1b1b1b] text-[var(--gr-primary)] shadow-sm' : 'text-slate-400 hover:text-slate-600'}`}
              title="Tabela"
            >
              <Filter size={18} />
            </button>
            <button 
              onClick={() => activeTab === 'checklist' ? setViewMode('kanban') : setOsViewMode('kanban')}
              className={`p-2 rounded-lg transition-all ${ (activeTab === 'checklist' ? viewMode : osViewMode) === 'kanban' ? 'bg-white dark:bg-[#1b1b1b] text-[var(--gr-primary)] shadow-sm' : 'text-slate-400 hover:text-slate-600'}`}
              title="Kanban"
            >
              <ClipboardCheck size={18} />
            </button>
          </div>

          <div className="relative group">
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 group-focus-within:text-[var(--gr-primary)] transition-colors" size={16} />
            <input 
              type="text" 
              placeholder={activeTab === 'checklist' ? "BUSCAR PLACA..." : "BUSCAR O.S. OU PLACA..."}
              value={activeTab === 'checklist' ? searchTerm : osSearchTerm}
              onChange={(e) => activeTab === 'checklist' ? setSearchTerm(e.target.value) : setOsSearchTerm(e.target.value)}
              className="pl-10 pr-4 py-2 bg-white dark:bg-[#141414] border border-slate-200 dark:border-white/5 rounded-full text-[10px] font-bold focus:outline-none focus:ring-4 focus:ring-[var(--gr-primary)]/10 transition-all uppercase outline-none w-48"
            />
          </div>
        </div>
      </div>

      {/* Conteúdo Dinâmico por ViewMode - APENAS SE ESTIVER NA ABA CHECKLIST */}
      {activeTab === 'checklist' && (
        <>
          {viewMode === 'grid' && (
            <div className="grid md:grid-cols-2 xl:grid-cols-3 gap-6">
              {filteredVehicles.map((vehicle) => (
                <div
                  key={vehicle.id}
                  className="p-6 bg-white dark:bg-[#1b1b1b] rounded-3xl border border-slate-200 dark:border-white/5 hover:border-[var(--gr-primary)]/40 transition-all shadow-sm group"
                >
                  <div className="flex items-start justify-between mb-6">
                    <div className="flex items-center gap-4">
                      <div className="p-3 bg-[var(--gr-primary)]/10 rounded-2xl group-hover:bg-[var(--gr-primary)] group-hover:text-white transition-all">
                        <Truck size={24} />
                      </div>
                      <div>
                        <h3 className="text-2xl font-bold text-slate-800 dark:text-white tracking-tighter">{vehicle.plate}</h3>
                        <p className="text-[10px] text-slate-400 font-bold uppercase tracking-widest">{vehicle.type}</p>
                      </div>
                    </div>
                    <span className={`px-4 py-1.5 rounded-full text-[10px] font-bold tracking-widest border uppercase ${getStatusStyle(vehicle.status)}`}>
                      {vehicle.status}
                    </span>
                  </div>

                  <div className="space-y-4">
                    <div className="flex items-center gap-3 p-3 bg-slate-50 dark:bg-[#141414] rounded-2xl border border-slate-100 dark:border-white/5">
                      <Calendar size={16} className="text-slate-400" />
                      <div>
                        <p className="text-[8px] font-bold text-slate-400 uppercase tracking-widest">Checklist</p>
                        <p className="text-sm font-bold text-slate-700 dark:text-slate-200">{vehicle.checklistExpiry}</p>
                      </div>
                    </div>

                    <div className="flex gap-2">
                      {vehicle.status !== 'VALID' && (
                        <button
                          onClick={() => handleRenew(vehicle.id)}
                          className="flex-1 px-4 py-3.5 bg-emerald-500 text-white rounded-2xl text-[10px] font-bold uppercase tracking-widest hover:bg-emerald-600 transition-all flex items-center justify-center gap-2 shadow-lg shadow-emerald-500/20"
                        >
                          <CheckCircle2 size={14} />
                          Renovar
                        </button>
                      )}
                      <button 
                        onClick={() => handleOpenOS(vehicle.id)}
                        className="flex-1 px-4 py-3.5 bg-slate-800 dark:bg-[#252525] text-white rounded-2xl text-[10px] font-bold uppercase tracking-widest hover:bg-slate-900 transition-all flex items-center justify-center gap-2 shadow-lg"
                      >
                        <Wrench size={14} />
                        Nova OS
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}

          {viewMode === 'table' && (
            <div className="flex-1 min-h-[500px]">
              <ExcelTable 
                data={filteredVehicles}
                loading={loading}
                columns={[
                  { field: 'plate', header: 'Placa', width: 120, render: (row) => (
                    <div>
                      <div className="font-bold text-slate-800 dark:text-white tracking-tighter">{row.plate}</div>
                      <div className="text-[9px] text-slate-400 font-bold uppercase">{row.type}</div>
                    </div>
                  )},
                  { field: 'driver', header: 'Motorista', width: 220 },
                  { field: 'checklistExpiry', header: 'Checklist', width: 150 },
                  { field: 'status', header: 'Status', width: 120, render: (row) => (
                    <span className={`px-3 py-1 rounded-full text-[10px] font-bold uppercase tracking-widest border ${getStatusStyle(row.status)}`}>
                      {row.status}
                    </span>
                  )}
                ]}
                onEdit={(row) => handleOpenOS(row.id)}
                pageSize={10}
                filterDefs={[
                  { field: 'plate', header: 'Placa', type: 'text' },
                  { field: 'driver', header: 'Motorista', type: 'text' },
                  { field: 'base', header: 'Base', type: 'select' }
                ]}
                filterOptions={{
                  base: bases.map(b => b.base || b.nome).filter(Boolean).sort()
                }}
              />
            </div>
          )}

          {viewMode === 'kanban' && (
            <div className="h-[600px] flex gap-4 w-full">
              <GrKanbanBoard 
                userRole={userRole}
                columns={[
                  { 
                    id: 'VALID', 
                    title: 'Em Dia', 
                    color: 'emerald', 
                    cards: filteredVehicles.filter(v => v.status === 'VALID').map(v => ({
                      id: v.id,
                      title: v.plate,
                      subtitle: v.driver || 'Sem Motorista',
                      date: v.checklistExpiry,
                      details: [{ label: 'Tipo', value: v.type }]
                    }))
                  },
                  { 
                    id: 'WARNING', 
                    title: 'Atenção', 
                    color: 'orange', 
                    cards: filteredVehicles.filter(v => v.status === 'WARNING').map(v => ({
                      id: v.id,
                      title: v.plate,
                      subtitle: v.driver || 'Sem Motorista',
                      date: v.checklistExpiry,
                      details: [{ label: 'Tipo', value: v.type }]
                    }))
                  },
                  { 
                    id: 'EXPIRED', 
                    title: 'Vencidos', 
                    color: 'red', 
                    cards: filteredVehicles.filter(v => v.status === 'EXPIRED').map(v => ({
                      id: v.id,
                      title: v.plate,
                      subtitle: v.driver || 'Sem Motorista',
                      date: v.checklistExpiry,
                      details: [{ label: 'Tipo', value: v.type }]
                    }))
                  }
                ]}
                onCardClick={(card) => handleOpenOS(card.id)}
              />
            </div>
          )}
        </>
      )}

      {/* Modal Nova OS - Redesenhado conforme Prints */}
      <Modal 
        isOpen={isOSModalOpen} 
        onClose={() => setIsOSModalOpen(false)}
        title={
          <div className="flex items-center gap-3">
            <Wrench className="text-[#f15a24]" size={28} />
            <span className="text-2xl font-bold text-slate-800 dark:text-white tracking-tighter">Nova O.S.</span>
          </div>
        }
      >
        <form onSubmit={handleCreateOS} className="space-y-6">
          {/* Tabs Internas */}
          <div className="flex p-1.5 bg-slate-100 dark:bg-[#141414] rounded-2xl border border-slate-200 dark:border-white/5 shadow-inner">
            <button
              type="button"
              onClick={() => setOsForm({...osForm, type: 'SENSOR'})}
              className={`flex-1 py-3 rounded-xl text-[10px] font-bold uppercase tracking-widest transition-all ${
                osForm.type === 'SENSOR' 
                ? 'bg-white dark:bg-[#1b1b1b] text-slate-900 dark:text-white shadow-md' 
                : 'text-slate-400'
              }`}
            >
              Sensores
            </button>
            <button
              type="button"
              onClick={() => setOsForm({...osForm, type: 'INTERNO'})}
              className={`flex-1 py-3 rounded-xl text-[10px] font-bold uppercase tracking-widest transition-all ${
                osForm.type === 'INTERNO' 
                ? 'bg-white dark:bg-[#1b1b1b] text-slate-900 dark:text-white shadow-md' 
                : 'text-slate-400'
              }`}
            >
              Interna
            </button>
          </div>

          {/* Placa (Read-only) */}
          <div className="space-y-2">
            <div className="relative">
              <input 
                type="text" 
                readOnly
                value={vehicles.find(v => v.id === selectedVehicleId)?.plate || ''}
                className="w-full px-6 py-4 bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-white/5 rounded-2xl text-base font-bold text-slate-400 focus:outline-none"
                placeholder="Placa"
              />
            </div>
          </div>

          {osForm.type === 'SENSOR' ? (
            <>
              {/* Select de Sensores */}
              <div className="space-y-2">
                <select 
                  required
                  value={osForm.sensor}
                  onChange={(e) => setOsForm({...osForm, sensor: e.target.value})}
                  className="w-full px-6 py-4 bg-white dark:bg-[#141414] border border-slate-200 dark:border-white/5 rounded-2xl text-base font-medium text-slate-700 dark:text-white outline-none ring-2 ring-transparent focus:ring-[#f15a24]/10 focus:border-[#f15a24] transition-all appearance-none cursor-pointer"
                  style={{ backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%2394a3b8'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E")`, backgroundRepeat: 'no-repeat', backgroundPosition: 'right 1.5rem center', backgroundSize: '1.25rem' }}
                >
                  <option value="">Selecione o Sensor...</option>
                  <option value="Painel Violado">Painel Violado</option>
                  <option value="Porta Motorista">Porta Motorista</option>
                  <option value="Porta Carona">Porta Carona</option>
                  <option value="Teclado">Teclado</option>
                  <option value="Pânico">Pânico</option>
                  <option value="Desengate/Engate">Desengate/Engate</option>
                  <option value="Bloqueio">Bloqueio</option>
                  <option value="Sirene">Sirene</option>
                  <option value="Trava de Baú">Trava de Baú</option>
                  <option value="Baú Traseiro">Baú Traseiro</option>
                </select>
              </div>

              {/* Nº O.S. (Manual para Sensores) */}
              <div className="space-y-2">
                <input 
                  type="text" 
                  value={osForm.osNumber}
                  onChange={(e) => setOsForm({...osForm, osNumber: e.target.value})}
                  placeholder="Nº O.S."
                  className="w-full px-6 py-4 bg-white dark:bg-[#141414] border border-slate-200 dark:border-white/5 rounded-2xl text-base font-medium text-slate-700 dark:text-white outline-none ring-2 ring-transparent focus:ring-[#f15a24]/10 focus:border-[#f15a24] transition-all"
                />
              </div>
            </>
          ) : (
            /* Próxima OS Automática para Interna */
            <div className="p-8 bg-blue-50/50 dark:bg-blue-900/10 border border-blue-100 dark:border-blue-900/20 rounded-3xl space-y-2">
              <p className="text-[10px] font-bold text-blue-400 uppercase tracking-widest">Próxima O.S. Automática</p>
              <p className="text-4xl font-bold text-slate-800 dark:text-white">#{maintenanceOrders.length + 1}</p>
            </div>
          )}

          <div className="space-y-2">
            <textarea 
              required
              rows={4}
              value={osForm.description}
              onChange={(e) => setOsForm({...osForm, description: e.target.value})}
              placeholder="Motivo/Detalhes"
              className="w-full p-6 bg-white dark:bg-[#141414] border border-slate-200 dark:border-white/5 rounded-3xl text-base font-medium text-slate-700 dark:text-white outline-none ring-2 ring-transparent focus:ring-[#f15a24]/10 focus:border-[#f15a24] transition-all resize-none shadow-sm"
            />
          </div>

          <button 
            type="submit"
            className="w-full py-5 bg-[#f15a24] text-white rounded-2xl font-bold text-sm uppercase tracking-widest hover:bg-[#d84a1a] transition-all shadow-xl shadow-[#f15a24]/20 active:scale-95"
          >
            Registrar Manutenção
          </button>
        </form>
      </Modal>

      {/* Aba de Ordens de Serviço */}
      {activeTab === 'os' && (
        <div className="space-y-6 animate-in fade-in slide-in-from-right-4 duration-500">
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 bg-white dark:bg-[#1b1b1b] p-6 rounded-[32px] border border-slate-200 dark:border-white/5 shadow-sm">
            <h2 className="text-2xl font-bold text-slate-800 dark:text-white tracking-tighter flex items-center gap-4">
              <div className="p-3 bg-orange-500 rounded-2xl text-white shadow-lg shadow-orange-500/20">
                <AlertTriangle size={24} />
              </div>
              Gestão de <span className="text-orange-500">Manutenção</span>
            </h2>

            <div className="flex flex-wrap gap-3">
               <select 
                 value={osStatusFilter}
                 onChange={(e) => setOsStatusFilter(e.target.value)}
                 className="px-4 py-2 bg-slate-100 dark:bg-[#141414] border-none rounded-xl text-[10px] font-bold uppercase tracking-widest focus:ring-2 focus:ring-orange-500/20 outline-none"
               >
                 <option value="ALL">Todos Status</option>
                 <option value="ABERTO">Aberto</option>
                 <option value="EM_ANALISE">Em Análise</option>
                 <option value="CONCLUIDO">Concluído</option>
               </select>
            </div>
          </div>

          {filteredOS.length > 0 ? (
            <>
              {osViewMode === 'grid' && (
                <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
                  {filteredOS.map(os => (
                    <div key={os.id} className="p-6 bg-white dark:bg-[#1b1b1b] rounded-[32px] border border-slate-200 dark:border-white/5 flex flex-col justify-between hover:shadow-2xl transition-all border-l-[8px] border-l-orange-500/30 hover:border-l-orange-500 group overflow-hidden">
                      <div className="flex items-center justify-between mb-4">
                        <div>
                          <p className="text-[11px] font-bold text-slate-400 uppercase tracking-[0.2em] mb-0.5">{os.osNumber}</p>
                          <p className="text-lg font-bold text-slate-800 dark:text-white tracking-tighter group-hover:text-orange-500 transition-colors uppercase">{os.plate}</p>
                        </div>
                        <span className="px-3 py-1.5 bg-orange-500 text-white rounded-full text-[10px] font-bold uppercase tracking-widest shadow-lg shadow-orange-500/20">
                          {os.status}
                        </span>
                      </div>
                      
                      <div className="bg-slate-50 dark:bg-white/[0.02] p-4 rounded-2xl mb-4 h-24 overflow-y-auto custom-scrollbar">
                        <p className="text-xs text-slate-700 dark:text-slate-200 font-bold leading-snug italic">
                          "{os.description}"
                        </p>
                      </div>

                      <div className="flex items-center justify-between pt-4 border-t border-slate-100 dark:border-white/5">
                        <div className="flex items-center gap-2.5">
                          <div className="w-8 h-8 rounded-xl bg-[var(--gr-primary)]/10 flex items-center justify-center text-[var(--gr-primary)] font-bold text-xs">
                            {os.createdBy?.slice(0, 1)}
                          </div>
                          <div>
                            <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest leading-none mb-0.5">Operador</p>
                            <p className="text-xs font-bold text-slate-700 dark:text-slate-200">{os.createdBy}</p>
                          </div>
                        </div>
                        <div className="text-right">
                           <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-0.5">Abertura</p>
                           <p className="text-xs font-bold text-slate-600 dark:text-slate-400">{new Date(os.createdAt).toLocaleDateString('pt-BR')}</p>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {osViewMode === 'table' && (
                <div className="flex-1 min-h-[500px]">
                  <ExcelTable 
                    data={filteredOS}
                    loading={loading}
                    columns={[
                      { field: 'osNumber', header: 'O.S.', width: 120 },
                      { field: 'plate', header: 'Placa', width: 120, render: (row) => (
                        <div className="font-bold tracking-tighter uppercase">{row.plate}</div>
                      )},
                      { field: 'description', header: 'Descrição', width: 350, render: (row) => (
                        <span className="text-xs italic">"{row.description}"</span>
                      )},
                      { field: 'createdAt', header: 'Data', width: 120, render: (row) => (
                        <span>{new Date(row.createdAt).toLocaleDateString('pt-BR')}</span>
                      )},
                      { field: 'status', header: 'Status', width: 120, render: (row) => (
                        <span className="px-3 py-1 bg-orange-500 text-white rounded-full text-[10px] font-bold uppercase tracking-widest shadow-lg shadow-orange-500/20">
                          {row.status}
                        </span>
                      )}
                    ]}
                    pageSize={10}
                    hideActions
                  />
                </div>
              )}

              {osViewMode === 'kanban' && (
                <div className="h-[600px] flex gap-4 w-full">
                  <GrKanbanBoard 
                    userRole={userRole}
                    columns={[
                      { 
                        id: 'ABERTO', 
                        title: 'Aberto', 
                        color: 'orange', 
                        cards: filteredOS.filter(o => o.status === 'ABERTO').map(o => ({
                          id: o.id,
                          title: o.plate,
                          subtitle: o.osNumber,
                          date: new Date(o.createdAt).toLocaleDateString('pt-BR'),
                          details: [{ label: 'Operador', value: o.createdBy }],
                          status: o.status
                        }))
                      },
                      { 
                        id: 'EM_ANALISE', 
                        title: 'Em Análise', 
                        color: 'blue', 
                        cards: filteredOS.filter(o => o.status === 'EM_ANALISE').map(o => ({
                          id: o.id,
                          title: o.plate,
                          subtitle: o.osNumber,
                          date: new Date(o.createdAt).toLocaleDateString('pt-BR'),
                          details: [{ label: 'Operador', value: o.createdBy }],
                          status: o.status
                        }))
                      },
                      { 
                        id: 'CONCLUIDO', 
                        title: 'Concluído', 
                        color: 'emerald', 
                        cards: filteredOS.filter(o => o.status === 'CONCLUIDO').map(o => ({
                          id: o.id,
                          title: o.plate,
                          subtitle: o.osNumber,
                          date: new Date(o.createdAt).toLocaleDateString('pt-BR'),
                          details: [{ label: 'Operador', value: o.createdBy }],
                          status: o.status
                        }))
                      }
                    ]}
                  />
                </div>
              )}
            </>
          ) : (
            <div className="py-32 text-center bg-white dark:bg-[#1b1b1b] rounded-[48px] border-2 border-dashed border-slate-200 dark:border-white/5">
               <div className="p-6 bg-slate-50 dark:bg-white/5 rounded-full w-fit mx-auto mb-6">
                 <Search size={48} className="text-slate-200" />
               </div>
               <p className="text-sm font-black text-slate-400 uppercase tracking-[0.3em]">Nenhuma Ordem de Serviço encontrada</p>
            </div>
          )}
        </div>
      )}
      {/* Modal Novo Veículo */}
      <VehicleFormModal 
        isOpen={isVehicleModalOpen} 
        onClose={() => setIsVehicleModalOpen(false)} 
        onSave={async (newVehicle) => {
          // Logic to save new vehicle if service allows
          // For now, just a toast as the mock/hooks might not support it yet
          console.log("Saving new vehicle:", newVehicle);
          alert("Veículo cadastrado com sucesso! (Simulado)");
          setIsVehicleModalOpen(false);
          refresh();
        }} 
      />
    </div>
  );
};

export default GrChecklistView;
