// Clients.jsx
'use strict';
const { useState, useEffect } = React;

function ClientModal({ open, onClose, onSave, editClient }) {
  const empty = { name:'', cpf:'', phone:'', email:'', address:'', notes:'' };
  const [form, setForm] = useState(empty);
  const [errors, setErrors] = useState({});
  useEffect(() => { if (open) { setForm(editClient ? {...editClient} : {...empty}); setErrors({}); } }, [open, editClient]);
  const set = (k,v) => setForm(f=>({...f,[k]:v}));
  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = 'Nome obrigatório';
    if (!form.phone.trim()) e.phone = 'Telefone obrigatório';
    setErrors(e);
    return Object.keys(e).length === 0;
  };
  const handleSave = () => { if (!validate()) return; onSave(form); onClose(); };
  return (
    <Modal open={open} onClose={onClose} title={editClient ? 'Editar Cliente' : 'Novo Cliente'} width="max-w-xl">
      <div className="space-y-4">
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <FormField label="Nome completo" required error={errors.name} className="sm:col-span-2">
            <Input value={form.name} onChange={e=>set('name',e.target.value)} placeholder="João da Silva" error={!!errors.name}/>
          </FormField>
          <FormField label="CPF / CNPJ">
            <Input value={form.cpf} onChange={e=>set('cpf',e.target.value)} placeholder="000.000.000-00"/>
          </FormField>
          <FormField label="Telefone / WhatsApp" required error={errors.phone}>
            <Input value={form.phone} onChange={e=>set('phone',e.target.value)} placeholder="(11) 99999-9999" error={!!errors.phone}/>
          </FormField>
          <FormField label="E-mail" className="sm:col-span-2">
            <Input type="email" value={form.email} onChange={e=>set('email',e.target.value)} placeholder="cliente@email.com"/>
          </FormField>
          <FormField label="Endereço completo" className="sm:col-span-2">
            <Input value={form.address} onChange={e=>set('address',e.target.value)} placeholder="Rua, número, bairro, cidade/UF, CEP"/>
          </FormField>
          <FormField label="Observações" className="sm:col-span-2">
            <Textarea rows={2} value={form.notes} onChange={e=>set('notes',e.target.value)} placeholder="Informações adicionais sobre o cliente..."/>
          </FormField>
        </div>
        <div className="flex gap-3 pt-2 border-t border-slate-100">
          <Btn variant="outline" onClick={onClose} className="mr-auto">Cancelar</Btn>
          <Btn icon="Check" onClick={handleSave}>{editClient ? 'Salvar alterações' : 'Cadastrar cliente'}</Btn>
        </div>
      </div>
    </Modal>
  );
}

function ClientDetailModal({ open, onClose, client, workOrders, onEdit, onDelete }) {
  if (!client) return null;
  const clientOS = workOrders.filter(o => o.clientId === client.id).sort((a,b)=>b.num?.localeCompare(a.num));
  return (
    <Modal open={open} onClose={onClose} title="Ficha do Cliente" width="max-w-lg">
      <div className="space-y-5">
        <div className="flex items-center gap-4">
          <div className="w-14 h-14 rounded-2xl flex items-center justify-center text-xl font-bold text-white flex-shrink-0"
            style={{background:'#0A1F44'}}>{client.name.split(' ').map(w=>w[0]).slice(0,2).join('')}</div>
          <div>
            <h3 className="text-lg font-bold" style={{color:'#0A1F44'}}>{client.name}</h3>
            <p className="text-sm text-slate-400">Cliente desde {fmtDate(client.createdAt)}</p>
          </div>
        </div>
        <div className="grid grid-cols-1 gap-2 text-sm">
          {client.phone && <div className="flex items-center gap-2 text-slate-600"><Icon name="Phone" size={14} color="#94A3B8"/>{client.phone}</div>}
          {client.email && <div className="flex items-center gap-2 text-slate-600"><Icon name="Mail" size={14} color="#94A3B8"/>{client.email}</div>}
          {client.address && <div className="flex items-start gap-2 text-slate-600"><Icon name="MapPin" size={14} color="#94A3B8" style={{marginTop:2}}/><span>{client.address}</span></div>}
          {client.cpf && <div className="flex items-center gap-2 text-slate-500 text-xs"><Icon name="User" size={14} color="#94A3B8"/>CPF/CNPJ: {client.cpf}</div>}
          {client.notes && <div className="p-3 rounded-xl bg-amber-50 text-amber-800 text-xs">{client.notes}</div>}
        </div>
        {clientOS.length > 0 && (
          <div>
            <p className="text-xs font-bold uppercase text-slate-400 mb-2">Histórico de OSs ({clientOS.length})</p>
            <div className="space-y-1.5 max-h-40 overflow-y-auto">
              {clientOS.map(os=>(
                <div key={os.id} className="flex items-center justify-between px-3 py-2 rounded-xl bg-slate-50 text-sm">
                  <div><span className="font-bold text-xs" style={{color:'#0A1F44'}}>#{os.num}</span><span className="text-slate-500 text-xs ml-2">{os.equipment?.brand} {os.equipment?.model}</span></div>
                  <div className="flex items-center gap-2"><StatusBadge status={os.status} size="xs"/><span className="font-medium text-xs text-slate-600">{fmtCurrency(os.total||0)}</span></div>
                </div>
              ))}
            </div>
          </div>
        )}
        <div className="flex flex-wrap gap-2 pt-3 border-t border-slate-100">
          <Btn variant="outline" onClick={onClose} className="sm:mr-auto">Fechar</Btn>
          <Btn variant="ghost" icon="Trash2" onClick={()=>{ if (onDelete){ onClose(); onDelete(client); } }} className="text-red-500 hover:bg-red-50">Excluir</Btn>
          <Btn variant="ghost" icon="Edit" onClick={()=>{onClose();onEdit(client);}}>Editar</Btn>
        </div>
      </div>
    </Modal>
  );
}

function Clients({ clients, workOrders, onAdd, onUpdate, onDelete, addToast }) {
  const [search, setSearch] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [showDetail, setShowDetail] = useState(false);
  const [editClient, setEditClient] = useState(null);
  const [detailClient, setDetailClient] = useState(null);
  const [confirm, setConfirm] = useState(null);
  const [loading, setLoading] = useState(true);
  useEffect(()=>{ const t=setTimeout(()=>setLoading(false),500); return()=>clearTimeout(t); },[]);

  const filtered = clients.filter(c => {
    const q = search.toLowerCase();
    return !q || c.name?.toLowerCase().includes(q) || c.phone?.includes(q) || c.email?.toLowerCase().includes(q) || c.cpf?.includes(q);
  }).sort((a,b)=>a.name.localeCompare(b.name,'pt-BR'));

  const getLastOS = c => {
    const cos = workOrders.filter(o=>o.clientId===c.id).sort((a,b)=>b.entryDate?.localeCompare(a.entryDate));
    return cos[0];
  };

  const handleSave = form => {
    if (editClient) { onUpdate(editClient.id, form); addToast({type:'success',msg:'Cliente atualizado!'}); }
    else { onAdd({...form, id:'CLI'+String(clients.length+1).padStart(3,'0'), createdAt:new Date().toISOString().split('T')[0]}); addToast({type:'success',msg:'Cliente cadastrado!'}); }
  };

  return (
    <div className="anim-fade">
      <PageHeader title="Clientes" subtitle={`${clients.length} clientes cadastrados`}
        action={<Btn icon="Plus" onClick={()=>{setEditClient(null);setShowModal(true);}}>Novo Cliente</Btn>}/>
      <Card>
        <div className="flex flex-col sm:flex-row gap-3 p-4 border-b border-slate-50">
          <SearchInput value={search} onChange={setSearch} placeholder="Buscar por nome, telefone, e-mail..." className="flex-1"/>
          <div className="text-xs text-slate-400 self-center whitespace-nowrap">{filtered.length} resultado(s)</div>
        </div>
        {loading ? Array.from({length:6}).map((_,i)=><SkeletonRow key={i}/>) :
          filtered.length===0 ? <EmptyState icon="Users" title="Nenhum cliente encontrado" message="Tente ajustar a busca ou cadastre um novo cliente." actionLabel="Novo Cliente" onAction={()=>setShowModal(true)}/> :
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead><tr className="border-b border-slate-100">
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase tracking-wider">Nome</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase tracking-wider hidden sm:table-cell">Telefone</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase tracking-wider hidden md:table-cell">E-mail</th>
                <th className="px-4 py-3 text-center text-xs font-semibold text-slate-400 uppercase tracking-wider hidden md:table-cell">OSs</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase tracking-wider hidden lg:table-cell">Última OS</th>
                <th className="px-4 py-3 text-right text-xs font-semibold text-slate-400 uppercase tracking-wider">Ações</th>
              </tr></thead>
              <tbody>
                {filtered.map(c => {
                  const lastOS = getLastOS(c);
                  const osCount = workOrders.filter(o=>o.clientId===c.id).length;
                  return (
                    <tr key={c.id}
                      onClick={()=>{setDetailClient(c);setShowDetail(true);}}
                      className="border-b border-slate-50 hover:bg-slate-50 active:bg-slate-100 transition-colors cursor-pointer">
                      <td className="px-4 py-3.5">
                        <div className="flex items-center gap-3">
                          <div className="w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold text-white flex-shrink-0" style={{background:'#0A1F44'}}>
                            {c.name.split(' ').map(w=>w[0]).slice(0,2).join('')}
                          </div>
                          <div>
                            <div className="font-semibold text-slate-800">{c.name}</div>
                            <div className="text-xs text-slate-400 sm:hidden">{c.phone}</div>
                            {c.cpf && <div className="text-xs text-slate-400 hidden sm:block">{c.cpf}</div>}
                          </div>
                        </div>
                      </td>
                      <td className="px-4 py-3.5 hidden sm:table-cell text-slate-600">{c.phone}</td>
                      <td className="px-4 py-3.5 hidden md:table-cell text-slate-500 text-xs">{c.email||'—'}</td>
                      <td className="px-4 py-3.5 hidden md:table-cell text-center">
                        <span className="inline-flex items-center justify-center w-6 h-6 rounded-full text-xs font-bold"
                          style={{background: osCount>0?'#EFF6FF':'#F1F5F9', color: osCount>0?'#3B82F6':'#94A3B8'}}>{osCount}</span>
                      </td>
                      <td className="px-4 py-3.5 hidden lg:table-cell">
                        {lastOS ? <StatusBadge status={lastOS.status} size="xs"/> : <span className="text-slate-300 text-xs">—</span>}
                      </td>
                      <td className="px-2 py-3.5">
                        <div className="hidden md:flex items-center justify-end gap-1">
                          <button onClick={(e)=>{e.stopPropagation();setDetailClient(c);setShowDetail(true);}} className="w-7 h-7 rounded-lg flex items-center justify-center text-slate-400 hover:text-blue-600 hover:bg-blue-50 transition-colors"><Icon name="Eye" size={14}/></button>
                          <button onClick={(e)=>{e.stopPropagation();setEditClient(c);setShowModal(true);}} className="w-7 h-7 rounded-lg flex items-center justify-center text-slate-400 hover:text-amber-600 hover:bg-amber-50 transition-colors"><Icon name="Edit" size={14}/></button>
                          <button onClick={(e)=>{e.stopPropagation();setConfirm(c.id);}} className="w-7 h-7 rounded-lg flex items-center justify-center text-slate-400 hover:text-red-600 hover:bg-red-50 transition-colors"><Icon name="Trash2" size={14}/></button>
                        </div>
                        <div className="md:hidden flex items-center justify-end pr-1">
                          <Icon name="ChevronRight" size={18} color="#94A3B8"/>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        }
      </Card>
      <ClientModal open={showModal} onClose={()=>{setShowModal(false);setEditClient(null);}} onSave={handleSave} editClient={editClient}/>
      <ClientDetailModal open={showDetail} onClose={()=>{setShowDetail(false);setDetailClient(null);}} client={detailClient} workOrders={workOrders}
        onEdit={c=>{setEditClient(c);setShowModal(true);}}
        onDelete={c=>setConfirm(c.id)}/>
      <ConfirmDialog open={!!confirm} onClose={()=>setConfirm(null)}
        onConfirm={()=>{onDelete(confirm);addToast({type:'info',msg:'Cliente excluído.'});}}
        message="Excluir este cliente? As OSs vinculadas não serão removidas."/>
    </div>
  );
}

Object.assign(window, { Clients });
