import React, { useEffect, useState } from 'react';
import { useWorkshops } from '../hooks/useWorkshops';
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 WorkshopsView() {
  const { workshops, loading, fetchWorkshops, createWorkshop, updateWorkshop } = useWorkshops();
  const [searchTerm, setSearchTerm] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingItem, setEditingItem] = useState(null);

  const initialFormState = {
    idoficinas_frota: '',
    cod_estabelecimento: '',
    cnpj: '',
    razao_social: '',
    nome_reduzido: '',
    tipo_estabelecimento: '',
    endereco: '',
    bairro: '',
    cidade: '',
    uf: '',
    fone_comercial: '',
    descricao_grupo: ''
  };
  const [formData, setFormData] = useState(initialFormState);

  useEffect(() => {
    fetchWorkshops();
  }, []);

  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 updateWorkshop(editingItem.idoficinas_frota, formData);
    } else {
        success = await createWorkshop(formData);
    }
    if (success) setIsModalOpen(false);
  };

  const filteredData = Array.isArray(workshops) ? workshops.filter(item => 
    item.nome_reduzido?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    item.razao_social?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    item.cidade?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    item.cnpj?.toLowerCase().includes(searchTerm.toLowerCase())
  ) : [];

  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 uppercase">Gestão de Oficinas</h1>
          <p className="text-slate-500 text-sm">Rede credenciada e prestadores de serviços.</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 transition-all"
              placeholder="Buscar por nome, CNPJ ou cidade..." 
              value={searchTerm}
              onChange={e => setSearchTerm(e.target.value)}
            />
          </div>
          <DarkButton onClick={() => handleOpenModal()}>
            <Plus size={18} /> Nova Oficina
          </DarkButton>
        </div>
      </div>

      <div className="h-[calc(100vh-220px)] w-full max-w-full overflow-hidden min-w-0">
        <ExcelTable 
           data={filteredData}
           loading={loading}
           rowKey="idoficinas_frota"
           columns={[
             { header: 'ID', field: 'idoficinas_frota', width: '80px' },
             { header: 'Cod. Estab.', field: 'cod_estabelecimento', width: '100px' },
             { header: 'Nome Reduzido', field: 'nome_reduzido', width: '220px', className: 'font-bold text-emerald-600 dark:text-emerald-500' },
             { header: 'Razão Social', field: 'razao_social', width: '250px' },
             { header: 'CNPJ', field: 'cnpj', width: '150px' },
             { header: 'Tipo', field: 'tipo_estabelecimento', width: '180px' },
             { header: 'Cidade', field: 'cidade', width: '150px' },
             { header: 'UF', field: 'uf', width: '60px' },
             { header: 'Bairro', field: 'bairro', width: '150px' },
             { header: 'Endereço', field: 'endereco', width: '300px' },
             { header: 'Telefone', field: 'fone_comercial', width: '150px' },
             { header: 'Grupo', field: 'descricao_grupo', width: '200px' },
           ]}
           filterDefs={[
               { field: 'cidade', label: 'Cidade', type: 'select' },
               { field: 'tipo_estabelecimento', label: 'Tipo', type: 'select' },
               { field: 'uf', label: 'UF', type: 'select' },
               { field: 'descricao_grupo', label: 'Grupo', type: 'select' },
           ]}
           onEdit={handleOpenModal}
        />
      </div>

      <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
        <DialogContent className="max-w-3xl 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] bg-slate-50/50 dark:bg-[#222]/30">
               <DialogTitle className="text-slate-800 dark:text-white uppercase font-black flex items-center gap-2">
                   <div className="w-2 h-6 bg-emerald-500 rounded-xl"></div>
                   {editingItem ? 'Editar Oficina' : 'Cadastrar Nova Oficina'}
               </DialogTitle>
               <DialogDescription className="text-slate-500 dark:text-slate-400">
                  Preencha os dados cadastrais da oficina conforme os registros do sistema.
               </DialogDescription>
           </DialogHeader>
           
           <form onSubmit={handleSubmit} className="px-6 py-6 space-y-6 max-h-[70vh] overflow-y-auto custom-scrollbar">
               {/* Seção: Identificação */}
               <div className="space-y-4">
                  <h3 className="text-[11px] font-black text-emerald-600 dark:text-emerald-500 uppercase tracking-[0.2em] border-b border-emerald-500/20 pb-1">Identificação</h3>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                      <div className="md:col-span-1">
                          <DarkInput label="Cod. Estabelecimento" value={formData.cod_estabelecimento} onChange={e => setFormData({...formData, cod_estabelecimento: e.target.value})} />
                      </div>
                      <div className="md:col-span-2">
                          <DarkInput label="CNPJ" value={formData.cnpj} onChange={e => setFormData({...formData, cnpj: e.target.value})} />
                      </div>
                  </div>
                  
                  <DarkInput label="Razão Social" value={formData.razao_social} onChange={e => setFormData({...formData, razao_social: e.target.value})} required />
                  
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <DarkInput label="Nome Reduzido" value={formData.nome_reduzido} onChange={e => setFormData({...formData, nome_reduzido: e.target.value})} required />
                      <DarkInput label="Tipo Estabelecimento" value={formData.tipo_estabelecimento} onChange={e => setFormData({...formData, tipo_estabelecimento: e.target.value})} />
                  </div>
               </div>

               {/* Seção: Localização e Contato */}
               <div className="space-y-4">
                  <h3 className="text-[11px] font-black text-emerald-600 dark:text-emerald-500 uppercase tracking-[0.2em] border-b border-emerald-500/20 pb-1">Localização e Contato</h3>
                  <DarkInput label="Endereço" value={formData.endereco} onChange={e => setFormData({...formData, endereco: e.target.value})} />
                  
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                      <DarkInput label="Bairro" value={formData.bairro} onChange={e => setFormData({...formData, bairro: e.target.value})} />
                      <DarkInput label="Cidade" value={formData.cidade} onChange={e => setFormData({...formData, cidade: e.target.value})} />
                      <DarkInput label="UF" value={formData.uf} onChange={e => setFormData({...formData, uf: e.target.value})} maxLength={2} />
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <DarkInput label="Telefone Comercial" value={formData.fone_comercial} onChange={e => setFormData({...formData, fone_comercial: e.target.value})} />
                      <DarkInput label="Descrição do Grupo" value={formData.descricao_grupo} onChange={e => setFormData({...formData, descricao_grupo: e.target.value})} />
                  </div>
               </div>

               <DialogFooter className="bg-slate-50 dark:bg-[#1c1c1c] border-t border-slate-200 dark:border-[#2a2a2a] p-4 gap-2 mt-6">
                   <DarkButton type="button" variant="ghost" onClick={() => setIsModalOpen(false)}>Cancelar</DarkButton>
                   <DarkButton type="submit" className="min-w-[150px]">Salvar Cadastro</DarkButton>
               </DialogFooter>
           </form>
        </DialogContent>
      </Dialog>
    </div>
  );
}
