import React, { useEffect, useState, useMemo } from 'react';
import { useVehicles } from '../../prafrot/hooks/useVehicles';
import { useFleetLists } from '../../prafrot/hooks/useFleetLists';
import { useDrivers } from '../../prafrot/hooks/useDrivers';
import ExcelTable from '../../prafrot/components/ExcelTable';
import { Plus, Search, Truck, CheckCircle, Edit2, Trash2 } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { toast } from 'sonner';
import { prafrotStatisticsService } from '../../prafrot/services/prafrotStatisticsService';

const GrVehiclesSimplified = () => {
  const { vehicles, loading, fetchVehicles, createVehicle, updateVehicle, deleteVehicle } = useVehicles();
  const { fetchListsConfig } = useFleetLists();
  const { drivers, fetchDrivers } = useDrivers();
  const [searchTerm, setSearchTerm] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingVehicle, setEditingVehicle] = useState(null);
  const [statusStats, setStatusStats] = useState([]);

  const initialFormState = {
    ano_fabricacao: '', ano_modelo: '', atuacao: '', base: '', categoria: 'Passeio',
    chassi: '', cnpj: '', combustivel: 'Gasolina', contrato: '', coordenador: '', 
    cor: '', data_limite: '', dispatcher: '', fabricante: '', fiscal_operacao: '',
    geotab: 'NÃO', gestor: '', golfleet: 'NÃO', idveiculo_frota: '', modelo: '',
    placa: '', pooltrack: 'NÃO', primeira_locacao: '', proprietario: '',
    renavam: '', sascar: 'NÃO', t4s: 'NÃO', tipo_de_placa: '', tipo_frota: '',
    uf: '', valor_aluguel: '', valor_fipe: '',
    situacao: 'ATIVO', km_atual: '', observacoes: '', empresa: '', financiamento: '', 
    locadora: '', motorista_atual: ''
  };
  const [formData, setFormData] = useState(initialFormState);

  useEffect(() => {
    fetchVehicles();
    fetchDrivers();
    fetchListsConfig();
    
    prafrotStatisticsService.getPlacasPorStatus().then(data => {
      if (Array.isArray(data)) setStatusStats(data);
    });
  }, []);

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

  const handleOpenModal = (vehicle = null) => {
    if (vehicle) {
      setEditingVehicle(vehicle);
      setFormData({
        ...initialFormState,
        ...vehicle,
        tipo_placa: vehicle.tipo_de_placa || vehicle.tipo_placa || '',
        data_aquisicao: vehicle.data_aquisicao?.split('T')[0] || '',
        data_venda: vehicle.data_venda?.split('T')[0] || '',
        data_limite: vehicle.data_limite?.split('T')[0] || '',
        primeira_locacao: vehicle.primeira_locacao?.split('T')[0] || '',
        situacao: vehicle.situacao || vehicle.status_frota || 'ATIVO',
      });
    } else {
      setEditingVehicle(null);
      setFormData(initialFormState);
    }
    setIsModalOpen(true);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (!formData.placa || !formData.modelo || !formData.fabricante) {
      toast.error('Preencha os campos obrigatórios: Placa, Modelo e Fabricante');
      return;
    }

    const payload = { ...formData, tipo_de_placa: formData.tipo_placa };
    delete payload.motorista_atual;
    delete payload.empresa;
    delete payload.locadora;
    delete payload.km_atual;
    delete payload.data_venda;
    delete payload.valor_venda;
    delete payload.situacao;

    let success;
    if (editingVehicle) {
      success = await updateVehicle(editingVehicle.idveiculo_frota, payload);
    } else {
      success = await createVehicle(payload);
    }

    if (success) setIsModalOpen(false);
  };

  const filteredVehicles = useMemo(() => Array.isArray(vehicles) ? vehicles.filter(v => 
    v.placa?.toLowerCase().includes(searchTerm.toLowerCase()) || 
    v.modelo?.toLowerCase().includes(searchTerm.toLowerCase())
  ) : [], [vehicles, searchTerm]);

  return (
    <div className="space-y-6">
      {/* Search and New Button */}
      <div className="flex items-center gap-3 justify-end">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" size={18} />
          <input 
            className="w-full pl-12 pr-4 py-3 bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-white/5 rounded-[20px] text-sm font-medium text-slate-700 dark:text-slate-200 focus:outline-none focus:ring-4 focus:ring-[var(--gr-primary)]/10 focus:border-[var(--gr-primary)] transition-all placeholder:text-slate-400"
            placeholder="Buscar veículo por placa ou modelo..." 
            value={searchTerm}
            onChange={e => setSearchTerm(e.target.value)}
          />
        </div>
        <button 
          onClick={() => handleOpenModal()}
          className="flex items-center gap-2 px-6 py-3 bg-[var(--gr-primary)] hover:bg-[var(--gr-primary-dark)] text-white rounded-[20px] font-bold text-xs uppercase tracking-widest transition-all shadow-lg shadow-[var(--gr-primary)]/20 hover:scale-[1.02] active:scale-95"
        >
          <Plus size={18} /> Novo Veículo
        </button>
      </div>

      {/* Status Cards */}
      <div className="grid grid-cols-2 gap-6">
        <div className="bg-white dark:bg-[#1b1b1b] border border-slate-200 dark:border-white/5 rounded-[28px] p-6 shadow-sm hover:shadow-xl transition-all">
          <div className="flex items-center gap-4">
            <div className="p-4 bg-blue-500/10 rounded-[20px] text-blue-600">
              <Truck size={28} />
            </div>
            <div className="flex flex-col">
              <span className="text-[10px] font-bold uppercase tracking-[0.2em] text-slate-400">Veículos Alugados</span>
              <div className="text-4xl font-bold text-slate-800 dark:text-white mt-1">
                {getStatusData('Veículo Alugado')?.total || 0}
              </div>
            </div>
          </div>
        </div>
        <div className="bg-white dark:bg-[#1b1b1b] border border-slate-200 dark:border-white/5 rounded-[28px] p-6 shadow-sm hover:shadow-xl transition-all">
          <div className="flex items-center gap-4">
            <div className="p-4 bg-[var(--gr-primary)]/10 rounded-[20px] text-[var(--gr-primary)]">
              <CheckCircle size={28} />
            </div>
            <div className="flex flex-col">
              <span className="text-[10px] font-bold uppercase tracking-[0.2em] text-slate-400">Em Operação</span>
              <div className="text-4xl font-bold text-slate-800 dark:text-white mt-1">
                {getStatusData('Em Operação')?.total || 0}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Vehicles Table */}
      <div className="h-[600px] w-full max-w-full overflow-hidden min-w-0">
        <ExcelTable 
          data={filteredVehicles} 
          loading={loading}
          columns={[
            { header: 'ID', field: 'idveiculo_frota', width: '80px' },
            { header: 'PLACA', field: 'placa', width: '100px', className: 'font-mono font-bold text-[var(--gr-primary)]' },
            { header: 'MODELO', field: 'modelo', width: '180px' },
            { header: 'FABRICANTE', field: 'fabricante', width: '140px' },
            { header: 'ANO', field: 'ano_modelo', width: '80px' },
            { header: 'BASE', field: 'base', width: '120px' },
            { header: 'CATEGORIA', field: 'categoria', width: '120px' },
            { header: 'STATUS', field: 'status_frota', width: '140px' },
          ]}
          onEdit={handleOpenModal}
          onDelete={(vehicle) => {
            if (window.confirm(`Deseja realmente excluir o veículo ${vehicle.placa}?`)) {
              deleteVehicle(vehicle.idveiculo_frota);
            }
          }}
        />
      </div>

      {/* Vehicle Form Modal */}
      <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto bg-white dark:bg-[#1b1b1b]">
          <DialogHeader>
            <DialogTitle className="text-2xl font-bold text-slate-800 dark:text-white">
              {editingVehicle ? 'Editar Veículo' : 'Novo Veículo'}
            </DialogTitle>
          </DialogHeader>
          <form onSubmit={handleSubmit} className="space-y-6">
            <div className="grid 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">Placa *</label>
                <input 
                  value={formData.placa}
                  onChange={e => setFormData({...formData, placa: e.target.value})}
                  className="w-full bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-white/5 rounded-xl px-3 py-2 text-sm text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)] focus:ring-1 focus:ring-[var(--gr-primary)] transition-all"
                  placeholder="ABC-1234"
                />
              </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">Modelo *</label>
                <input 
                  value={formData.modelo}
                  onChange={e => setFormData({...formData, modelo: e.target.value})}
                  className="w-full bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-white/5 rounded-xl px-3 py-2 text-sm text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)] focus:ring-1 focus:ring-[var(--gr-primary)] transition-all"
                />
              </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">Fabricante *</label>
                <input 
                  value={formData.fabricante}
                  onChange={e => setFormData({...formData, fabricante: e.target.value})}
                  className="w-full bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-white/5 rounded-xl px-3 py-2 text-sm text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)] focus:ring-1 focus:ring-[var(--gr-primary)] transition-all"
                />
              </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">Ano Modelo</label>
                <input 
                  value={formData.ano_modelo}
                  onChange={e => setFormData({...formData, ano_modelo: e.target.value})}
                  className="w-full bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-white/5 rounded-xl px-3 py-2 text-sm text-slate-700 dark:text-slate-200 focus:outline-none focus:border-[var(--gr-primary)] focus:ring-1 focus:ring-[var(--gr-primary)] transition-all"
                />
              </div>
            </div>
            <DialogFooter>
              <button 
                type="button"
                onClick={() => setIsModalOpen(false)}
                className="px-6 py-2 bg-slate-100 dark:bg-[#2a2a2a] hover:bg-slate-200 dark:hover:bg-[#333] text-slate-700 dark:text-slate-200 rounded-xl font-bold text-sm transition-all"
              >
                Cancelar
              </button>
              <button 
                type="submit"
                className="px-6 py-2 bg-[var(--gr-primary)] hover:bg-[var(--gr-primary-dark)] text-white rounded-xl font-bold text-sm transition-all shadow-lg"
              >
                {editingVehicle ? 'Atualizar' : 'Criar'}
              </button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default GrVehiclesSimplified;
