import React, { useState, useEffect } from 'react';
import { X, Truck, ShieldCheck, User, Key, Save, MapPin } from 'lucide-react';
import * as grService from '../services/grService';

export const VehicleFormModal = ({ isOpen, onClose, onSave }) => {
  const [formData, setFormData] = useState({
    plate: '',
    type: 'TRUCK',
    trackerBrand: 'ONIXSAT',
    trackerLogin: '',
    trackerPassword: '',
    driverName: '',
    base: ''
  });
  const [bases, setBases] = useState([]);

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

  if (!isOpen) return null;

  const handleSave = (e) => {
    e.preventDefault();
    onSave?.(formData);
    onClose();
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 backdrop-blur-md animate-in fade-in duration-300">
      <div className="bg-white dark:bg-[#1b1b1b] w-full max-w-lg rounded-[48px] shadow-2xl overflow-hidden border border-white/5 animate-in zoom-in-95 duration-300">
        <div className="flex items-center justify-between p-8 pb-4">
          <h3 className="text-2xl font-black text-slate-800 dark:text-white tracking-tighter uppercase">Novo <span className="text-[var(--gr-primary)]">Veículo</span></h3>
          <button onClick={onClose} className="p-3 bg-slate-100 dark:bg-white/5 rounded-full hover:bg-red-500 hover:text-white transition-all text-slate-400">
            <X size={20} />
          </button>
        </div>

        <form onSubmit={handleSave} className="p-10 pt-4 space-y-8">
          {/* Placa Section */}
          <div className="flex flex-col items-center gap-4 py-8 bg-slate-50 dark:bg-white/[0.02] rounded-[40px] border border-slate-100 dark:border-white/5">
            <div className="p-4 bg-[var(--gr-primary)]/10 text-[var(--gr-primary)] rounded-full">
              <Truck size={48} />
            </div>
            <div className="w-full px-12 space-y-2 text-center">
              <label className="text-[10px] font-black text-slate-400 uppercase tracking-[0.3em]">Identificação</label>
              <input 
                autoFocus
                type="text"
                placeholder="ABC-1234"
                value={formData.plate}
                onChange={(e) => setFormData({ ...formData, plate: e.target.value.toUpperCase() })}
                className="w-full text-center text-4xl font-black text-[var(--gr-primary)] bg-transparent border-none outline-none placeholder:opacity-20 uppercase tracking-tighter"
              />
            </div>
          </div>

          <div className="grid grid-cols-1 gap-6">
            {/* Tipo e Raster */}
            <div className="space-y-4">
               <div className="flex items-center gap-2 mb-2">
                 <ShieldCheck className="text-[var(--gr-primary)]" size={18} />
                 <h4 className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Rastreador e Tipo</h4>
               </div>
               
               <div className="grid grid-cols-2 gap-4">
                  <select 
                    value={formData.type}
                    onChange={(e) => setFormData({ ...formData, type: e.target.value })}
                    className="w-full p-4 bg-slate-50 dark:bg-white/5 rounded-2xl border-none text-sm font-bold text-slate-700 dark:text-white outline-none focus:ring-2 focus:ring-[var(--gr-primary)]/20 transition-all"
                  >
                    <option value="TRUCK">Caminhão</option>
                    <option value="VAN">Van / Fiorino</option>
                    <option value="CAR">Carro / Passeio</option>
                    <option value="CAVALO">Cavalo</option>
                    <option value="CARRETA">Carreta</option>
                  </select>

                  <select 
                    value={formData.trackerBrand}
                    onChange={(e) => setFormData({ ...formData, trackerBrand: e.target.value })}
                    className="w-full p-4 bg-slate-50 dark:bg-white/5 rounded-2xl border-none text-sm font-bold text-slate-700 dark:text-white outline-none focus:ring-2 focus:ring-[var(--gr-primary)]/20 transition-all"
                  >
                    <option value="ONIXSAT">Onixsat</option>
                    <option value="SASCAR">Sascar</option>
                    <option value="AUTOTRAC">Autotrac</option>
                    <option value="OMNILINK">Omnilink</option>
                  </select>
               </div>

               <div className="grid grid-cols-2 gap-4">
                  <div className="relative">
                    <User className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" size={14} />
                    <input 
                      type="text"
                      placeholder="Login"
                      value={formData.trackerLogin}
                      onChange={(e) => setFormData({ ...formData, trackerLogin: e.target.value })}
                      className="w-full pl-10 pr-4 py-3.5 bg-slate-50 dark:bg-white/5 rounded-2xl border-none text-xs font-bold text-slate-700 dark:text-white outline-none focus:ring-2 focus:ring-[var(--gr-primary)]/20 transition-all"
                    />
                  </div>
                  <div className="relative">
                    <Key className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" size={14} />
                    <input 
                      type="password"
                      placeholder="Senha"
                      value={formData.trackerPassword}
                      onChange={(e) => setFormData({ ...formData, trackerPassword: e.target.value })}
                      className="w-full pl-10 pr-4 py-3.5 bg-slate-50 dark:bg-white/5 rounded-2xl border-none text-xs font-bold text-slate-700 dark:text-white outline-none focus:ring-2 focus:ring-[var(--gr-primary)]/20 transition-all"
                    />
                  </div>
               </div>
            </div>

            {/* Motorista e Base Section */}
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-4">
                <div className="flex items-center gap-2 mb-2">
                  <User className="text-[var(--gr-primary)]" size={18} />
                  <h4 className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Motorista</h4>
                </div>
                <input 
                  type="text"
                  placeholder="BUSCAR MOTORISTA..."
                  value={formData.driverName}
                  onChange={(e) => setFormData({ ...formData, driverName: e.target.value })}
                  className="w-full p-4 bg-slate-50 dark:bg-white/5 rounded-2xl border-none text-xs font-bold text-slate-700 dark:text-white outline-none focus:ring-2 focus:ring-[var(--gr-primary)]/20 transition-all uppercase placeholder:opacity-40"
                />
              </div>

              <div className="space-y-4">
                <div className="flex items-center gap-2 mb-2">
                  <MapPin className="text-[var(--gr-primary)]" size={18} />
                  <h4 className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Base</h4>
                </div>
                <select 
                  value={formData.base}
                  onChange={(e) => setFormData({ ...formData, base: e.target.value })}
                  className="w-full p-4 bg-slate-50 dark:bg-white/5 rounded-2xl border-none text-xs font-bold text-slate-700 dark:text-white outline-none focus:ring-2 focus:ring-[var(--gr-primary)]/20 transition-all cursor-pointer"
                >
                  <option value="" className="dark:bg-[#1b1b1b]">Selecionar Base</option>
                  {bases.map(b => (
                    <option key={b.idbase || b.id} value={b.base || b.nome} className="dark:bg-[#1b1b1b]">
                      {b.base || b.nome}
                    </option>
                  ))}
                </select>
              </div>
            </div>
          </div>

          <div className="flex gap-4 pt-6">
            <button 
              type="button"
              onClick={onClose}
              className="flex-1 py-5 bg-slate-100 dark:bg-white/5 text-slate-500 dark:text-slate-400 rounded-3xl font-black text-[10px] uppercase tracking-[0.2em] hover:bg-slate-200 dark:hover:bg-white/10 transition-all"
            >
              Cancelar
            </button>
            <button 
              type="submit"
              className="flex-[2] py-5 bg-emerald-500 text-white rounded-3xl font-black text-[10px] uppercase tracking-[0.2em] hover:bg-emerald-600 transition-all shadow-xl shadow-emerald-500/20 flex items-center justify-center gap-3"
            >
              <Save size={18} />
              Confirmar Cadastro
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};
