
// ============================================================
// JuFlow — Profissionais
// ============================================================
const { useState: useStPR } = React;
const UPR = window.JFUtils;

const PROF_COLORS = ['#7C3AED','#DB2777','#0891B2','#059669','#FF6B35','#F59E0B','#EF4444','#3B82F6','#14B8A6','#8B5CF6'];
const PROF_DAYS = ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb'];
const EMPTY_PROF = {
  id: null, name: '', role: '', email: '', phone: '',
  color: '#7C3AED', commission: 30,
  workDays: [1,2,3,4,5], startHour: 9, endHour: 18, bio: '',
};

const Profissionais = ({ appointments, addToast }) => {
  const [selected, setSelected] = useStPR(null);
  const [extraProfs, setExtraProfs] = useStPR([]);
  const [removed, setRemoved] = useStPR([]);
  const [modal, setModal] = useStPR({ open:false, mode:'create', form: EMPTY_PROF });
  const [confirm, setConfirm] = useStPR({ open:false, prof:null });

  const allProfs = [...window.JF.PROFESSIONALS, ...extraProfs].filter(p => !removed.includes(p.id));

  const getStats = (profId) => {
    const profAppts = appointments.filter(a => a.professionalId === profId);
    const completed = profAppts.filter(a => a.status === 'completed');
    const revenue   = completed.reduce((s,a) => s + a.price, 0);
    const profObj   = allProfs.find(p => p.id === profId);
    const commission = revenue * ((profObj?.commission || 0) / 100);
    return { total: profAppts.length, completed: completed.length, revenue, commission };
  };

  const openCreate = () => setModal({ open:true, mode:'create', form: { ...EMPTY_PROF, color: PROF_COLORS[Math.floor(Math.random()*PROF_COLORS.length)] } });
  const openEdit = (prof) => setModal({ open:true, mode:'edit', form: { ...EMPTY_PROF, ...prof } });
  const closeModal = () => setModal(m => ({ ...m, open:false }));
  const setForm = (k, v) => setModal(m => ({ ...m, form: { ...m.form, [k]: v } }));
  const toggleDay = (i) => setForm('workDays', modal.form.workDays.includes(i) ? modal.form.workDays.filter(d=>d!==i) : [...modal.form.workDays, i].sort());

  const saveProf = () => {
    const f = modal.form;
    if (!f.name.trim() || !f.role.trim()) { addToast('Preencha nome e função.', 'warning'); return; }
    if (modal.mode === 'create') {
      const id = Math.max(0, ...allProfs.map(p=>p.id)) + 1;
      setExtraProfs(arr => [...arr, { ...f, id, lastName: f.name.split(' ').slice(-1)[0] }]);
      addToast(`${f.name} adicionado(a) à equipe!`, 'success');
    } else {
      const isFromBase = window.JF.PROFESSIONALS.some(p => p.id === f.id);
      if (isFromBase) {
        Object.assign(window.JF.PROFESSIONALS.find(p=>p.id===f.id), f);
        setExtraProfs(arr => [...arr]);
      } else {
        setExtraProfs(arr => arr.map(p => p.id === f.id ? { ...p, ...f } : p));
      }
      addToast('Profissional atualizado!', 'success');
    }
    closeModal();
  };

  const askRemove = (prof) => setConfirm({ open:true, prof });
  const confirmRemove = () => {
    setRemoved(arr => [...arr, confirm.prof.id]);
    setSelected(null);
    addToast(`${confirm.prof.name} foi desativado(a).`, 'success');
  };

  return (
    <div style={{ padding:28, display:'flex', flexDirection:'column', gap:20 }}>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14 }}>
        <MetricCard title="Profissionais" value={allProfs.length} icon="UserCheck" color="#7C3AED" subtitle="ativos" />
        <MetricCard title="Especialidades" value={new Set(allProfs.map(p=>p.role)).size} icon="Award" color="#0891B2" subtitle="áreas" />
        <MetricCard title="Média de Sessões" value={allProfs.length ? Math.round(appointments.filter(a=>a.status==='completed').length/allProfs.length) : 0} icon="Calendar" color="#059669" subtitle="por profissional" />
        <MetricCard title="Comissão Média" value={allProfs.length ? `${Math.round(allProfs.reduce((s,p)=>s+p.commission,0)/allProfs.length)}%` : '0%'} icon="Percent" color="#FF6B35" subtitle="média geral" />
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(320px,1fr))', gap:16 }}>
        {allProfs.map(prof => {
          const stats = getStats(prof.id);
          const isSelected = selected?.id === prof.id;
          return (
            <div key={prof.id}
              style={{
                background:'#fff', borderRadius:16, overflow:'hidden',
                boxShadow: isSelected ? `0 8px 32px ${UPR.hexToRgba(prof.color,0.25)}` : '0 2px 8px rgba(10,31,68,.06)',
                border: isSelected ? `2px solid ${prof.color}` : '2px solid transparent',
                transition:'all .2s', cursor:'pointer',
              }}
              onClick={() => setSelected(isSelected ? null : prof)}
            >
              <div style={{ height:6, background:`linear-gradient(90deg, ${prof.color}, ${UPR.hexToRgba(prof.color,0.4)})` }} />
              <div style={{ padding:20 }}>
                <div style={{ display:'flex', alignItems:'flex-start', gap:14, marginBottom:16 }}>
                  <Avatar name={prof.name} color={prof.color} size={54} style={{ fontSize:20, fontWeight:800 }} />
                  <div style={{ flex:1 }}>
                    <h3 style={{ margin:'0 0 2px', fontSize:16, fontWeight:800, color:'#0A1F44' }}>{prof.name}</h3>
                    <div style={{ fontSize:13, color:prof.color, fontWeight:600, marginBottom:6 }}>{prof.role}</div>
                    <div style={{ display:'flex', gap:6 }}>
                      <div style={{ padding:'2px 8px', borderRadius:20, fontSize:11, fontWeight:600, background:UPR.hexToRgba(prof.color,.1), color:prof.color }}>
                        {prof.commission}% comissão
                      </div>
                    </div>
                  </div>
                  <DropdownMenu
                    trigger={<button style={{ width:30,height:30,borderRadius:8,border:'1px solid #E2E8F0',background:'#F9FAFB',cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center' }} onClick={e=>e.stopPropagation()}><Icon name="MoreVertical" size={14} color="#6B7280" /></button>}
                    items={[
                      {label:'Editar',icon:'Edit2',onClick:()=>openEdit(prof)},
                      {label:'Ver agenda',icon:'Calendar',onClick:()=>addToast('Navegando para agenda...','info')},
                      'divider',
                      {label:'Desativar',icon:'UserX',onClick:()=>askRemove(prof),danger:true},
                    ]}
                  />
                </div>

                <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:8, marginBottom:14 }}>
                  {[
                    { label:'Sessões', value:stats.completed, color:'#059669' },
                    { label:'Faturado', value:UPR.formatCurrency(stats.revenue), color:'#0891B2' },
                    { label:'Comissão', value:UPR.formatCurrency(stats.commission), color:prof.color },
                  ].map(stat => (
                    <div key={stat.label} style={{ background:'#F9FAFB', borderRadius:8, padding:'8px', textAlign:'center' }}>
                      <div style={{ fontSize:14, fontWeight:800, color:stat.color }}>{stat.value}</div>
                      <div style={{ fontSize:10, color:'#9CA3AF' }}>{stat.label}</div>
                    </div>
                  ))}
                </div>

                <div style={{ display:'flex', flexDirection:'column', gap:5 }}>
                  <div style={{ display:'flex', alignItems:'center', gap:6, fontSize:12, color:'#6B7280' }}>
                    <Icon name="Mail" size={12} color="#9CA3AF" />{prof.email}
                  </div>
                  <div style={{ display:'flex', alignItems:'center', gap:6, fontSize:12, color:'#6B7280' }}>
                    <Icon name="Phone" size={12} color="#9CA3AF" />{prof.phone}
                  </div>
                </div>

                {isSelected && (
                  <div style={{ marginTop:14, paddingTop:14, borderTop:'1px solid #F0F4F8' }}>
                    <div style={{ fontSize:11, fontWeight:700, color:'#9CA3AF', textTransform:'uppercase', letterSpacing:.5, marginBottom:8 }}>Horário de trabalho</div>
                    <div style={{ display:'flex', gap:4 }}>
                      {PROF_DAYS.map((d,i) => (
                        <div key={d} style={{
                          width:32, height:32, borderRadius:8, fontSize:10, fontWeight:700,
                          display:'flex', alignItems:'center', justifyContent:'center',
                          background: prof.workDays.includes(i) ? prof.color : '#F3F4F6',
                          color: prof.workDays.includes(i) ? '#fff' : '#C4CDD6',
                        }}>{d}</div>
                      ))}
                    </div>
                    <div style={{ fontSize:12, color:'#6B7280', marginTop:8 }}>
                      <Icon name="Clock" size={11} color="#9CA3AF" style={{marginRight:4}} />
                      {String(prof.startHour).padStart(2,'0')}:00 às {String(prof.endHour).padStart(2,'0')}:00
                    </div>
                    <div style={{ marginTop:10 }}>
                      <div style={{ fontSize:11, fontWeight:700, color:'#9CA3AF', textTransform:'uppercase', letterSpacing:.5, marginBottom:6 }}>Serviços</div>
                      <div style={{ display:'flex', gap:4, flexWrap:'wrap' }}>
                        {window.JF.SERVICES.filter(s=>s.professionals?.includes(prof.id)).map(s => (
                          <span key={s.id} style={{ padding:'2px 8px', borderRadius:20, fontSize:11, fontWeight:600, background:'#F3F4F6', color:'#374151' }}>{s.name}</span>
                        ))}
                        {window.JF.SERVICES.filter(s=>s.professionals?.includes(prof.id)).length === 0 && (
                          <span style={{ fontSize:11, color:'#9CA3AF', fontStyle:'italic' }}>Nenhum serviço associado ainda</span>
                        )}
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </div>
          );
        })}

        {/* Add new card */}
        <div style={{ borderRadius:16, 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={openCreate}
        >
          <Icon name="UserPlus" size={32} color="#D1D5DB" />
          <span style={{ fontSize:15, fontWeight:600, color:'#9CA3AF', marginTop:12 }}>Novo Profissional</span>
        </div>
      </div>

      {/* Form modal */}
      <Modal
        open={modal.open}
        onClose={closeModal}
        title={modal.mode === 'create' ? 'Novo Profissional' : 'Editar Profissional'}
        width={620}
        footer={<>
          <Button variant="secondary" onClick={closeModal}>Cancelar</Button>
          <Button variant="primary" icon="Save" onClick={saveProf}>Salvar</Button>
        </>}
      >
        <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
          {/* Avatar preview + color picker */}
          <div style={{ display:'flex', alignItems:'center', gap:16, padding:'14px 16px', background:'#F9FAFB', borderRadius:12, border:'1px solid #E2E8F0' }}>
            <Avatar name={modal.form.name || '? ?'} color={modal.form.color} size={64} style={{ fontSize:22, fontWeight:800 }} />
            <div style={{ flex:1 }}>
              <div style={{ fontSize:12, fontWeight:600, color:'#374151', marginBottom:8 }}>Cor do profissional</div>
              <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
                {PROF_COLORS.map(c => (
                  <button key={c} onClick={() => setForm('color', c)} style={{
                    width:26, height:26, borderRadius:7, background:c, cursor:'pointer',
                    border: modal.form.color === c ? '3px solid #0A1F44' : '3px solid transparent',
                    boxShadow:'0 1px 3px rgba(0,0,0,.15)', transition:'transform .15s',
                  }}
                    onMouseEnter={e => e.currentTarget.style.transform='scale(1.15)'}
                    onMouseLeave={e => e.currentTarget.style.transform='scale(1)'}
                  />
                ))}
                <input type="color" value={modal.form.color} onChange={e => setForm('color', e.target.value)} style={{ width:26, height:26, borderRadius:7, border:'1px solid #E2E8F0', cursor:'pointer', padding:1 }} />
              </div>
            </div>
          </div>

          {/* Name + role */}
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
            <Input label="Nome completo" value={modal.form.name} onChange={v=>setForm('name',v)} icon="User" required autoFocus />
            <Input label="Função / Especialidade" value={modal.form.role} onChange={v=>setForm('role',v)} icon="Award" required placeholder="Ex: Fisioterapeuta" />
          </div>

          {/* Email + phone */}
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
            <Input label="E-mail" type="email" value={modal.form.email} onChange={v=>setForm('email',v)} icon="Mail" placeholder="nome@clinica.com" />
            <Input label="Telefone" value={modal.form.phone} onChange={v=>setForm('phone',v)} icon="Phone" placeholder="(11) 99999-9999" />
          </div>

          {/* Commission + hours */}
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:12 }}>
            <div style={{ display:'flex', flexDirection:'column', gap:5 }}>
              <label style={{ fontSize:13, fontWeight:600, color:'#374151' }}>Comissão (%)</label>
              <input type="number" min="0" max="100" value={modal.form.commission} onChange={e=>setForm('commission', 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' }}>Início</label>
              <input type="number" min="0" max="23" value={modal.form.startHour} onChange={e=>setForm('startHour', 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' }}>Fim</label>
              <input type="number" min="0" max="23" value={modal.form.endHour} onChange={e=>setForm('endHour', 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>

          {/* Work days */}
          <div>
            <label style={{ fontSize:13, fontWeight:600, color:'#374151', display:'block', marginBottom:8 }}>Dias de trabalho</label>
            <div style={{ display:'flex', gap:6 }}>
              {PROF_DAYS.map((d,i) => {
                const active = modal.form.workDays.includes(i);
                return (
                  <button key={d} onClick={() => toggleDay(i)} style={{
                    flex:1, padding:'10px 0', borderRadius:8, fontSize:12, fontWeight:700,
                    border: active ? `2px solid ${modal.form.color}` : '2px solid #E2E8F0',
                    background: active ? UPR.hexToRgba(modal.form.color,.12) : '#fff',
                    color: active ? modal.form.color : '#9CA3AF',
                    cursor:'pointer', transition:'all .15s',
                  }}>{d}</button>
                );
              })}
            </div>
          </div>

          {/* Bio */}
          <Textarea
            label="Bio / Observações"
            value={modal.form.bio}
            onChange={v=>setForm('bio',v)}
            rows={2}
            placeholder="Especialista em... com X anos de experiência."
          />
        </div>
      </Modal>

      {/* Confirm remove */}
      <ConfirmDialog
        open={confirm.open}
        onClose={() => setConfirm(c => ({ ...c, open:false }))}
        onConfirm={confirmRemove}
        title="Desativar profissional"
        message={confirm.prof ? `Tem certeza que deseja desativar ${confirm.prof.name}? Os atendimentos passados serão preservados, mas o profissional não aparecerá mais nas listas.` : ''}
        confirmLabel="Desativar"
        danger
      />
    </div>
  );
};

Object.assign(window, { Profissionais });
