// Caririaçu Guincho — Tab Checklist

const { useState: useStateTC, useEffect: useEffectTC, useMemo: useMemoTC } = React;

const TabChecklist = ({ guincho, periodo }) => {
  const [items, setItems] = useStateTC([]);
  const [templates, setTemplates] = useStateTC([]);
  const [view, setView] = useStateTC(null);
  const [novoStep, setNovoStep] = useStateTC(null);
  const [tick, setTick] = useStateTC(0);

  useEffectTC(() => {
    sb.from('checklist_execucoes').select('*')
      .eq('guincho_id', guincho.id)
      .gte('data', periodo.inicio)
      .lte('data', periodo.fim + 'T23:59:59')
      .order('data', { ascending: false })
      .then(r => setItems(r.data || []));
  }, [guincho.id, periodo.inicio, periodo.fim, tick]);

  useEffectTC(() => {
    db.list('checklist_templates', { eq: { ativo: true }, order: 'nome', asc: true }).then(setTemplates);
  }, []);

  const metricas = useMemoTC(() => {
    const ultima = items[0];
    let pctOk = null;
    if (ultima) {
      const r = ultima.respostas || [];
      const ok = r.filter(x => x.ok).length;
      pctOk = r.length ? Math.round((ok / r.length) * 100) : null;
    }
    return { count: items.length, ultima, pctOk };
  }, [items]);

  const iniciar = (tpl) => {
    setNovoStep({
      template_id: tpl.id,
      template_nome: tpl.nome,
      data: new Date().toISOString().slice(0, 16),
      km: guincho.km_atual,
      responsavel: '',
      respostas: (tpl.itens || []).map(it => ({
        item_id: it.id, label: it.label, obrigatorio: it.obrigatorio, ok: false, obs: ''
      })),
    });
  };

  const salvar = async () => {
    const obrigSemOk = novoStep.respostas.filter(r => r.obrigatorio && !r.ok);
    let statusFinal = 'concluido';
    if (obrigSemOk.length) {
      if (!confirm(`${obrigSemOk.length} item(ns) obrigatório(s) não marcados como OK. Salvar como pendente?`)) return;
      statusFinal = 'pendente';
    }
    const result = await db.insert('checklist_execucoes', {
      guincho_id: guincho.id,
      template_id: novoStep.template_id,
      template_nome: novoStep.template_nome,
      data: novoStep.data,
      km: parseInt(novoStep.km) || null,
      responsavel: novoStep.responsavel,
      respostas: novoStep.respostas.map(r => ({ item_id: r.item_id, label: r.label, ok: r.ok, obs: r.obs })),
      status: statusFinal,
    });
    if (!result) return;
    setNovoStep(null); setTick(t => t + 1);
    showToast('Checklist salvo', 'success');
  };

  const excluir = async (item) => {
    if (!confirm('Excluir este checklist?')) return;
    const ok = await db.remove('checklist_execucoes', item.id);
    if (!ok) return;
    setTick(t => t + 1);
    showToast('Checklist excluído', 'info');
  };

  return (
    <>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginBottom: 12 }}>
        <div style={{ background: '#fff', border: '1px solid #E2E8F0', borderRadius: 10, padding: 12 }}>
          <div style={{ fontSize: 10, color: '#64748B', textTransform: 'uppercase', letterSpacing: 0.5, fontWeight: 600 }}>Total no período</div>
          <div style={{ fontSize: 18, fontWeight: 700, color: '#0F172A', marginTop: 4 }}>{metricas.count}</div>
        </div>
        <div style={{ background: '#fff', border: '1px solid #E2E8F0', borderRadius: 10, padding: 12 }}>
          <div style={{ fontSize: 10, color: '#64748B', textTransform: 'uppercase', letterSpacing: 0.5, fontWeight: 600 }}>Último</div>
          <div style={{ fontSize: 14, fontWeight: 700, color: '#0F172A', marginTop: 4 }}>
            {metricas.ultima ? new Date(metricas.ultima.data).toLocaleDateString('pt-BR') : '—'}
          </div>
        </div>
        <div style={{ background: '#fff', border: '1px solid #E2E8F0', borderRadius: 10, padding: 12 }}>
          <div style={{ fontSize: 10, color: '#64748B', textTransform: 'uppercase', letterSpacing: 0.5, fontWeight: 600 }}>% OK último</div>
          <div style={{ fontSize: 18, fontWeight: 700, color: metricas.pctOk >= 90 ? '#10B981' : '#F59E0B', marginTop: 4 }}>
            {metricas.pctOk != null ? metricas.pctOk + '%' : '—'}
          </div>
        </div>
      </div>

      <div style={{ background: '#fff', border: '1px solid #E2E8F0', borderRadius: 10, overflow: 'hidden' }}>
        {items.length === 0 ? (
          <div style={{ color: '#94A3B8', textAlign: 'center', padding: 24 }}>
            Nenhum checklist no período. Clique no + pra preencher um.
          </div>
        ) : items.map(x => {
          const ok = (x.respostas || []).filter(r => r.ok).length;
          const total = (x.respostas || []).length;
          return (
            <div key={x.id} style={{
              padding: 12, borderBottom: '1px solid #F1F5F9',
              display: 'flex', justifyContent: 'space-between', gap: 12, alignItems: 'center'
            }}>
              <div style={{ flex: 1, cursor: 'pointer' }} onClick={() => setView(x)}>
                <div style={{ fontSize: 13, fontWeight: 600, color: '#0F172A' }}>
                  {x.template_nome || 'Checklist'}
                </div>
                <div style={{ fontSize: 11, color: '#64748B', marginTop: 2 }}>
                  {new Date(x.data).toLocaleDateString('pt-BR')}
                  {x.km && ` · ${fmtKM(x.km)}`}
                  {x.responsavel && ` · ${x.responsavel}`}
                  · {ok}/{total} OK
                  {x.status === 'pendente' && <span style={{ color: '#F59E0B', fontWeight: 600 }}> · pendente</span>}
                </div>
              </div>
              <button onClick={() => excluir(x)} style={{
                background: 'none', border: 'none', cursor: 'pointer', color: '#EF4444', fontSize: 11
              }}>Excluir</button>
            </div>
          );
        })}
      </div>

      <FabAdicionar onClick={() => {
        if (!templates.length) { showToast('Cadastre um template em Configurações primeiro', 'warning'); return; }
        if (templates.length === 1) iniciar(templates[0]);
        else setNovoStep('select-template');
      }} />

      {/* Seletor de template */}
      {novoStep === 'select-template' && (
        <Modal open={true} onClose={() => setNovoStep(null)} title="Escolher template" width={400}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {templates.map(t => (
              <button key={t.id} onClick={() => iniciar(t)} style={{
                background: '#F8FAFC', border: '1px solid #E2E8F0', borderRadius: 8,
                padding: 12, textAlign: 'left', cursor: 'pointer'
              }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{t.nome}</div>
                <div style={{ fontSize: 11, color: '#64748B', marginTop: 2 }}>
                  {(t.itens || []).length} itens
                </div>
              </button>
            ))}
          </div>
        </Modal>
      )}

      {/* Form de preenchimento */}
      {novoStep && typeof novoStep === 'object' && (
        <Modal open={true} onClose={() => setNovoStep(null)} title={`Preencher: ${novoStep.template_nome}`} width={560}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12, maxHeight: '70vh', overflowY: 'auto' }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <Input label="Data/Hora" type="datetime-local" value={novoStep.data}
                     onChange={e => setNovoStep({ ...novoStep, data: e.target.value })} />
              <Input label="Odômetro (km)" type="number" value={novoStep.km || ''}
                     onChange={e => setNovoStep({ ...novoStep, km: e.target.value })} />
            </div>
            <Input label="Responsável" placeholder="Nome do motorista/operador" value={novoStep.responsavel}
                   onChange={e => setNovoStep({ ...novoStep, responsavel: e.target.value })} />
            <div style={{ borderTop: '1px solid #E2E8F0', paddingTop: 12 }}>
              <div style={{ fontSize: 12, color: '#64748B', fontWeight: 600, textTransform: 'uppercase', marginBottom: 8 }}>
                Itens
              </div>
              {novoStep.respostas.map((r, i) => (
                <div key={r.item_id} style={{
                  background: r.ok ? '#ECFDF5' : '#F8FAFC',
                  border: '1px solid ' + (r.ok ? '#86EFAC' : '#E2E8F0'),
                  borderRadius: 8, padding: 10, marginBottom: 6,
                  display: 'flex', flexDirection: 'column', gap: 8
                }}>
                  <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
                    <input type="checkbox" checked={r.ok} onChange={e => {
                      const arr = [...novoStep.respostas];
                      arr[i] = { ...r, ok: e.target.checked };
                      setNovoStep({ ...novoStep, respostas: arr });
                    }} style={{ width: 18, height: 18 }} />
                    <span style={{ fontSize: 13, color: '#0F172A', fontWeight: r.obrigatorio ? 600 : 500 }}>
                      {r.label} {r.obrigatorio && <span style={{ color: '#EF4444' }}>*</span>}
                    </span>
                  </label>
                  <input value={r.obs || ''} placeholder="Observação (opcional)"
                         onChange={e => {
                           const arr = [...novoStep.respostas];
                           arr[i] = { ...r, obs: e.target.value };
                           setNovoStep({ ...novoStep, respostas: arr });
                         }}
                         style={{ border: '1px solid #E2E8F0', borderRadius: 4, padding: '4px 8px', fontSize: 11, background: '#fff' }} />
                </div>
              ))}
            </div>
            <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end',
                          paddingTop: 8, borderTop: '1px solid #F1F5F9' }}>
              <Btn variant="secondary" onClick={() => setNovoStep(null)}>Cancelar</Btn>
              <Btn variant="primary" icon="check" onClick={salvar}>Salvar</Btn>
            </div>
          </div>
        </Modal>
      )}

      {/* Visualização read-only */}
      {view && (
        <Modal open={true} onClose={() => setView(null)} title={`${view.template_nome}`} width={500}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <div style={{ fontSize: 11, color: '#64748B' }}>
              {new Date(view.data).toLocaleString('pt-BR')}
              {view.km && ` · ${fmtKM(view.km)}`}
              {view.responsavel && ` · ${view.responsavel}`}
            </div>
            {(view.respostas || []).map(r => (
              <div key={r.item_id} style={{
                background: r.ok ? '#ECFDF5' : '#FEE2E2',
                border: '1px solid ' + (r.ok ? '#86EFAC' : '#FCA5A5'),
                borderRadius: 6, padding: 8
              }}>
                <div style={{ fontSize: 12 }}>
                  {r.ok ? '✓' : '✗'} <strong>{r.label}</strong>
                </div>
                {r.obs && <div style={{ fontSize: 11, color: '#64748B', marginTop: 4 }}>{r.obs}</div>}
              </div>
            ))}
            <div style={{ display: 'flex', justifyContent: 'flex-end',
                          paddingTop: 8, borderTop: '1px solid #F1F5F9' }}>
              <Btn variant="secondary" onClick={() => setView(null)}>Fechar</Btn>
            </div>
          </div>
        </Modal>
      )}
    </>
  );
};

Object.assign(window, { TabChecklist });
