// Caririaçu Guincho — Frota Screen

const { useState: useStateF, useEffect: useEffectF } = React;

// ── Modal de Registro de Manutenção ──────────────────────────────────────
const NovaManutencaoModal = ({ open, item, onClose, onSaved }) => {
  const [form, setForm] = useStateF({ data: new Date().toISOString().slice(0,10), tipo: 'Preventiva', descricao: '', valor: '', oficina: '' });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  if (!open || !item) return null;

  const handle = async () => {
    if (!form.descricao) { showToast('Descreva o serviço de manutenção', 'warning'); return; }
    const created = await db.insert('manutencoes', {
      guincho_id: item.id,
      guincho_code: item.code,
      data: form.data,
      tipo: form.tipo,
      descricao: form.descricao,
      valor: parseFloat(form.valor) || 0,
      oficina: form.oficina,
    });
    if (created) {
      showToast(`Manutenção registrada para ${item.code}`, 'success');
      setForm({ data: new Date().toISOString().slice(0,10), tipo: 'Preventiva', descricao: '', valor: '', oficina: '' });
      onSaved?.();
      onClose();
    }
  };

  return (
    <Modal open={open} onClose={onClose} title={`Nova Manutenção · ${item.code}`} width={520}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ background: '#F8FAFC', borderRadius: 10, padding: 12, display: 'flex', alignItems: 'center', gap: 10 }}>
          <Icon name="truck" size={18} color="#3B82F6" />
          <div>
            <div style={{ fontSize: 13, fontWeight: 600, color: '#0F172A' }}>{item.modelo}</div>
            <div style={{ fontSize: 11, color: '#64748B' }}>{item.placa} · {item.code}</div>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <Input label="Data" type="date" value={form.data} onChange={e => set('data', e.target.value)} />
          <Select label="Tipo" value={form.tipo} onChange={e => set('tipo', e.target.value)}
            options={[{value:'Preventiva',label:'Preventiva'},{value:'Corretiva',label:'Corretiva'}]} />
        </div>
        <Input label="Descrição do serviço" placeholder="Ex: Troca de óleo, filtros e correia" value={form.descricao} onChange={e => set('descricao', e.target.value)} />
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 14 }}>
          <Input label="Oficina" placeholder="Ex: TruckService" value={form.oficina} onChange={e => set('oficina', e.target.value)} />
          <Input label="Valor (R$)" type="number" placeholder="0.00" value={form.valor} onChange={e => set('valor', e.target.value)} />
        </div>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', paddingTop: 8, borderTop: '1px solid #F1F5F9' }}>
          <Btn variant="secondary" onClick={onClose}>Cancelar</Btn>
          <Btn variant="primary" icon="check" onClick={handle}>Registrar</Btn>
        </div>
      </div>
    </Modal>
  );
};

const FrotaScreen = () => {
  const [frota, setFrota] = useStateF([]);
  const [loading, setLoading] = useStateF(true);
  const [motoristas, setMotoristas] = useStateF([]);
  const [modal, setModal] = useStateF(false);
  const [editItem, setEditItem] = useStateF(null);
  const [form, setForm] = useStateF({ placa: '', modelo: '', marca: '', ano: '', cor: '', status: 'ativo', motorista_id: '', obs: '' });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const statusMap = { ativo: { label: 'Ativo', color: '#10B981' }, manutencao: { label: 'Manutenção', color: '#F59E0B' }, inativo: { label: 'Inativo', color: '#94A3B8' } };

  const refresh = async () => {
    setLoading(true);
    const [f, m] = await Promise.all([
      db.list('frota', { order: 'code', asc: true }),
      db.list('motoristas', { order: 'nome', asc: true })
    ]);
    setFrota(f);
    setMotoristas(m);
    setLoading(false);
  };
  useEffectF(() => { refresh(); }, []);

  const openNew = () => {
    const nextNum = (frota.length + 1).toString().padStart(3, '0');
    setEditItem(null);
    setForm({ placa: '', modelo: '', marca: '', ano: '', cor: '', status: 'ativo', motorista_id: '', obs: '', code: `GNC-${nextNum}` });
    setModal(true);
  };
  const openEdit = (item) => {
    setEditItem(item);
    setForm({
      placa: item.placa, modelo: item.modelo || '', marca: item.marca || '', ano: item.ano || '',
      cor: item.cor || '', status: item.status, motorista_id: item.motorista_id || '', obs: item.obs || '', code: item.code
    });
    setModal(true);
  };

  const handleSave = async () => {
    if (!form.placa || !form.modelo) { showToast('Placa e modelo são obrigatórios', 'warning'); return; }
    const motoristaSel = motoristas.find(m => m.id === parseInt(form.motorista_id));
    const payload = {
      placa: form.placa, modelo: form.modelo, marca: form.marca, ano: form.ano ? parseInt(form.ano) : null,
      cor: form.cor, status: form.status, obs: form.obs,
      motorista_id: form.motorista_id ? parseInt(form.motorista_id) : null,
      motorista_nome: motoristaSel?.nome || null,
    };
    if (editItem) {
      const updated = await db.update('frota', editItem.id, payload);
      if (updated) { showToast('Guincho atualizado!', 'success'); refresh(); }
    } else {
      const created = await db.insert('frota', { ...payload, code: form.code });
      if (created) {
        showToast('Guincho cadastrado!', 'success');
        if (motoristaSel) await db.update('motoristas', motoristaSel.id, { guincho_code: form.code });
        refresh();
      }
    }
    setModal(false);
  };

  const toggleManutencao = async (item) => {
    const novoStatus = item.status === 'manutencao' ? 'ativo' : 'manutencao';
    const updated = await db.update('frota', item.id, { status: novoStatus });
    if (updated) { showToast('Status atualizado!', 'success'); refresh(); }
  };

  return (
    <div style={{ padding: 28, display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
        <div>
          <h1 style={{ margin: 0, fontSize: 22, fontWeight: 700, color: '#0F172A', fontFamily: 'DM Sans, sans-serif' }}>Frota de Guinchos</h1>
          <span style={{ fontSize: 13, color: '#64748B' }}>{frota.length} veículos cadastrados · {frota.filter(f => f.status === 'ativo').length} ativos</span>
        </div>
        <Btn variant="primary" icon="plus" onClick={openNew}>Novo Guincho</Btn>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(140px,1fr))', gap: 12 }}>
        {[
          { label: 'Total', value: frota.length, color: '#3B82F6', icon: 'truck' },
          { label: 'Ativos', value: frota.filter(f=>f.status==='ativo').length, color: '#10B981', icon: 'check' },
          { label: 'Manutenção', value: frota.filter(f=>f.status==='manutencao').length, color: '#F59E0B', icon: 'wrench' },
          { label: 'Inativos', value: frota.filter(f=>f.status==='inativo').length, color: '#94A3B8', icon: 'x' },
        ].map(c => (
          <Card key={c.label} style={{ padding: '16px 20px', display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 36, height: 36, borderRadius: 9, background: c.color + '18', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <Icon name={c.icon} size={18} color={c.color} />
            </div>
            <div>
              <div style={{ fontSize: 22, fontWeight: 700, color: '#0F172A', fontFamily: 'DM Sans, sans-serif' }}>{c.value}</div>
              <div style={{ fontSize: 12, color: '#64748B' }}>{c.label}</div>
            </div>
          </Card>
        ))}
      </div>

      {loading ? (
        <Card style={{ padding: 60, textAlign: 'center', color: '#94A3B8', fontSize: 14 }}>Carregando frota...</Card>
      ) : frota.length === 0 ? (
        <Card style={{ padding: 60, textAlign: 'center' }}>
          <Icon name="truck" size={48} color="#CBD5E1" />
          <div style={{ fontSize: 16, color: '#64748B', marginTop: 14, fontWeight: 600 }}>Nenhum guincho cadastrado</div>
          <div style={{ fontSize: 13, color: '#94A3B8', marginTop: 4 }}>Cadastre o primeiro veículo da sua frota</div>
          <Btn variant="primary" icon="plus" onClick={openNew} style={{ marginTop: 16 }}>Cadastrar Primeiro Guincho</Btn>
        </Card>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(280px,1fr))', gap: 16 }}>
          {frota.map(item => {
            const st = statusMap[item.status];
            return (
              <Card key={item.id} style={{ padding: 0, overflow: 'hidden', transition: 'box-shadow 0.2s' }}
                onMouseEnter={e => e.currentTarget.style.boxShadow = '0 4px 16px rgba(0,0,0,0.1)'}
                onMouseLeave={e => e.currentTarget.style.boxShadow = '0 1px 3px rgba(0,0,0,0.07)'}>
                <div style={{ height: 100, background: 'linear-gradient(135deg,#1E293B,#0F172A)', display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
                  <Icon name="truck" size={44} color="rgba(255,255,255,0.15)" />
                  <div style={{ position: 'absolute', top: 12, right: 12 }}>
                    <span style={{ background: st.color + '20', color: st.color, border: `1px solid ${st.color}40`, borderRadius: 6, padding: '3px 9px', fontSize: 11, fontWeight: 700 }}>{st.label}</span>
                  </div>
                  <div style={{ position: 'absolute', bottom: 10, left: 16, fontFamily: 'DM Mono, monospace', fontSize: 16, fontWeight: 700, color: '#F59E0B', letterSpacing: 1 }}>{item.placa}</div>
                  <div style={{ position: 'absolute', bottom: 10, right: 16, fontSize: 11, color: '#64748B' }}>{item.code}</div>
                </div>
                <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
                  <div>
                    <div style={{ fontWeight: 700, color: '#0F172A', fontSize: 15, fontFamily: 'DM Sans, sans-serif' }}>{item.modelo}</div>
                    <div style={{ fontSize: 13, color: '#64748B' }}>{item.marca || '—'} · {item.ano || '—'} · {item.cor || '—'}</div>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 10px', background: '#F8FAFC', borderRadius: 8 }}>
                    <Avatar initials={item.motorista_nome ? item.motorista_nome.split(' ').map(w=>w[0]).join('').slice(0,2).toUpperCase() : '--'} size={26} />
                    <div>
                      <div style={{ fontSize: 12, color: '#374151', fontWeight: 600 }}>{item.motorista_nome || 'Sem motorista'}</div>
                      <div style={{ fontSize: 11, color: '#94A3B8' }}>Motorista vinculado</div>
                    </div>
                  </div>
                  <div style={{ display: 'flex', gap: 6, paddingTop: 4, borderTop: '1px solid #F1F5F9' }}>
                    <Btn variant="secondary" size="sm" icon="edit" onClick={() => openEdit(item)} style={{ flex: 1, justifyContent: 'center' }}>Editar</Btn>
                    <Btn variant="ghost" size="sm" icon="fileText" onClick={() => window.abrirGuincho?.(item.id)} style={{ flex: 1, justifyContent: 'center' }}>Histórico</Btn>
                    <Btn variant="ghost" size="sm" icon="wrench" onClick={() => toggleManutencao(item)} title={item.status === 'manutencao' ? 'Reativar' : 'Marcar como manutenção'}>
                      {item.status === 'manutencao' ? '↩' : '🔧'}
                    </Btn>
                  </div>
                </div>
              </Card>
            );
          })}
        </div>
      )}

      <Modal open={modal} onClose={() => setModal(false)} title={editItem ? `Editar ${editItem.placa}` : 'Novo Guincho'} width={540}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Input label="Código" placeholder="GNC-001" value={form.code} onChange={e => set('code', e.target.value)} />
            <Input label="Placa" placeholder="ABC-1D23" value={form.placa} onChange={e => set('placa', e.target.value)} />
            <Input label="Modelo" placeholder="Constellation 24.280" value={form.modelo} onChange={e => set('modelo', e.target.value)} />
            <Input label="Marca" placeholder="Volkswagen" value={form.marca} onChange={e => set('marca', e.target.value)} />
            <Input label="Ano" placeholder="2022" value={form.ano} onChange={e => set('ano', e.target.value)} />
            <Input label="Cor" placeholder="Branco" value={form.cor} onChange={e => set('cor', e.target.value)} />
            <Select label="Status" value={form.status} onChange={e => set('status', e.target.value)}
              options={[{value:'ativo',label:'Ativo'},{value:'manutencao',label:'Em Manutenção'},{value:'inativo',label:'Inativo'}]} />
            <Select label="Motorista Responsável" value={form.motorista_id} onChange={e => set('motorista_id', e.target.value)}
              options={[{value:'',label:'Sem motorista'}, ...motoristas.map(m => ({ value: m.id, label: m.nome }))]} />
          </div>
          <Input label="Observações" placeholder="Informações adicionais..." value={form.obs} onChange={e => set('obs', e.target.value)} />
          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', paddingTop: 8, borderTop: '1px solid #F1F5F9' }}>
            <Btn variant="secondary" onClick={() => setModal(false)}>Cancelar</Btn>
            <Btn variant="primary" onClick={handleSave}>{editItem ? 'Salvar Alterações' : 'Cadastrar Guincho'}</Btn>
          </div>
        </div>
      </Modal>
    </div>
  );
};

Object.assign(window, { FrotaScreen, NovaManutencaoModal });
