import React, { useEffect, useState } from 'react';
import { useClaims } from '../hooks/useClaims';
import { useVehicles } from '../hooks/useVehicles';
import { 
  FileWarning, Search, Filter, Plus, Pencil, Trash2,
  AlertTriangle, RotateCcw, DollarSign, Calendar,
  User, MapPin, Truck, ShieldAlert, FileText, CheckCircle2
} from 'lucide-react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { motion } from 'framer-motion';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';

export const ClaimsView = () => {
    const { claims, loading, fetchClaims, createClaim, updateClaim } = useClaims();
    const { vehicles, fetchVehicles } = useVehicles();
    const [searchTerm, setSearchTerm] = useState('');
    
    // Modal State
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingClaim, setEditingClaim] = useState(null);
    
    // Form State com todos os 40+ campos
    const [formData, setFormData] = useState({
        // Evento Base
        tipo_placa: '', 
        placa: '',
        status: 'Desmobilizado', // Default do JSON exemplo
        obs: '',
        data_entrada: '', // Data do evento/entrada
        previsao: '',
        dias_parado: '',
        agendamento: '', // Campo específico

        // Veículo Detalhes
        chassi: '',
        renavan: '',
        fabricante: '',
        modelo: '',
        ano_fabricacao: '',
        ano_modelo: '',
        cor: '',
        combustivel: '',
        categoria: '', // Categoria: Utilitário etc
        tipo_frota: '', // Locação etc

        // Operacional / Rota
        id_rota: '',
        motorista: '',
        base: '',
        uf: '',
        atuacao: '',
        
        // Responsáveis
        dispatcher: '',
        coordenador: '',
        gestor: '',
        fiscal_operacao: '',
        proprietario: '',
        contrato: '',

        // Financeiro / Datas Contrato
        primeira_locacao: '',
        data_limite: '',
        valor_aluguel: '',
        valor_fipe: '',

        // Preventiva / Km
        km_preventiva: '',
        km_atual: '',
        ultima_preventiva: '',
        prox_preventiva: '',
        
        // Rastreadores e Flags
        melifleet: 'No',
        geotab: 'NÃO',
        sascar: 'NÃO',
        pooltrack: 'NÃO',
        t4s: 'NÃO',
        cmou: '',
        d: '', // d_col
        u: ''  // u_col
    });

    useEffect(() => {
        fetchClaims();
        fetchVehicles();
    }, [fetchClaims, fetchVehicles]);

    const handleOpenModal = (claim = null) => {
        if (claim) {
            setEditingClaim(claim);
            // Mapeamento direto de todos os campos
            setFormData({
                tipo_placa: claim.tipo_placa || '',
                placa: claim.placa || '',
                status: claim.status || 'Desmobilizado',
                obs: claim.obs || '',
                data_entrada: claim.data_entrada ? claim.data_entrada.split(' ')[0] : '',
                previsao: claim.previsao ? claim.previsao.split(' ')[0] : '',
                dias_parado: claim.dias_parado || '',
                agendamento: claim.agendamento || '',
                
                chassi: claim.chassi || '',
                renavan: claim.renavan || '',
                fabricante: claim.fabricante || '',
                modelo: claim.modelo || '',
                ano_fabricacao: claim.ano_fabricacao || '',
                ano_modelo: claim.ano_modelo || '',
                cor: claim.cor || '',
                combustivel: claim.combustivel || '',
                categoria: claim.categoria || '',
                tipo_frota: claim.tipo_frota || '',
                
                id_rota: claim.id_rota || '',
                motorista: claim.motorista || '',
                base: claim.base || '',
                uf: claim.uf || '',
                atuacao: claim.atuacao || '',
                
                dispatcher: claim.dispatcher || '',
                coordenador: claim.coordenador || '',
                gestor: claim.gestor || '',
                fiscal_operacao: claim.fiscal_operacao || '',
                proprietario: claim.proprietario || '',
                contrato: claim.contrato ? claim.contrato.split(' ')[0] : '',
                
                primeira_locacao: claim.primeira_locacao ? claim.primeira_locacao.split(' ')[0] : '',
                data_limite: claim.data_limite || '',
                valor_aluguel: claim.valor_aluguel || '',
                valor_fipe: claim.valor_fipe || '',
                
                km_preventiva: claim.km_preventiva || '',
                km_atual: claim.km_atual || '',
                ultima_preventiva: claim.ultima_preventiva || '',
                prox_preventiva: claim.prox_preventiva || '',
                
                melifleet: claim.melifleet || 'No',
                geotab: claim.geotab || 'NÃO',
                sascar: claim.sascar || 'NÃO',
                pooltrack: claim.pooltrack || 'NÃO',
                t4s: claim.t4s || 'NÃO',
                cmou: claim.cmou || '',
                d: claim.d || '',
                u: claim.u || ''
            });
        } else {
            setEditingClaim(null);
            // Limpar form - default values
            setFormData({
                tipo_placa: '', placa: '', status: 'Desmobilizado', obs: '',
                data_entrada: new Date().toISOString().split('T')[0], previsao: '', dias_parado: '', agendamento: '',
                chassi: '', renavan: '', fabricante: '', modelo: '', ano_fabricacao: '', ano_modelo: '', cor: '', combustivel: '', categoria: '', tipo_frota: '',
                id_rota: '', motorista: '', base: '', uf: '', atuacao: '',
                dispatcher: '', coordenador: '', gestor: '', fiscal_operacao: '', proprietario: '', contrato: '',
                primeira_locacao: '', data_limite: '', valor_aluguel: '', valor_fipe: '',
                km_preventiva: '', km_atual: '', ultima_preventiva: '', prox_preventiva: '',
                melifleet: 'No', geotab: 'NÃO', sascar: 'NÃO', pooltrack: 'NÃO', t4s: 'NÃO', cmou: '', d: '', u: ''
            });
        }
        setIsModalOpen(true);
    };

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

    // Auto-fill ao selecionar placa
    const handleVehicleSelect = (placa) => {
        const vehicle = vehicles.find(v => v.placa === placa);
        if (vehicle) {
            setFormData(prev => ({
                ...prev,
                placa: vehicle.placa,
                chassi: vehicle.chassi || prev.chassi,
                renavan: vehicle.renavam || prev.renavan,
                modelo: vehicle.modelo || prev.modelo,
                fabricante: vehicle.fabricante || prev.fabricante,
                cor: vehicle.cor || prev.cor,
                ano_fabricacao: vehicle.ano_fabricacao || prev.ano_fabricacao,
                ano_modelo: vehicle.ano_modelo || prev.ano_modelo,
                categoria: vehicle.categoria || prev.categoria,
                base: vehicle.base || prev.base,
                uf: vehicle.uf || prev.uf,
                gestor: vehicle.gestor || prev.gestor,
                proprietario: vehicle.proprietario || prev.proprietario
            }));
        } else {
            setFormData(prev => ({ ...prev, placa }));
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        let success;
        // Payload já está mapeado em formData 1:1 com o esperado
        if (editingClaim) {
            // Usa idsinistro_devolucao_frota
            success = await updateClaim(editingClaim.idsinistro_devolucao_frota, formData);
        } else {
            success = await createClaim(formData);
        }
        if (success) setIsModalOpen(false);
    };

    const filteredClaims = claims.filter(c => 
        (c.placa || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
        (c.modelo || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
        (c.obs || '').toLowerCase().includes(searchTerm.toLowerCase())
    );

    return (
        <div className="space-y-6 pb-20">
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                <div className="space-y-1">
                    <h2 className="text-3xl font-black tracking-tight text-slate-900">Sinistros & Desmobilização</h2>
                    <p className="text-slate-500 font-medium font-inter">Gestão de ocorrências, devoluções de ativos e vendas.</p>
                </div>
                <div className="flex items-center gap-3">
                    <Button variant="outline" className="gap-2 h-10 font-bold text-slate-700 border-slate-200">
                        <Filter size={16} /> Filtros
                    </Button>
                    <Button 
                        className="gap-2 h-10 font-bold bg-rose-600 hover:bg-rose-700 text-white shadow-lg shadow-rose-600/20"
                        onClick={() => handleOpenModal()}
                    >
                        <Plus size={18} /> Nova Ocorrência
                    </Button>
                </div>
            </div>

            {/* KPI Cards */}
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                <Card className="border-slate-200 shadow-sm bg-white">
                    <CardContent className="p-5 flex items-center gap-4">
                         <div className="w-10 h-10 bg-rose-100 rounded-lg flex items-center justify-center text-rose-600">
                             <ShieldAlert size={20} />
                         </div>
                         <div>
                             <p className="text-2xl font-bold text-slate-900">{claims.filter(c => c.status === 'Sinistrado').length}</p>
                             <p className="text-[10px] uppercase font-bold text-slate-400">Sinistros Ativos</p>
                         </div>
                    </CardContent>
                </Card>
                <Card className="border-slate-200 shadow-sm bg-white">
                    <CardContent className="p-5 flex items-center gap-4">
                         <div className="w-10 h-10 bg-slate-100 rounded-lg flex items-center justify-center text-slate-600">
                             <RotateCcw size={20} />
                         </div>
                         <div>
                             <p className="text-2xl font-bold text-slate-900">{claims.filter(c => c.status === 'Desmobilizado').length}</p>
                             <p className="text-[10px] uppercase font-bold text-slate-400">Desmobilizados</p>
                         </div>
                    </CardContent>
                </Card>
            </div>

            <Card className="border border-slate-200 shadow-sm overflow-hidden bg-white">
                <CardHeader className="bg-slate-50/50 border-b border-slate-100 px-6 py-4 flex flex-row items-center justify-between">
                    <div className="relative flex-1 max-w-md">
                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" size={18} />
                        <Input 
                            placeholder="Buscar por placa, modelo ou status..." 
                            className="pl-10 h-10 bg-white border-slate-200 text-slate-900 focus:ring-emerald-500 font-medium"
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                        />
                    </div>
                </CardHeader>
                <div className="overflow-x-auto">
                    {loading ? <div className="p-8 text-center text-slate-500">Carregando dados...</div> : (
                    <table className="w-full text-left border-collapse min-w-[1000px] text-sm">
                        <thead className="bg-slate-50 font-bold text-xs uppercase text-slate-500 tracking-wider">
                            <tr>
                                 <th className="px-6 py-4 border-b border-slate-100">Ocorrência</th>
                                 <th className="px-6 py-4 border-b border-slate-100">Veículo</th>
                                 <th className="px-6 py-4 border-b border-slate-100">Operacional</th>
                                 <th className="px-6 py-4 border-b border-slate-100">ID Rota</th>
                                 <th className="px-6 py-4 border-b border-slate-100">Agendamento</th>
                                 <th className="px-6 py-4 border-b border-slate-100">Status</th>
                                 <th className="px-6 py-4 border-b border-slate-100 text-right">Ações</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100">
                            {filteredClaims.map((c) => (
                                <tr key={c.idsinistro_devolucao_frota || Math.random()} className="hover:bg-slate-50/50 transition-colors">
                                    <td className="px-6 py-4 align-top">
                                        <div className="flex flex-col">
                                            <span className="font-bold text-slate-800">{c.obs ? c.obs.substring(0, 30) + '...' : 'Sem descrição'}</span>
                                            <span className="text-[10px] font-bold text-slate-400 mt-1 uppercase">Entrada: {c.data_entrada ? new Date(c.data_entrada).toLocaleDateString('pt-BR') : '-'}</span>
                                        </div>
                                    </td>
                                    <td className="px-6 py-4 align-top">
                                        <div className="flex flex-col">
                                            <span className="font-mono font-bold text-emerald-950">{c.placa}</span>
                                            <span className="text-xs text-slate-500">{c.modelo}</span>
                                        </div>
                                    </td>
                                    <td className="px-6 py-4 align-top">
                                        <div className="flex flex-col text-xs text-slate-500">
                                            <div className="flex items-center gap-1"><MapPin size={10} /> {c.base} - {c.uf}</div>
                                            <div className="flex items-center gap-1"><User size={10} /> {c.motorista || 'Sem Motorista'}</div>
                                        </div>
                                    </td>
                                     <td className="px-6 py-4 align-top">
                                         <Badge variant="outline" className="bg-slate-50 text-slate-600 border-slate-200 text-[10px] font-bold">
                                             {c.id_rota || '-'}
                                         </Badge>
                                     </td>
                                     <td className="px-6 py-4 align-top">
                                         <div className="text-xs text-slate-500 font-medium">
                                             {c.agendamento || '-'}
                                         </div>
                                     </td>
                                     <td className="px-6 py-4 align-top">
                                          <Badge variant="outline" className={cn("text-[10px] font-bold uppercase", 
                                             c.status === 'Desmobilizado' ? 'bg-slate-100 text-slate-600 border-slate-200' :
                                             'bg-rose-50 text-rose-600 border-rose-200'
                                          )}>
                                              {c.status}
                                          </Badge>
                                     </td>
                                    <td className="px-6 py-4 align-top text-right">
                                        <Button variant="ghost" size="icon" onClick={() => handleOpenModal(c)} className="text-slate-400 hover:text-emerald-600">
                                            <Pencil size={16} />
                                        </Button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                    )}
                </div>
            </Card>

             {/* MODAL COMPLEXO - 40+ CAMPOS */}
             <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
                <DialogContent className="sm:max-w-[900px] h-[90vh] flex flex-col p-0 gap-0 bg-white overflow-hidden">
                    <DialogHeader className="px-6 py-4 border-b border-slate-100 bg-slate-50/50">
                        <DialogTitle className="text-xl font-bold text-slate-900">
                            {editingClaim ? `Editar Registro #${editingClaim.idsinistro_devolucao_frota}` : 'Nova Ocorrência / Devolução'}
                        </DialogTitle>
                        <DialogDescription>
                            Preencha todos os detalhes operacionais e preventivos.
                        </DialogDescription>
                    </DialogHeader>

                    <form onSubmit={handleSubmit} className="flex-1 overflow-y-auto">
                        <Tabs defaultValue="evento" className="w-full">
                            <div className="px-6 pt-4 bg-white sticky top-0 z-10 border-b border-slate-100 pb-4">
                                <TabsList className="grid w-full grid-cols-5 bg-slate-100 p-1 rounded-lg">
                                    <TabsTrigger value="evento" className="font-bold text-[10px] uppercase">Evento</TabsTrigger>
                                    <TabsTrigger value="veiculo" className="font-bold text-[10px] uppercase">Veículo</TabsTrigger>
                                    <TabsTrigger value="operacional" className="font-bold text-[10px] uppercase">Operacional</TabsTrigger>
                                    <TabsTrigger value="financeiro" className="font-bold text-[10px] uppercase">Financeiro</TabsTrigger>
                                    <TabsTrigger value="rastreadores" className="font-bold text-[10px] uppercase">Rastreadores</TabsTrigger>
                                </TabsList>
                            </div>

                            <div className="p-6">
                                {/* ABA EVENTO */}
                                <TabsContent value="evento" className="space-y-4 m-0">
                                    <div className="grid grid-cols-3 gap-4">
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Placa Alvo</Label>
                                            <div className="flex gap-2">
                                                <Input value={formData.placa} onChange={e => handleInputChange('placa', e.target.value)} placeholder="ABC-1234" className="font-mono font-bold" />
                                                <Button type="button" size="icon" variant="outline" onClick={() => handleVehicleSelect(formData.placa)} title="Buscar dados"><Search size={14} /></Button>
                                            </div>
                                         </div>
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Status</Label>
                                            <Input value={formData.status} onChange={e => handleInputChange('status', e.target.value)} placeholder="Ex: Desmobilizado" />
                                         </div>
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Data Entrada</Label>
                                            <Input type="date" value={formData.data_entrada} onChange={e => handleInputChange('data_entrada', e.target.value)} />
                                         </div>
                                    </div>
                                    <div className="grid grid-cols-3 gap-4">
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Previsão</Label>
                                            <Input type="date" value={formData.previsao} onChange={e => handleInputChange('previsao', e.target.value)} />
                                         </div>
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Dias Parado</Label>
                                            <Input value={formData.dias_parado} onChange={e => handleInputChange('dias_parado', e.target.value)} />
                                         </div>
                                          <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Agendamento</Label>
                                            <Input value={formData.agendamento} onChange={e => handleInputChange('agendamento', e.target.value)} />
                                         </div>
                                    </div>
                                    <div className="space-y-1.5">
                                         <Label className="text-xs font-bold text-slate-500 uppercase">Observações (Descrição)</Label>
                                         <Textarea value={formData.obs} onChange={e => handleInputChange('obs', e.target.value)} className="min-h-[100px]" />
                                    </div>
                                </TabsContent>

                                {/* ABA VEICULO */}
                                <TabsContent value="veiculo" className="space-y-4 m-0">
                                    <div className="grid grid-cols-3 gap-4">
                                        <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Chassi</Label>
                                            <Input value={formData.chassi} onChange={e => handleInputChange('chassi', e.target.value)} />
                                        </div>
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Renavam</Label>
                                            <Input value={formData.renavan} onChange={e => handleInputChange('renavan', e.target.value)} />
                                        </div>
                                        <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Modelo</Label>
                                            <Input value={formData.modelo} onChange={e => handleInputChange('modelo', e.target.value)} />
                                        </div>
                                    </div>
                                    <div className="grid grid-cols-3 gap-4">
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Fabricante</Label>
                                            <Input value={formData.fabricante} onChange={e => handleInputChange('fabricante', e.target.value)} />
                                        </div>
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Cor</Label>
                                            <Input value={formData.cor} onChange={e => handleInputChange('cor', e.target.value)} />
                                        </div>
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Combustível</Label>
                                            <Input value={formData.combustivel} onChange={e => handleInputChange('combustivel', e.target.value)} />
                                        </div>
                                    </div>
                                    <div className="grid grid-cols-3 gap-4">
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Ano Fab.</Label>
                                            <Input value={formData.ano_fabricacao} onChange={e => handleInputChange('ano_fabricacao', e.target.value)} />
                                        </div>
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Ano Mod.</Label>
                                            <Input value={formData.ano_modelo} onChange={e => handleInputChange('ano_modelo', e.target.value)} />
                                        </div>
                                        <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Categoria</Label>
                                            <Input value={formData.categoria} onChange={e => handleInputChange('categoria', e.target.value)} />
                                        </div>
                                    </div>
                                </TabsContent>

                                {/* ABA OPERACIONAL */}
                                <TabsContent value="operacional" className="space-y-4 m-0">
                                     <div className="grid grid-cols-3 gap-4">
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Base</Label>
                                            <Input value={formData.base} onChange={e => handleInputChange('base', e.target.value)} />
                                        </div>
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">UF</Label>
                                            <Input value={formData.uf} onChange={e => handleInputChange('uf', e.target.value)} maxLength={2} />
                                        </div>
                                        <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Proprietário</Label>
                                            <Input value={formData.proprietario} onChange={e => handleInputChange('proprietario', e.target.value)} />
                                        </div>
                                    </div>
                                    <div className="grid grid-cols-2 gap-4">
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Motorista</Label>
                                            <Input value={formData.motorista} onChange={e => handleInputChange('motorista', e.target.value)} />
                                        </div>
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">ID Rota</Label>
                                            <Input value={formData.id_rota} onChange={e => handleInputChange('id_rota', e.target.value)} />
                                        </div>
                                    </div>

                                    <div className="grid grid-cols-2 gap-4 border-t border-slate-100 pt-4">
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Gestor</Label>
                                            <Input value={formData.gestor} onChange={e => handleInputChange('gestor', e.target.value)} />
                                        </div>
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Coordenador</Label>
                                            <Input value={formData.coordenador} onChange={e => handleInputChange('coordenador', e.target.value)} />
                                        </div>
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Dispatcher</Label>
                                            <Input value={formData.dispatcher} onChange={e => handleInputChange('dispatcher', e.target.value)} />
                                        </div>
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Fiscal Op.</Label>
                                            <Input value={formData.fiscal_operacao} onChange={e => handleInputChange('fiscal_operacao', e.target.value)} />
                                        </div>
                                    </div>
                                    <div className="space-y-1.5 pt-2">
                                        <Label className="text-xs font-bold text-slate-500 uppercase">Atuação</Label>
                                        <Input value={formData.atuacao} onChange={e => handleInputChange('atuacao', e.target.value)} />
                                    </div>
                                </TabsContent>

                                {/* ABA FINANCEIRO */}
                                <TabsContent value="financeiro" className="space-y-4 m-0">
                                    <div className="grid grid-cols-2 gap-4">
                                        <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Contrato</Label>
                                            <Input type="date" value={formData.contrato} onChange={e => handleInputChange('contrato', e.target.value)} />
                                        </div>
                                        <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">1ª Locação</Label>
                                            <Input type="date" value={formData.primeira_locacao} onChange={e => handleInputChange('primeira_locacao', e.target.value)} />
                                        </div>
                                        <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Data Limite</Label>
                                            <Input type="date" value={formData.data_limite} onChange={e => handleInputChange('data_limite', e.target.value)} />
                                        </div>
                                    </div>
                                    <div className="grid grid-cols-2 gap-4 border-t border-slate-100 pt-4">
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Valor Aluguel</Label>
                                            <Input value={formData.valor_aluguel} onChange={e => handleInputChange('valor_aluguel', e.target.value)} />
                                        </div>
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Valor FIPE</Label>
                                            <Input value={formData.valor_fipe} onChange={e => handleInputChange('valor_fipe', e.target.value)} />
                                        </div>
                                    </div>
                                    <div className="grid grid-cols-2 gap-4 border-t border-slate-100 pt-4">
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Km Preventiva</Label>
                                            <Input value={formData.km_preventiva} onChange={e => handleInputChange('km_preventiva', e.target.value)} />
                                        </div>
                                        <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Km Atual</Label>
                                            <Input value={formData.km_atual} onChange={e => handleInputChange('km_atual', e.target.value)} />
                                        </div>
                                        <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Última Prev.</Label>
                                            <Input value={formData.ultima_preventiva} onChange={e => handleInputChange('ultima_preventiva', e.target.value)} />
                                        </div>
                                        <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">Prox. Prev.</Label>
                                            <Input value={formData.prox_preventiva} onChange={e => handleInputChange('prox_preventiva', e.target.value)} />
                                        </div>
                                    </div>
                                </TabsContent>

                                {/* ABA RASTREADORES */}
                                <TabsContent value="rastreadores" className="space-y-4 m-0">
                                     <div className="grid grid-cols-3 gap-4 bg-slate-50 p-4 rounded-lg">
                                        {['geotab', 'sascar', 'pooltrack', 't4s'].map(tracker => (
                                            <div key={tracker} className="space-y-1.5">
                                                <Label className="text-xs font-bold text-slate-500 uppercase">{tracker}</Label>
                                                <Select value={formData[tracker]} onValueChange={v => handleInputChange(tracker, v)}>
                                                    <SelectTrigger className="bg-white"><SelectValue /></SelectTrigger>
                                                    <SelectContent>
                                                        <SelectItem value="SIM">SIM</SelectItem>
                                                        <SelectItem value="NÃO">NÃO</SelectItem>
                                                    </SelectContent>
                                                </Select>
                                            </div>
                                        ))}
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">MeliFleet</Label>
                                             <Select value={formData.melifleet} onValueChange={v => handleInputChange('melifleet', v)}>
                                                    <SelectTrigger className="bg-white"><SelectValue /></SelectTrigger>
                                                    <SelectContent>
                                                        <SelectItem value="Yes">Yes</SelectItem>
                                                        <SelectItem value="No">No</SelectItem>
                                                    </SelectContent>
                                                </Select>
                                        </div>
                                     </div>
                                     <div className="grid grid-cols-3 gap-4 pt-4">
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">CMOU</Label>
                                            <Input value={formData.cmou} onChange={e => handleInputChange('cmou', e.target.value)} />
                                        </div>
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">D (Col)</Label>
                                            <Input value={formData.d} onChange={e => handleInputChange('d', e.target.value)} />
                                        </div>
                                         <div className="space-y-1.5">
                                            <Label className="text-xs font-bold text-slate-500 uppercase">U (Col)</Label>
                                            <Input value={formData.u} onChange={e => handleInputChange('u', e.target.value)} />
                                        </div>
                                     </div>
                                </TabsContent>
                            </div>
                        
                            <DialogFooter className="px-6 py-4 border-t border-slate-100 bg-slate-50/50">
                                <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>Cancelar</Button>
                                <Button type="submit" className="bg-rose-600 hover:bg-rose-700 text-white font-bold">Salvar Dados</Button>
                            </DialogFooter>
                        </Tabs>
                    </form>
                </DialogContent>
             </Dialog>
        </div>
    );
};
