import React, { useEffect, useState, useMemo } from 'react';
import { useMonitoring } from '../hooks/useMonitoring';
import { useVehicles } from '../hooks/useVehicles';
import { useDrivers } from '../hooks/useDrivers';
import AutocompleteInput from '../components/AutocompleteInput';
import ExcelTable from '../components/ExcelTable';
import { Plus, Search } from 'lucide-react';
import { 
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription 
} from "@/components/ui/dialog";

// Reusing styled components locally
const DarkInput = ({ label, ...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 
      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-emerald-500 focus:ring-1 focus:ring-emerald-500 transition-all placeholder:text-slate-400 dark:placeholder:text-slate-700"
      {...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-emerald-500 focus:ring-1 focus:ring-emerald-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-emerald-600 hover:bg-emerald-500 text-white shadow-emerald-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>
  );
};

export default function MonitoringView() {
  const { monitorings, loading, fetchMonitoring, createMonitoring, updateMonitoring } = useMonitoring();
  const [searchTerm, setSearchTerm] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingItem, setEditingItem] = useState(null);

  const initialFormState = {
    data_carga: '', id_externo: '', idmonitoramento_frota: '', motorista: '',
    placa: '', unidade: '', obs: ''
  };
  const [formData, setFormData] = useState(initialFormState);

  const { vehicles, fetchVehicles } = useVehicles();
  const { drivers, fetchDrivers } = useDrivers();

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

  const handleVehicleSelect = (vehicle) => {
    if (!vehicle) return;
    setFormData(prev => ({
      ...prev,
      placa: vehicle.placa || prev.placa,
      unidade: vehicle.base || prev.unidade,
      rota: vehicle.id_rota || prev.rota,
      // Add other relevant fields for monitoring
    }));
  };

  const handleOpenModal = (item = null) => {
    if (item) {
        setEditingItem(item);
        setFormData({ ...initialFormState, ...item });
    } else {
        setEditingItem(null);
        setFormData(initialFormState);
    }
    setIsModalOpen(true);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    let success;
    if (editingItem) {
        success = await updateMonitoring(editingItem.idmonitoramento_frota, formData);
    } else {
        success = await createMonitoring(formData);
    }
    if (success) setIsModalOpen(false);
  };

  const filteredData = useMemo(() => Array.isArray(monitorings) ? monitorings.filter(item => 
    item.unidade?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    item.motorista?.toLowerCase().includes(searchTerm.toLowerCase())
  ) : [], [monitorings, searchTerm]);

  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-black text-slate-800 dark:text-white tracking-tight">Monitoramento & Logística</h1>
          <p className="text-slate-500 text-sm">Acompanhamento em tempo real e rastreabilidade.</p>
        </div>
        <div className="flex items-center gap-3 w-full md:w-auto">
          <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-emerald-500 w-full md:w-64"
              placeholder="Buscar unidade..." 
              value={searchTerm}
              onChange={e => setSearchTerm(e.target.value)}
            />
          </div>
          <DarkButton onClick={() => handleOpenModal()}>
            <Plus size={18} /> Novo Monitoramento
          </DarkButton>
        </div>
      </div>

      <div className="h-[600px] w-full max-w-full overflow-hidden min-w-0">
        <ExcelTable 
           data={filteredData}
           loading={loading}
           columns={[
             { header: 'ID', field: 'idmonitoramento_frota', width: '80px' },
             { header: 'ID EXTERNO', field: 'id_externo', width: '120px' },
             { header: 'PLACA', field: 'placa', width: '100px', className: 'font-mono font-bold text-emerald-600 dark:text-emerald-500' },
             { header: 'UNIDADE', field: 'unidade', width: '150px' },
             { header: 'MOTORISTA', field: 'motorista', width: '150px' },
             { header: 'DATA CARGA', field: 'data_carga', width: '150px' },
           ]}
           filterDefs={[
               { field: 'placa', label: 'Placa', type: 'text', placeholder: 'Buscar placa...' },
               { field: 'unidade', label: 'Unidade', type: 'select' },
           ]}
           onEdit={handleOpenModal}
        />
      </div>

      <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
        <DialogContent className="max-w-4xl bg-white dark:bg-[#1c1c1c] border-slate-200 dark:border-[#2a2a2a] text-slate-700 dark:text-slate-200 p-0 overflow-hidden shadow-2xl">
           <DialogHeader className="p-6 border-b border-slate-200 dark:border-[#2a2a2a]">
               <DialogTitle className="text-slate-800 dark:text-white uppercase font-black">
                   {editingItem ? 'Editar Monitoramento' : 'Novo Registro de Monitoramento'}
               </DialogTitle>
               <DialogDescription className="text-slate-500 dark:text-stone-500">
                   Detalhes sobre o acompanhamento da viagem e carga.
               </DialogDescription>
           </DialogHeader>
           
           <form onSubmit={handleSubmit} className="px-6 py-4 max-h-[75vh] overflow-y-auto custom-scrollbar">
               <div className="grid grid-cols-2 gap-4 pb-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="Unidade" value={formData.unidade} onChange={e => setFormData({...formData, unidade: e.target.value})} />
               </div>
               <div className="grid grid-cols-3 gap-4 pb-4">
                  <DarkInput label="Rota" value={formData.rota} onChange={e => setFormData({...formData, rota: e.target.value})} />
                  <AutocompleteInput
                      label="Motorista"
                      value={formData.motorista}
                      onChange={v => setFormData({...formData, motorista: v})}
                      options={drivers}
                      displayKey="NOME_FAVORECIDO" 
                      valueKey="NOME_FAVORECIDO"
                      placeholder="Buscar motorista..."
                   />
                  <DarkInput type="date" label="Data Carga" value={formData.data_carga?.split('T')[0]} onChange={e => setFormData({...formData, data_carga: e.target.value})} />
               </div>
               <div className="grid grid-cols-1 gap-4 pb-4">
                  <DarkInput label="ID Externo" value={formData.id_externo} onChange={e => setFormData({...formData, id_externo: e.target.value})} />
               </div>
               
                <div className="gap-4 pb-4">
                    <label className="text-[10px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider ml-1">Observações de Monitoramento</label>
                    <textarea 
                      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-emerald-500 transition-all placeholder:text-slate-400 dark:placeholder:text-slate-700 min-h-[100px]"
                      value={formData.obs}
                      onChange={e => setFormData({...formData, obs: e.target.value})}
                    />
                </div>

               <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">Salvar Registro</DarkButton>
               </DialogFooter>
           </form>
        </DialogContent>
      </Dialog>
    </div>
  );
}
