
// ============================================================
// JuFlow — Appointment Modal (New / Edit / Detail)
// ============================================================
const { useState: useStAM, useMemo: useMemoAM, useEffect: useEfAM } = React;
const UAM = window.JFUtils;

// ─── APPOINTMENT DETAIL MODAL ─────────────────────────────
const ApptDetailModal = ({ appt, onClose, onEdit, onCancel, addToast }) => {
  if (!appt) return null;
  const client  = UAM.getClient(appt.clientId);
  const service = UAM.getService(appt.serviceId);
  const prof    = UAM.getProfessional(appt.professionalId);
  const endTime = UAM.addMinutes(appt.datetime, appt.duration);

  const handleCancel = () => {
    onCancel(appt.id);
    addToast('Agendamento cancelado.', 'info');
    onClose();
  };

  return (
    <Modal open={!!appt} onClose={onClose} title="Detalhes do Agendamento" width={520}
      footer={<>
        <Button variant="secondary" icon="Edit2" onClick={() => { onEdit(appt); onClose(); }}>Editar</Button>
        {['confirmed','pending'].includes(appt.status) && (
          <Button variant="danger" icon="XCircle" onClick={handleCancel}>Cancelar</Button>
        )}
        <Button variant="primary" icon="Check" onClick={onClose}>Fechar</Button>
      </>}
    >
      <div style={{ display:'flex', flexDirection:'column', gap:20 }}>
        {/* Status banner */}
        <div style={{
          padding:'10px 14px', borderRadius:10,
          background: UAM.statusColor(appt.status).bg,
          border: `1px solid ${UAM.statusColor(appt.status).border}`,
          display:'flex', alignItems:'center', gap:8,
        }}>
          <Icon name={appt.status==='confirmed'?'CheckCircle':appt.status==='completed'?'CheckCircle2':'Clock'} size={16} color={UAM.statusColor(appt.status).text} />
          <span style={{ fontSize:13, fontWeight:700, color:UAM.statusColor(appt.status).text }}>
            {UAM.statusLabel(appt.status)}
          </span>
        </div>

        {/* Client + Professional */}
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
          <div style={{ background:'#F9FAFB', borderRadius:10, padding:'12px 14px' }}>
            <div style={{ fontSize:11, fontWeight:700, color:'#9CA3AF', textTransform:'uppercase', letterSpacing:.5, marginBottom:8 }}>Cliente</div>
            <div style={{ display:'flex', alignItems:'center', gap:8 }}>
              <Avatar name={client?.name} color="#0A1F44" size={32} />
              <div>
                <div style={{ fontSize:13, fontWeight:700, color:'#0A1F44' }}>{client?.name}</div>
                <div style={{ fontSize:11, color:'#6B7280' }}>{client?.phone}</div>
              </div>
            </div>
          </div>
          <div style={{ background:'#F9FAFB', borderRadius:10, padding:'12px 14px' }}>
            <div style={{ fontSize:11, fontWeight:700, color:'#9CA3AF', textTransform:'uppercase', letterSpacing:.5, marginBottom:8 }}>Profissional</div>
            <div style={{ display:'flex', alignItems:'center', gap:8 }}>
              <Avatar name={prof?.name} color={prof?.color} size={32} />
              <div>
                <div style={{ fontSize:13, fontWeight:700, color:'#0A1F44' }}>{prof?.name}</div>
                <div style={{ fontSize:11, color:'#6B7280' }}>{prof?.role}</div>
              </div>
            </div>
          </div>
        </div>

        {/* Service details */}
        <div style={{ background:'#F9FAFB', borderRadius:10, padding:'14px' }}>
          <div style={{ fontSize:11, fontWeight:700, color:'#9CA3AF', textTransform:'uppercase', letterSpacing:.5, marginBottom:10 }}>Serviço</div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:12 }}>
            {[
              { label:'Serviço', value:service?.name, icon:'Scissors' },
              { label:'Data', value:UAM.formatDate(appt.datetime,'dd/MM/yyyy'), icon:'Calendar' },
              { label:'Horário', value:`${UAM.formatTime(appt.datetime)} – ${UAM.formatTime(endTime)}`, icon:'Clock' },
              { label:'Duração', value:`${appt.duration} min`, icon:'Timer' },
              { label:'Valor', value:UAM.formatCurrency(appt.price), icon:'DollarSign' },
              { label:'Pagamento', value:appt.paymentMethod || '—', icon:'CreditCard' },
            ].map(item => (
              <div key={item.label}>
                <div style={{ fontSize:10, color:'#9CA3AF', marginBottom:3 }}>{item.label}</div>
                <div style={{ fontSize:13, fontWeight:600, color:'#0A1F44' }}>{item.value}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Session notes */}
        {appt.sessionNotes && (
          <div style={{ background:'#FFFBF0', border:'1px solid #FDE68A', borderRadius:10, padding:'12px 14px' }}>
            <div style={{ fontSize:11, fontWeight:700, color:'#92400E', textTransform:'uppercase', letterSpacing:.5, marginBottom:6 }}>Observações da sessão</div>
            <p style={{ fontSize:13, color:'#374151', margin:0, lineHeight:1.6 }}>{appt.sessionNotes}</p>
          </div>
        )}
      </div>
    </Modal>
  );
};

// ─── NEW / EDIT APPOINTMENT MODAL ─────────────────────────
const NewApptModal = ({ open, onClose, initial = {}, appointments, onSave, addToast }) => {
  const emptyForm = {
    clientId: '', serviceId: '', professionalId: '',
    date: UAM.formatDate(initial.datetime || window.JF.TODAY, 'yyyy-MM-dd'),
    time: initial.datetime ? UAM.formatTime(initial.datetime) : '09:00',
    status: 'confirmed', notes: '', paymentMethod: 'Pix',
  };

  const [form, setForm] = useStAM({ ...emptyForm });
  const [errors, setErrors] = useStAM({});
  const [clientSearch, setClientSearch] = useStAM('');
  const [showClientDD, setShowClientDD] = useStAM(false);

  useEfAM(() => {
    if (open) {
      setForm({
        ...emptyForm,
        date: UAM.formatDate(initial.datetime || window.JF.TODAY, 'yyyy-MM-dd'),
        time: initial.datetime ? UAM.formatTime(initial.datetime) : '09:00',
        clientId: initial.clientId || '',
        serviceId: initial.serviceId || '',
        professionalId: initial.professionalId || '',
        status: initial.status || 'confirmed',
      });
      setErrors({});
      if (initial.clientId) {
        const c = UAM.getClient(initial.clientId);
        setClientSearch(c?.name || '');
      } else setClientSearch('');
    }
  }, [open]);

  const set = (key, val) => setForm(f => ({ ...f, [key]:val }));

  const selectedService = useMemoAM(() => window.JF.SERVICES.find(s => s.id === Number(form.serviceId)), [form.serviceId]);
  const availableProfs  = useMemoAM(() => selectedService ? window.JF.PROFESSIONALS.filter(p => selectedService.professionals.includes(p.id)) : window.JF.PROFESSIONALS, [selectedService]);

  // Suggested available slots
  const suggestedSlots = useMemoAM(() => {
    if (!form.date) return [];
    const day  = new Date(form.date + 'T00:00:00');
    const dur  = selectedService?.duration || 60;
    const dayAppts = appointments.filter(a => UAM.isSameDay(a.datetime, day) && a.status !== 'cancelled');
    const slots = [];
    for (let h = 8; h <= 18; h++) {
      for (let m of [0, 30]) {
        const slotStart = h * 60 + m;
        const slotEnd   = slotStart + dur;
        const conflict  = dayAppts.some(a => {
          const as = UAM.minutesFromMidnight(a.datetime);
          const ae = as + a.duration;
          return !(slotEnd <= as || slotStart >= ae);
        });
        if (!conflict) {
          slots.push(`${String(h).padStart(2,'0')}:${String(m).padStart(2,'0')}`);
          if (slots.length >= 6) break;
        }
      }
      if (slots.length >= 6) break;
    }
    return slots;
  }, [form.date, form.serviceId, appointments]);

  const filteredClients = useMemoAM(() => {
    if (!clientSearch) return window.JF.CLIENTS.slice(0, 8);
    const q = clientSearch.toLowerCase();
    return window.JF.CLIENTS.filter(c => c.name.toLowerCase().includes(q) || c.phone.includes(q)).slice(0, 8);
  }, [clientSearch]);

  const validate = () => {
    const e = {};
    if (!form.clientId)       e.clientId = 'Selecione um cliente';
    if (!form.serviceId)      e.serviceId = 'Selecione um serviço';
    if (!form.professionalId) e.professionalId = 'Selecione um profissional';
    if (!form.date)           e.date = 'Informe a data';
    if (!form.time)           e.time = 'Informe o horário';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handleSave = (sendWhatsApp = false) => {
    if (!validate()) return;
    const svc = UAM.getService(Number(form.serviceId));
    const dt  = new Date(form.date + 'T' + form.time + ':00');
    const newAppt = {
      id: Date.now(),
      clientId: Number(form.clientId),
      serviceId: Number(form.serviceId),
      professionalId: Number(form.professionalId),
      datetime: dt.toISOString(),
      duration: svc?.duration || 60,
      price: svc?.price || 0,
      status: form.status,
      notes: form.notes,
      sessionNotes: '',
      paymentMethod: form.paymentMethod,
    };
    onSave(newAppt);
    addToast(sendWhatsApp ? 'Agendamento salvo e lembrete enviado pelo WhatsApp!' : 'Agendamento salvo com sucesso!', 'success');
    onClose();
  };

  return (
    <Modal open={open} onClose={onClose} title={initial.id ? 'Editar Agendamento' : 'Novo Agendamento'} width={600}
      footer={<>
        <Button variant="secondary" onClick={onClose}>Cancelar</Button>
        <Button variant="outline" icon="MessageCircle" onClick={() => handleSave(true)} style={{ color:'#25D366', borderColor:'#25D366' }}>
          Salvar e enviar WhatsApp
        </Button>
        <Button variant="primary" icon="Check" onClick={() => handleSave(false)}>Salvar</Button>
      </>}
    >
      <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
        {/* Client selector */}
        <div style={{ position:'relative' }}>
          <label style={{ fontSize:13, fontWeight:600, color:'#374151', display:'block', marginBottom:5 }}>
            Cliente <span style={{color:'#EF4444'}}>*</span>
          </label>
          <div style={{ position:'relative' }}>
            <input
              value={clientSearch}
              onChange={e => { setClientSearch(e.target.value); setShowClientDD(true); set('clientId',''); }}
              onFocus={() => setShowClientDD(true)}
              placeholder="Buscar cliente pelo nome ou telefone..."
              style={{
                width:'100%', boxSizing:'border-box',
                padding:'9px 12px 9px 34px', borderRadius:8, fontSize:13,
                border:`1.5px solid ${errors.clientId ? '#EF4444' : '#E2E8F0'}`,
                outline:'none', color:'#0A1F44',
              }}
            />
            <span style={{ position:'absolute', left:10, top:'50%', transform:'translateY(-50%)', pointerEvents:'none' }}>
              <Icon name="Search" size={14} color="#9CA3AF" />
            </span>
            {form.clientId && (
              <span style={{ position:'absolute', right:10, top:'50%', transform:'translateY(-50%)' }}>
                <Icon name="CheckCircle" size={14} color="#22C55E" />
              </span>
            )}
          </div>
          {errors.clientId && <span style={{ fontSize:11, color:'#EF4444' }}>{errors.clientId}</span>}

          {showClientDD && (
            <div style={{
              position:'absolute', top:'100%', left:0, right:0, zIndex:200,
              background:'#fff', borderRadius:10, border:'1px solid #E2E8F0',
              boxShadow:'0 8px 24px rgba(0,0,0,.1)', overflow:'hidden', maxHeight:220, overflowY:'auto',
            }}>
              {filteredClients.map(c => (
                <div key={c.id}
                  onClick={() => { setClientSearch(c.name); set('clientId', String(c.id)); setShowClientDD(false); }}
                  style={{
                    display:'flex', alignItems:'center', gap:10, padding:'9px 14px', cursor:'pointer', fontSize:13,
                  }}
                  onMouseEnter={e => e.currentTarget.style.background='#F9FAFB'}
                  onMouseLeave={e => e.currentTarget.style.background='#fff'}
                >
                  <Avatar name={c.name} color="#0A1F44" size={28} />
                  <div>
                    <div style={{ fontWeight:600, color:'#0A1F44' }}>{c.name}</div>
                    <div style={{ fontSize:11, color:'#9CA3AF' }}>{c.phone} · Última visita: {c.lastVisit ? UAM.formatDate(c.lastVisit) : '—'}</div>
                  </div>
                </div>
              ))}
              <div
                onClick={() => { setClientSearch('Novo Cliente'); set('clientId','new'); setShowClientDD(false); }}
                style={{
                  padding:'9px 14px', fontSize:13, color:'#FF6B35', fontWeight:600, cursor:'pointer',
                  borderTop:'1px solid #F0F4F8', display:'flex', alignItems:'center', gap:8,
                }}
                onMouseEnter={e => e.currentTarget.style.background='#FFF0EA'}
                onMouseLeave={e => e.currentTarget.style.background='#fff'}
              >
                <Icon name="UserPlus" size={14} color="#FF6B35" /> Cadastrar novo cliente
              </div>
            </div>
          )}
        </div>

        {/* Service + Professional */}
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
          <div>
            <label style={{ fontSize:13, fontWeight:600, color:'#374151', display:'block', marginBottom:5 }}>Serviço <span style={{color:'#EF4444'}}>*</span></label>
            <select value={form.serviceId} onChange={e => { set('serviceId',e.target.value); set('professionalId',''); }}
              style={{ width:'100%', padding:'9px 12px', borderRadius:8, fontSize:13, border:`1.5px solid ${errors.serviceId?'#EF4444':'#E2E8F0'}`, outline:'none', color:'#0A1F44', cursor:'pointer' }}>
              <option value=''>Selecione...</option>
              {window.JF.SERVICES.map(s => (
                <option key={s.id} value={s.id}>{s.name} · {s.duration}min · {UAM.formatCurrency(s.price)}</option>
              ))}
            </select>
            {errors.serviceId && <span style={{ fontSize:11, color:'#EF4444' }}>{errors.serviceId}</span>}
          </div>
          <div>
            <label style={{ fontSize:13, fontWeight:600, color:'#374151', display:'block', marginBottom:5 }}>Profissional <span style={{color:'#EF4444'}}>*</span></label>
            <select value={form.professionalId} onChange={e => set('professionalId',e.target.value)}
              style={{ width:'100%', padding:'9px 12px', borderRadius:8, fontSize:13, border:`1.5px solid ${errors.professionalId?'#EF4444':'#E2E8F0'}`, outline:'none', color:'#0A1F44', cursor:'pointer' }}>
              <option value=''>Selecione...</option>
              {availableProfs.map(p => (
                <option key={p.id} value={p.id}>{p.name} — {p.role}</option>
              ))}
            </select>
            {errors.professionalId && <span style={{ fontSize:11, color:'#EF4444' }}>{errors.professionalId}</span>}
          </div>
        </div>

        {/* Date + Time */}
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
          <Input label="Data" type="date" value={form.date} onChange={v => set('date',v)} required error={errors.date} icon="Calendar" />
          <div>
            <label style={{ fontSize:13, fontWeight:600, color:'#374151', display:'block', marginBottom:5 }}>Horário <span style={{color:'#EF4444'}}>*</span></label>
            <input type="time" value={form.time} onChange={e => set('time',e.target.value)}
              style={{ width:'100%', boxSizing:'border-box', padding:'9px 12px', borderRadius:8, fontSize:13, border:`1.5px solid ${errors.time?'#EF4444':'#E2E8F0'}`, outline:'none', color:'#0A1F44' }} />
            {suggestedSlots.length > 0 && (
              <div style={{ marginTop:6, display:'flex', gap:5, flexWrap:'wrap' }}>
                <span style={{ fontSize:11, color:'#9CA3AF', alignSelf:'center' }}>Disponíveis:</span>
                {suggestedSlots.map(slot => (
                  <button key={slot} onClick={() => set('time', slot)}
                    style={{
                      padding:'2px 8px', borderRadius:20, fontSize:11, fontWeight:600,
                      background: form.time===slot ? '#FF6B35' : '#F0FDF4',
                      color: form.time===slot ? '#fff' : '#15803D',
                      border:`1px solid ${form.time===slot ? '#FF6B35' : '#BBF7D0'}`,
                      cursor:'pointer',
                    }}>{slot}</button>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* Status + Payment */}
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
          <Select label="Status" value={form.status} onChange={v => set('status',v)}
            options={[
              {value:'confirmed',label:'Confirmado'},
              {value:'pending',label:'Pendente'},
              {value:'completed',label:'Realizado'},
              {value:'cancelled',label:'Cancelado'},
              {value:'no_show',label:'Falta'},
            ]} />
          <Select label="Forma de Pagamento" value={form.paymentMethod} onChange={v => set('paymentMethod',v)}
            options={[
              {value:'Pix',label:'Pix'},
              {value:'Cartão de Crédito',label:'Cartão de Crédito'},
              {value:'Cartão de Débito',label:'Cartão de Débito'},
              {value:'Dinheiro',label:'Dinheiro'},
              {value:'Pendente',label:'Pendente'},
            ]} />
        </div>

        {/* Notes */}
        <Textarea label="Observações" value={form.notes} onChange={v => set('notes',v)} placeholder="Informações adicionais sobre o agendamento..." rows={2} />

        {/* Summary */}
        {form.serviceId && form.date && form.time && (
          <div style={{ background:'#EFF6FF', border:'1px solid #BFDBFE', borderRadius:10, padding:'12px 14px', display:'flex', gap:16 }}>
            <Icon name="Info" size={15} color="#2563EB" style={{ marginTop:1, flexShrink:0 }} />
            <div style={{ fontSize:12, color:'#1D4ED8' }}>
              {selectedService && (<><strong>{selectedService.name}</strong> · {selectedService.duration}min · {UAM.formatCurrency(selectedService.price)}<br /></>)}
              {form.date && form.time && (<>Início: {UAM.formatDate(form.date+'T00:00','dd/MM/yyyy')} às {form.time} · Término previsto: {form.time && selectedService && (() => {
                const [h,m] = form.time.split(':').map(Number);
                const end = UAM.addMinutes(new Date(2026,0,1,h,m), selectedService.duration);
                return `${String(end.getHours()).padStart(2,'0')}:${String(end.getMinutes()).padStart(2,'0')}`;
              })()}</>)}
            </div>
          </div>
        )}
      </div>
    </Modal>
  );
};

Object.assign(window, { ApptDetailModal, NewApptModal });
