
// ============================================================
// JuFlow — Serviços + Pacotes
// ============================================================
const { useState: useStSV } = React;
const USV = window.JFUtils;

const SVC_COLORS = ['#FF6B35','#7C3AED','#0891B2','#059669','#D97706','#DB2777','#3B82F6','#14B8A6','#EF4444','#A855F7'];
const EMPTY_SVC = { id:null, name:'', category:'', price:100, duration:60, description:'', professionals:[], color:'#FF6B35' };

const Servicos = ({ addToast }) => {
  const [tab, setTab] = useStSV('servicos');
  const [search, setSearch] = useStSV('');
  const [catFilter, setCatFilter] = useStSV('all');
  const [extraSvcs, setExtraSvcs] = useStSV([]);
  const [removed, setRemoved] = useStSV([]);
  const [modal, setModal] = useStSV({ open:false, mode:'create', form: EMPTY_SVC });
  const [confirm, setConfirm] = useStSV({ open:false, svc:null });

  const allServices = [...window.JF.SERVICES, ...extraSvcs].filter(s => !removed.includes(s.id));
  const categories = [...new Set(allServices.map(s => s.category))];

  const filtered = allServices.filter(s => {
    const matchSearch = !search || s.name.toLowerCase().includes(search.toLowerCase());
    const matchCat    = catFilter === 'all' || s.category === catFilter;
    return matchSearch && matchCat;
  });

  const openCreate = () => setModal({ open:true, mode:'create', form: { ...EMPTY_SVC, color: SVC_COLORS[Math.floor(Math.random()*SVC_COLORS.length)] } });
  const openEdit = (svc) => setModal({ open:true, mode:'edit', form: { ...EMPTY_SVC, ...svc, professionals: [...(svc.professionals || [])] } });
  const closeModal = () => setModal(m => ({ ...m, open:false }));
  const setForm = (k, v) => setModal(m => ({ ...m, form: { ...m.form, [k]: v } }));
  const toggleProf = (id) => setForm('professionals', modal.form.professionals.includes(id) ? modal.form.professionals.filter(p => p !== id) : [...modal.form.professionals, id]);

  const saveSvc = () => {
    const f = modal.form;
    if (!f.name.trim() || !f.category.trim()) { addToast('Preencha nome e categoria.', 'warning'); return; }
    if (!f.price || f.price <= 0)              { addToast('Informe um valor válido.', 'warning'); return; }
    if (!f.duration || f.duration <= 0)        { addToast('Informe a duração.', 'warning'); return; }
    if (modal.mode === 'create') {
      const id = Math.max(0, ...allServices.map(s=>s.id)) + 1;
      setExtraSvcs(arr => [...arr, { ...f, id }]);
      addToast(`Serviço "${f.name}" criado!`, 'success');
    } else {
      const isFromBase = window.JF.SERVICES.some(s => s.id === f.id);
      if (isFromBase) {
        Object.assign(window.JF.SERVICES.find(s=>s.id===f.id), f);
        setExtraSvcs(arr => [...arr]);
      } else {
        setExtraSvcs(arr => arr.map(s => s.id === f.id ? { ...s, ...f } : s));
      }
      addToast('Serviço atualizado!', 'success');
    }
    closeModal();
  };

  const duplicateSvc = (svc) => {
    const id = Math.max(0, ...allServices.map(s=>s.id)) + 1;
    setExtraSvcs(arr => [...arr, { ...svc, id, name: svc.name + ' (cópia)' }]);
    addToast(`Cópia de "${svc.name}" criada.`, 'success');
  };

  const askDelete = (svc) => setConfirm({ open:true, svc });
  const confirmDelete = () => {
    setRemoved(arr => [...arr, confirm.svc.id]);
    addToast(`Serviço "${confirm.svc.name}" excluído.`, 'success');
  };

  return (
    <div style={{ padding:28, display:'flex', flexDirection:'column', gap:20 }}>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14 }}>
        <MetricCard title="Total de Serviços" value={allServices.length} icon="Scissors" color="#7C3AED" subtitle="no catálogo" />
        <MetricCard title="Categorias"        value={categories.length}   icon="Tag"      color="#0891B2" subtitle="diferentes" />
        <MetricCard title="Ticket Médio"      value={USV.formatCurrency(allServices.length ? allServices.reduce((s,sv)=>s+sv.price,0)/allServices.length : 0)} icon="DollarSign" color="#059669" subtitle="por serviço" />
        <MetricCard title="Pacotes Ativos"    value={window.JF.PACKAGES.length} icon="Package" color="#FF6B35" subtitle="disponíveis" />
      </div>

      <Tabs tabs={[{id:'servicos',label:'Catálogo de Serviços',icon:'Scissors'},{id:'pacotes',label:'Pacotes',icon:'Package'}]} activeTab={tab} onTabChange={setTab} />

      {tab === 'servicos' && (
        <>
          <div style={{ background:'#fff', borderRadius:14, padding:'14px 18px', boxShadow:'0 2px 8px rgba(10,31,68,.06)', display:'flex', gap:12, alignItems:'center', flexWrap:'wrap' }}>
            <SearchBar value={search} onChange={setSearch} placeholder="Buscar serviço..." style={{ flex:'1 1 200px' }} />
            <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
              <button onClick={()=>setCatFilter('all')} style={{ padding:'5px 12px', borderRadius:20, fontSize:12, fontWeight:600, cursor:'pointer', background:catFilter==='all'?'#0A1F44':'#F3F4F6', color:catFilter==='all'?'#fff':'#6B7280', border:'none' }}>Todos</button>
              {categories.map(c => (
                <button key={c} onClick={()=>setCatFilter(c)} style={{ padding:'5px 12px', borderRadius:20, fontSize:12, fontWeight:600, cursor:'pointer', background:catFilter===c?'#0A1F44':'#F3F4F6', color:catFilter===c?'#fff':'#6B7280', border:'none' }}>{c}</button>
              ))}
            </div>
            <Button variant="primary" icon="Plus" size="sm" onClick={openCreate}>Novo Serviço</Button>
          </div>

          <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(280px,1fr))', gap:14 }}>
            {filtered.map(svc => {
              const profs = (svc.professionals || []).map(id => USV.getProfessional(id)).filter(Boolean);
              return (
                <div key={svc.id} style={{ background:'#fff', borderRadius:14, padding:20, boxShadow:'0 2px 8px rgba(10,31,68,.06)', border:'1px solid #E2E8F0', transition:'all .2s', cursor:'pointer' }}
                  onMouseEnter={e=>{ e.currentTarget.style.boxShadow='0 8px 24px rgba(10,31,68,.12)'; e.currentTarget.style.transform='translateY(-2px)'; }}
                  onMouseLeave={e=>{ e.currentTarget.style.boxShadow='0 2px 8px rgba(10,31,68,.06)'; e.currentTarget.style.transform='none'; }}
                >
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:12 }}>
                    <div style={{ flex:1 }}>
                      <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:4 }}>
                        <div style={{ width:10, height:10, borderRadius:'50%', background: svc.color || '#FF6B35' }} />
                        <span style={{ fontSize:11, fontWeight:600, color:'#9CA3AF', textTransform:'uppercase', letterSpacing:.5 }}>{svc.category}</span>
                      </div>
                      <h3 style={{ margin:0, fontSize:15, fontWeight:700, color:'#0A1F44' }}>{svc.name}</h3>
                    </div>
                    <DropdownMenu
                      trigger={<button style={{ width:28,height:28,borderRadius:6,border:'1px solid #E2E8F0',background:'#F9FAFB',cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center' }}><Icon name="MoreHorizontal" size={14} color="#6B7280" /></button>}
                      items={[
                        {label:'Editar',icon:'Edit2',onClick:()=>openEdit(svc)},
                        {label:'Duplicar',icon:'Copy',onClick:()=>duplicateSvc(svc)},
                        'divider',
                        {label:'Excluir',icon:'Trash2',onClick:()=>askDelete(svc),danger:true},
                      ]}
                    />
                  </div>
                  <p style={{ fontSize:12, color:'#6B7280', margin:'0 0 14px', lineHeight:1.5 }}>{svc.description}</p>
                  <div style={{ display:'flex', gap:10, marginBottom:14 }}>
                    <div style={{ flex:1, background:'#F9FAFB', borderRadius:8, padding:'8px 10px', textAlign:'center' }}>
                      <div style={{ fontSize:15, fontWeight:800, color:'#0A1F44' }}>{USV.formatCurrency(svc.price)}</div>
                      <div style={{ fontSize:10, color:'#9CA3AF' }}>valor</div>
                    </div>
                    <div style={{ flex:1, background:'#F9FAFB', borderRadius:8, padding:'8px 10px', textAlign:'center' }}>
                      <div style={{ fontSize:15, fontWeight:800, color:'#0A1F44' }}>{svc.duration}min</div>
                      <div style={{ fontSize:10, color:'#9CA3AF' }}>duração</div>
                    </div>
                  </div>
                  <div>
                    <div style={{ fontSize:11, fontWeight:600, color:'#9CA3AF', marginBottom:6, textTransform:'uppercase', letterSpacing:.5 }}>Profissionais</div>
                    <div style={{ display:'flex', gap:4, flexWrap:'wrap' }}>
                      {profs.length === 0 ? (
                        <span style={{ fontSize:11, color:'#9CA3AF', fontStyle:'italic' }}>Nenhum profissional associado</span>
                      ) : profs.map(p => (
                        <div key={p.id} style={{ display:'flex', alignItems:'center', gap:4, padding:'3px 8px', borderRadius:20, background: USV.hexToRgba(p.color,0.1), border:`1px solid ${USV.hexToRgba(p.color,0.25)}` }}>
                          <div style={{ width:6, height:6, borderRadius:'50%', background:p.color }} />
                          <span style={{ fontSize:11, fontWeight:600, color:p.color }}>{p.name.split(' ')[0]}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </>
      )}

      {tab === 'pacotes' && (
        <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(300px,1fr))', gap:16 }}>
          {window.JF.PACKAGES.map(pkg => {
            const svc = USV.getService(pkg.serviceId);
            const discount = Math.round((1 - pkg.price/pkg.originalPrice)*100);
            return (
              <div key={pkg.id} style={{ background:'#fff', borderRadius:14, overflow:'hidden', boxShadow:'0 2px 8px rgba(10,31,68,.06)', border:'1px solid #E2E8F0' }}>
                <div style={{ background:'linear-gradient(135deg,#0A1F44,#0d2a5e)', padding:'18px 20px' }}>
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start' }}>
                    <div>
                      <div style={{ fontSize:11, color:'rgba(255,255,255,.5)', textTransform:'uppercase', letterSpacing:.5, marginBottom:4 }}>Pacote</div>
                      <h3 style={{ margin:0, fontSize:16, fontWeight:700, color:'#fff' }}>{pkg.name}</h3>
                    </div>
                    <div style={{ background:'#FF6B35', color:'#fff', padding:'4px 10px', borderRadius:20, fontSize:12, fontWeight:700 }}>-{discount}%</div>
                  </div>
                </div>
                <div style={{ padding:20 }}>
                  <p style={{ fontSize:12, color:'#6B7280', margin:'0 0 14px', lineHeight:1.5 }}>{pkg.description}</p>
                  <div style={{ display:'flex', gap:10, marginBottom:14 }}>
                    <div style={{ flex:1, background:'#F9FAFB', borderRadius:8, padding:'10px', textAlign:'center' }}>
                      <div style={{ fontSize:18, fontWeight:800, color:'#0A1F44' }}>{pkg.totalSessions}</div>
                      <div style={{ fontSize:10, color:'#9CA3AF' }}>sessões</div>
                    </div>
                    <div style={{ flex:1, background:'#F9FAFB', borderRadius:8, padding:'10px', textAlign:'center' }}>
                      <div style={{ fontSize:16, fontWeight:800, color:'#059669' }}>{USV.formatCurrency(pkg.price)}</div>
                      <div style={{ fontSize:10, color:'#9CA3AF', textDecoration:'line-through' }}>{USV.formatCurrency(pkg.originalPrice)}</div>
                    </div>
                  </div>
                  {svc && <div style={{ fontSize:12, color:'#6B7280', marginBottom:14 }}>Serviço: <strong>{svc.name}</strong></div>}
                  <div style={{ display:'flex', gap:8 }}>
                    <Button size="sm" variant="secondary" icon="Edit2" style={{ flex:1 }} onClick={()=>addToast('Edição de pacote em breve!','info')}>Editar</Button>
                    <Button size="sm" variant="primary" icon="UserPlus" style={{ flex:1 }} onClick={()=>addToast('Pacote vendido com sucesso!','success')}>Vender</Button>
                  </div>
                </div>
              </div>
            );
          })}
          <div style={{ borderRadius:14, border:'2px dashed #D1D5DB', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', padding:40, cursor:'pointer', transition:'all .15s', minHeight:200 }}
            onMouseEnter={e=>{ e.currentTarget.style.borderColor='#FF6B35'; e.currentTarget.style.background='#FFF0EA'; }}
            onMouseLeave={e=>{ e.currentTarget.style.borderColor='#D1D5DB'; e.currentTarget.style.background='transparent'; }}
            onClick={()=>addToast('Modal de novo pacote em breve!','info')}
          >
            <Icon name="Plus" size={28} color="#D1D5DB" />
            <span style={{ fontSize:14, fontWeight:600, color:'#9CA3AF', marginTop:10 }}>Novo Pacote</span>
          </div>
        </div>
      )}

      {/* Service form modal */}
      <Modal
        open={modal.open}
        onClose={closeModal}
        title={modal.mode === 'create' ? 'Novo Serviço' : 'Editar Serviço'}
        width={620}
        footer={<>
          <Button variant="secondary" onClick={closeModal}>Cancelar</Button>
          <Button variant="primary" icon="Save" onClick={saveSvc}>Salvar</Button>
        </>}
      >
        <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
          {/* Color + Name + Category */}
          <div style={{ display:'flex', alignItems:'flex-end', gap:12 }}>
            <div style={{ flexShrink:0 }}>
              <label style={{ fontSize:13, fontWeight:600, color:'#374151', display:'block', marginBottom:6 }}>Cor</label>
              <div style={{ display:'flex', gap:5, flexWrap:'wrap', maxWidth:220 }}>
                {SVC_COLORS.slice(0,5).map(c => (
                  <button key={c} onClick={()=>setForm('color',c)} style={{ width:28, height:28, borderRadius:7, background:c, border: modal.form.color === c ? '3px solid #0A1F44' : '3px solid transparent', cursor:'pointer', boxShadow:'0 1px 3px rgba(0,0,0,.15)' }} />
                ))}
              </div>
              <div style={{ display:'flex', gap:5, flexWrap:'wrap', maxWidth:220, marginTop:5 }}>
                {SVC_COLORS.slice(5).map(c => (
                  <button key={c} onClick={()=>setForm('color',c)} style={{ width:28, height:28, borderRadius:7, background:c, border: modal.form.color === c ? '3px solid #0A1F44' : '3px solid transparent', cursor:'pointer', boxShadow:'0 1px 3px rgba(0,0,0,.15)' }} />
                ))}
              </div>
            </div>
            <Input label="Nome do serviço" value={modal.form.name} onChange={v=>setForm('name',v)} icon="Scissors" required autoFocus style={{ flex:1 }} />
          </div>

          {/* Category (with suggestions) */}
          <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
            <Input label="Categoria" value={modal.form.category} onChange={v=>setForm('category',v)} icon="Tag" required placeholder="Ex: Massagem, Estética..." />
            {categories.length > 0 && (
              <div style={{ display:'flex', gap:5, flexWrap:'wrap' }}>
                <span style={{ fontSize:11, color:'#9CA3AF' }}>Sugestões:</span>
                {categories.map(c => (
                  <button key={c} type="button" onClick={()=>setForm('category',c)} style={{
                    padding:'2px 9px', borderRadius:20, fontSize:11, fontWeight:600, cursor:'pointer',
                    background: modal.form.category === c ? '#0A1F44' : '#F3F4F6',
                    color: modal.form.category === c ? '#fff' : '#6B7280',
                    border:'none',
                  }}>{c}</button>
                ))}
              </div>
            )}
          </div>

          {/* Price + Duration */}
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
            <div style={{ display:'flex', flexDirection:'column', gap:5 }}>
              <label style={{ fontSize:13, fontWeight:600, color:'#374151' }}>Valor (R$) <span style={{ color:'#EF4444' }}>*</span></label>
              <input type="number" min="0" step="10" value={modal.form.price} onChange={e=>setForm('price', Number(e.target.value))}
                style={{ padding:'9px 12px', borderRadius:8, fontSize:13, border:'1.5px solid #E2E8F0', outline:'none', color:'#0A1F44', background:'#fff' }} />
            </div>
            <div style={{ display:'flex', flexDirection:'column', gap:5 }}>
              <label style={{ fontSize:13, fontWeight:600, color:'#374151' }}>Duração (minutos) <span style={{ color:'#EF4444' }}>*</span></label>
              <input type="number" min="5" step="5" value={modal.form.duration} onChange={e=>setForm('duration', Number(e.target.value))}
                style={{ padding:'9px 12px', borderRadius:8, fontSize:13, border:'1.5px solid #E2E8F0', outline:'none', color:'#0A1F44', background:'#fff' }} />
            </div>
          </div>

          {/* Description */}
          <Textarea
            label="Descrição"
            value={modal.form.description}
            onChange={v=>setForm('description',v)}
            rows={2}
            placeholder="Descrição breve do serviço, técnica, benefícios..."
          />

          {/* Professionals selector */}
          <div>
            <label style={{ fontSize:13, fontWeight:600, color:'#374151', display:'block', marginBottom:8 }}>Profissionais que realizam</label>
            <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
              {window.JF.PROFESSIONALS.map(p => {
                const active = modal.form.professionals.includes(p.id);
                return (
                  <button key={p.id} type="button" onClick={()=>toggleProf(p.id)} style={{
                    display:'flex', alignItems:'center', gap:7,
                    padding:'7px 12px', borderRadius:24, fontSize:12, fontWeight:600, cursor:'pointer',
                    background: active ? USV.hexToRgba(p.color,.14) : '#F9FAFB',
                    border: active ? `2px solid ${p.color}` : '2px solid #E2E8F0',
                    color: active ? p.color : '#6B7280', transition:'all .15s',
                  }}>
                    <Avatar name={p.name} color={p.color} size={22} style={{ fontSize:10 }} />
                    {p.name.split(' ')[0]}
                    {active && <Icon name="Check" size={12} color={p.color} />}
                  </button>
                );
              })}
            </div>
            {modal.form.professionals.length === 0 && (
              <div style={{ fontSize:11, color:'#9CA3AF', marginTop:6, fontStyle:'italic' }}>Selecione ao menos um profissional para que o serviço apareça na agenda.</div>
            )}
          </div>
        </div>
      </Modal>

      {/* Delete confirm */}
      <ConfirmDialog
        open={confirm.open}
        onClose={() => setConfirm(c => ({ ...c, open:false }))}
        onConfirm={confirmDelete}
        title="Excluir serviço"
        message={confirm.svc ? `Tem certeza que deseja excluir o serviço "${confirm.svc.name}"? Atendimentos passados serão preservados, mas o serviço não estará mais disponível para novos agendamentos.` : ''}
        confirmLabel="Excluir"
        danger
      />
    </div>
  );
};

Object.assign(window, { Servicos });
