
// ============================================================
// JuFlow — Atendimentos (Appointments list)
// ============================================================
const { useState: useStAT, useMemo: useMemoAT } = React;
const UAT = window.JFUtils;

const Atendimentos = ({ appointments, onViewAppt, onNewAppt }) => {
  const [search, setSearch]   = useStAT('');
  const [statusF, setStatusF] = useStAT('all');
  const [profF, setProfF]     = useStAT('all');
  const [period, setPeriod]   = useStAT('30');

  const filtered = useMemoAT(() => {
    const cutoff = UAT.addDays(window.JF.TODAY, -Number(period));
    let list = appointments.filter(a => new Date(a.datetime) >= cutoff);
    if (statusF !== 'all') list = list.filter(a => a.status === statusF);
    if (profF   !== 'all') list = list.filter(a => a.professionalId === Number(profF));
    if (search) {
      const q = search.toLowerCase();
      list = list.filter(a => {
        const c = UAT.getClient(a.clientId);
        const s = UAT.getService(a.serviceId);
        return c?.name.toLowerCase().includes(q) || s?.name.toLowerCase().includes(q);
      });
    }
    return list.sort((a,b) => new Date(b.datetime) - new Date(a.datetime));
  }, [appointments, statusF, profF, period, search]);

  const totalRevenue = filtered.filter(a=>a.status==='completed').reduce((s,a)=>s+a.price,0);
  const completedCnt = filtered.filter(a=>a.status==='completed').length;
  const cancelledCnt = filtered.filter(a=>a.status==='cancelled'||a.status==='no_show').length;

  return (
    <div style={{ padding:28, display:'flex', flexDirection:'column', gap:20 }}>
      {/* Metrics */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14 }}>
        <MetricCard title="Total no período"  value={filtered.length}             icon="ClipboardList" color="#7C3AED" subtitle="atendimentos" />
        <MetricCard title="Realizados"        value={completedCnt}                icon="CheckCircle"   color="#059669" subtitle="concluídos" />
        <MetricCard title="Cancelados/Faltas" value={cancelledCnt}               icon="XCircle"       color="#EF4444" subtitle="perdidos" />
        <MetricCard title="Faturado"          value={UAT.formatCurrency(totalRevenue)} icon="DollarSign" color="#FF6B35" subtitle="no período" />
      </div>

      {/* Filters */}
      <div style={{ background:'#fff', borderRadius:14, padding:'16px 20px', boxShadow:'0 2px 8px rgba(10,31,68,.06)', display:'flex', gap:12, flexWrap:'wrap', alignItems:'center' }}>
        <SearchBar value={search} onChange={setSearch} placeholder="Buscar por cliente ou serviço..." style={{ flex:'1 1 200px' }} />

        {[
          { val:statusF, set:setStatusF, opts:[['all','Todos'],['completed','Realizados'],['confirmed','Confirmados'],['pending','Pendentes'],['cancelled','Cancelados'],['no_show','Faltas']] },
        ].map(({val,set,opts},i) => (
          <select key={i} value={val} onChange={e=>set(e.target.value)} style={{ padding:'9px 12px', borderRadius:8, fontSize:12, border:'1px solid #E2E8F0', background:'#fff', color:'#0A1F44', cursor:'pointer', outline:'none' }}>
            {opts.map(([v,l]) => <option key={v} value={v}>{l}</option>)}
          </select>
        ))}

        <select value={profF} onChange={e=>setProfF(e.target.value)} style={{ padding:'9px 12px', borderRadius:8, fontSize:12, border:'1px solid #E2E8F0', background:'#fff', color:'#0A1F44', cursor:'pointer', outline:'none' }}>
          <option value="all">Todos os profissionais</option>
          {window.JF.PROFESSIONALS.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
        </select>

        <select value={period} onChange={e=>setPeriod(e.target.value)} style={{ padding:'9px 12px', borderRadius:8, fontSize:12, border:'1px solid #E2E8F0', background:'#fff', color:'#0A1F44', cursor:'pointer', outline:'none' }}>
          <option value="7">Últimos 7 dias</option>
          <option value="30">Últimos 30 dias</option>
          <option value="60">Últimos 60 dias</option>
          <option value="90">Últimos 90 dias</option>
        </select>

        <span style={{ fontSize:12, color:'#9CA3AF', marginLeft:'auto' }}>{filtered.length} registros</span>
        <Button variant="primary" icon="Plus" onClick={() => onNewAppt({})}>Novo</Button>
      </div>

      {/* Table */}
      <div style={{ background:'#fff', borderRadius:14, boxShadow:'0 2px 8px rgba(10,31,68,.06)', overflow:'hidden' }}>
        {filtered.length === 0 ? (
          <EmptyState icon="ClipboardList" title="Nenhum atendimento encontrado" message="Ajuste os filtros para ver mais resultados." />
        ) : (
          <div style={{ overflowX:'auto' }}>
            <table style={{ width:'100%', borderCollapse:'collapse' }}>
              <thead>
                <tr style={{ background:'#F9FAFB', borderBottom:'2px solid #E2E8F0' }}>
                  {['Data/Hora','Cliente','Serviço','Profissional','Duração','Valor','Pagamento','Status','Ações'].map(h => (
                    <th key={h} style={{ padding:'11px 14px', fontSize:11, fontWeight:700, color:'#6B7280', textAlign:'left', textTransform:'uppercase', letterSpacing:.5, whiteSpace:'nowrap' }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {filtered.slice(0,50).map((appt, i) => {
                  const client  = UAT.getClient(appt.clientId);
                  const service = UAT.getService(appt.serviceId);
                  const prof    = UAT.getProfessional(appt.professionalId);
                  return (
                    <tr key={appt.id} style={{ borderBottom: i<filtered.length-1?'1px solid #F0F4F8':'none', transition:'background .1s', cursor:'pointer' }}
                      onClick={() => onViewAppt(appt)}
                      onMouseEnter={e=>e.currentTarget.style.background='#F9FAFB'}
                      onMouseLeave={e=>e.currentTarget.style.background='#fff'}
                    >
                      <td style={{ padding:'11px 14px' }}>
                        <div style={{ fontSize:12, fontWeight:700, color:'#0A1F44' }}>{UAT.formatDate(appt.datetime)}</div>
                        <div style={{ fontSize:11, color:'#9CA3AF' }}>{UAT.formatTime(appt.datetime)}</div>
                      </td>
                      <td style={{ padding:'11px 14px' }}>
                        <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                          <Avatar name={client?.name} color="#0A1F44" size={28} />
                          <span style={{ fontSize:13, fontWeight:600, color:'#0A1F44' }}>{client?.name}</span>
                        </div>
                      </td>
                      <td style={{ padding:'11px 14px', fontSize:12, color:'#374151', maxWidth:140 }}>
                        <span style={{ overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap', display:'block' }}>{service?.name}</span>
                      </td>
                      <td style={{ padding:'11px 14px' }}>
                        <div style={{ display:'flex', alignItems:'center', gap:6 }}>
                          <div style={{ width:8, height:8, borderRadius:'50%', background:prof?.color, flexShrink:0 }} />
                          <span style={{ fontSize:12, color:'#374151', whiteSpace:'nowrap' }}>{prof?.name?.split(' ').slice(0,2).join(' ')}</span>
                        </div>
                      </td>
                      <td style={{ padding:'11px 14px', fontSize:12, color:'#6B7280' }}>{appt.duration}min</td>
                      <td style={{ padding:'11px 14px', fontSize:13, fontWeight:700, color:'#059669' }}>{UAT.formatCurrency(appt.price)}</td>
                      <td style={{ padding:'11px 14px', fontSize:12, color:'#6B7280' }}>{appt.paymentMethod || '—'}</td>
                      <td style={{ padding:'11px 14px' }}><Badge status={appt.status} /></td>
                      <td style={{ padding:'11px 14px' }} onClick={e=>e.stopPropagation()}>
                        <div style={{ display:'flex', gap:5 }}>
                          <button onClick={()=>onViewAppt(appt)} title="Ver detalhes"
                            style={{ width:28,height:28,borderRadius:6,border:'1px solid #E2E8F0',background:'#F9FAFB',cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center' }}
                            onMouseEnter={e=>e.currentTarget.style.background='#EFF6FF'} onMouseLeave={e=>e.currentTarget.style.background='#F9FAFB'}
                          ><Icon name="Eye" size={12} color="#0891B2" /></button>
                          <button onClick={()=>window.print()} title="Imprimir recibo"
                            style={{ width:28,height:28,borderRadius:6,border:'1px solid #E2E8F0',background:'#F9FAFB',cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center' }}
                            onMouseEnter={e=>e.currentTarget.style.background='#F0FDF4'} onMouseLeave={e=>e.currentTarget.style.background='#F9FAFB'}
                          ><Icon name="Printer" size={12} color="#059669" /></button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
            {filtered.length > 50 && (
              <div style={{ padding:'12px 16px', background:'#F9FAFB', borderTop:'1px solid #E2E8F0', fontSize:12, color:'#9CA3AF', textAlign:'center' }}>
                Exibindo 50 de {filtered.length} registros. Use os filtros para refinar.
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { Atendimentos });
