const Appointments = ({ onOpenLead }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  const { data: appointments, loading } = useAppointments();
  const { data: leads } = useLeads();
  const createAppointment = useCreateAppointment();
  const deleteAppointment = useDeleteAppointment();
  const [modalOpen, setModalOpen] = React.useState(false);
  const [form, setForm] = React.useState({ leadId: '', title: '', date: '', time: '', description: '' });
  const { showToast } = useToast();

  const apptsArray = Array.isArray(appointments) ? appointments : [];
  const leadsArray = Array.isArray(leads) ? leads : (leads?.data || []);

  const handleCreate = async (e) => {
    e.preventDefault();
    if (!form.leadId || !form.title || !form.date || !form.time) {
      return showToast('Preencha os campos obrigatórios', 'error');
    }
    
    // Convert to Date
    const dateTime = new Date(`${form.date}T${form.time}:00`);
    
    try {
      await createAppointment({
        leadId: parseInt(form.leadId),
        title: form.title,
        date: dateTime.toISOString(),
        description: form.description
      });
      showToast('Compromisso agendado com sucesso!', 'success');
      setModalOpen(false);
      setForm({ leadId: '', title: '', date: '', time: '', description: '' });
    } catch (err) {
      showToast('Erro ao criar compromisso', 'error');
    }
  };

  const handleDelete = async (id) => {
    if (!confirm('Deseja cancelar e remover este compromisso?')) return;
    try {
      await deleteAppointment(id);
      showToast('Compromisso cancelado!', 'success');
    } catch (e) {
      showToast('Erro ao cancelar', 'error');
    }
  };

  const getGCalLink = (appt) => {
    const start = new Date(appt.date);
    const end = new Date(start.getTime() + 60 * 60 * 1000); // +1 hour
    const fmt = d => d.toISOString().replace(/-|:|\.\d\d\d/g, '');
    const title = encodeURIComponent(appt.title);
    const details = encodeURIComponent(`Compromisso com ${appt.lead?.name} (${appt.lead?.phone})\n\n${appt.description || ''}`);
    return `https://calendar.google.com/calendar/r/eventedit?text=${title}&dates=${fmt(start)}/${fmt(end)}&details=${details}`;
  };

  const getOutlookLink = (appt) => {
    const start = new Date(appt.date);
    const end = new Date(start.getTime() + 60 * 60 * 1000); // +1 hour
    const fmt = d => d.toISOString();
    const title = encodeURIComponent(appt.title);
    const details = encodeURIComponent(`Compromisso com ${appt.lead?.name} (${appt.lead?.phone})\n\n${appt.description || ''}`);
    return `https://outlook.live.com/calendar/0/deeplink/compose?subject=${title}&body=${details}&startdt=${fmt(start)}&enddt=${fmt(end)}`;
  };

  return (
    <div style={{ padding: 32, maxWidth: 1000, margin: '0 auto' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 24 }}>
        <div>
          <h1 style={{ fontSize: 28, fontFamily: t.fontDisplay, margin: 0, color: t.text }}>Compromissos</h1>
          <p style={{ margin: '4px 0 0', color: t.textMuted, fontSize: 14 }}>Acompanhe seus follow-ups e reuniões</p>
        </div>
        <Btn onClick={() => setModalOpen(true)} style={{ gap: 8 }}>
          <Icons.Plus size={16} />
          Agendar Novo
        </Btn>
      </div>

      <div style={{
        background: t.surface, borderRadius: t.radiusLg,
        border: `1px solid ${t.border}`, overflow: 'hidden',
        boxShadow: isBloom ? '6px 6px 0 0 #14131A' : '0 4px 20px rgba(0,0,0,0.2)',
      }}>
        {loading && <div style={{ padding: 40, textAlign: 'center', color: t.textMuted }}>Carregando compromissos...</div>}
        {!loading && apptsArray.length === 0 && <div style={{ padding: 40, textAlign: 'center', color: t.textMuted }}>Sua agenda está livre! Nenhum compromisso marcado.</div>}
        
        {!loading && apptsArray.length > 0 && (
          <table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left', fontSize: 13 }}>
            <thead>
              <tr style={{ borderBottom: `1px solid ${t.border}`, color: t.textMuted, fontFamily: t.fontMono, fontSize: 11 }}>
                <th style={{ padding: '16px 20px', fontWeight: 600 }}>DATA / HORA</th>
                <th style={{ padding: '16px 20px', fontWeight: 600 }}>COMPROMISSO</th>
                <th style={{ padding: '16px 20px', fontWeight: 600 }}>CLIENTE</th>
                <th style={{ padding: '16px 20px', fontWeight: 600, textAlign: 'right' }}>AÇÕES</th>
              </tr>
            </thead>
            <tbody>
              {apptsArray.map(appt => {
                const date = new Date(appt.date);
                const isPast = date < new Date();
                return (
                <tr key={appt.id} style={{ borderBottom: `1px solid ${t.border}`, background: 'transparent', opacity: isPast ? 0.6 : 1 }}>
                  <td style={{ padding: '16px 20px', color: t.text }}>
                    <div style={{ fontWeight: 600 }}>{date.toLocaleDateString()}</div>
                    <div style={{ color: t.textMuted, fontSize: 12 }}>{date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</div>
                  </td>
                  <td style={{ padding: '16px 20px' }}>
                    <div style={{ fontWeight: 600, color: t.text }}>{appt.title}</div>
                    {appt.description && <div style={{ color: t.textMuted, fontSize: 12, marginTop: 4 }}>{appt.description}</div>}
                  </td>
                  <td style={{ padding: '16px 20px', color: t.textMuted }}>
                    {appt.lead ? (
                      <span onClick={() => onOpenLead(appt.leadId)} style={{ cursor: 'pointer', color: t.primary, textDecoration: 'underline' }}>
                        {appt.lead.name}
                      </span>
                    ) : 'Lead Removido'}
                  </td>
                  <td style={{ padding: '16px 20px', textAlign: 'right', display: 'flex', gap: 8, justifyContent: 'flex-end', alignItems: 'center' }}>
                    <div style={{ display: 'flex', gap: 4, background: isBloom ? t.surfaceAlt : 'rgba(255,255,255,0.03)', padding: 4, borderRadius: t.radiusMd, border: `1px solid ${t.border}` }}>
                      <Btn variant="ghost" size="sm" onClick={() => window.open(getGCalLink(appt), '_blank')} style={{ padding: '4px 8px', color: t.text, fontSize: 11 }} title="Google Calendar">
                        Google
                      </Btn>
                      <Btn variant="ghost" size="sm" onClick={() => window.open(getOutlookLink(appt), '_blank')} style={{ padding: '4px 8px', color: t.text, fontSize: 11 }} title="Outlook">
                        Outlook
                      </Btn>
                      <Btn variant="ghost" size="sm" onClick={() => window.location.href = `/api/calendar/export/${appt.id}`} style={{ padding: '4px 8px', color: t.text, fontSize: 11 }} title="Apple Calendar (.ics)">
                        Apple
                      </Btn>
                    </div>
                    <Btn variant="ghost" size="sm" onClick={() => handleDelete(appt.id)} style={{ padding: '6px 10px', color: t.red }}>
                      Cancelar
                    </Btn>
                  </td>
                </tr>
              )})}
            </tbody>
          </table>
        )}
      </div>

      {modalOpen && (
        <div style={{
          position: 'fixed', inset: 0, zIndex: 9999,
          background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(4px)',
          display: 'flex', alignItems: 'center', justifyContent: 'center'
        }}>
          <div style={{
            background: t.surface, borderRadius: t.radiusLg,
            border: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
            width: 450, padding: 24, boxShadow: isBloom ? '8px 8px 0 0 #14131A' : '0 10px 40px -10px rgba(0,0,0,0.5)',
          }}>
            <h2 style={{ margin: '0 0 20px', fontSize: 18, fontFamily: t.fontDisplay, color: t.text }}>Agendar Compromisso</h2>
            <form onSubmit={handleCreate} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              
              <div>
                <label style={{ display: 'block', fontSize: 12, color: t.textMuted, marginBottom: 6 }}>Vincular a um Cliente</label>
                <select 
                  value={form.leadId} onChange={e => setForm({...form, leadId: e.target.value})}
                  style={{ width: '100%', padding: '10px 14px', background: 'transparent', border: `1px solid ${t.border}`, color: t.text, borderRadius: t.radiusMd, outline: 'none' }}
                >
                  <option value="" disabled style={{ background: t.surface, color: t.textMuted }}>Selecione um cliente...</option>
                  {leadsArray.map(l => <option key={l.id} value={l.id} style={{ background: t.surface, color: t.text }}>{l.name} ({l.phone})</option>)}
                </select>
              </div>

              <div>
                <label style={{ display: 'block', fontSize: 12, color: t.textMuted, marginBottom: 6 }}>Título da Reunião / Tarefa</label>
                <input 
                  type="text" required value={form.title} onChange={e => setForm({...form, title: e.target.value})} placeholder="Ex: Call de Alinhamento"
                  style={{ width: '100%', padding: '10px 14px', background: 'transparent', border: `1px solid ${t.border}`, color: t.text, borderRadius: t.radiusMd, outline: 'none' }}
                />
              </div>

              <div style={{ display: 'flex', gap: 12 }}>
                <div style={{ flex: 1 }}>
                  <label style={{ display: 'block', fontSize: 12, color: t.textMuted, marginBottom: 6 }}>Data</label>
                  <input 
                    type="date" required value={form.date} onChange={e => setForm({...form, date: e.target.value})}
                    style={{ width: '100%', padding: '10px 14px', background: 'transparent', border: `1px solid ${t.border}`, color: t.text, borderRadius: t.radiusMd, outline: 'none', colorScheme: 'dark' }}
                  />
                </div>
                <div style={{ flex: 1 }}>
                  <label style={{ display: 'block', fontSize: 12, color: t.textMuted, marginBottom: 6 }}>Hora</label>
                  <input 
                    type="time" required value={form.time} onChange={e => setForm({...form, time: e.target.value})}
                    style={{ width: '100%', padding: '10px 14px', background: 'transparent', border: `1px solid ${t.border}`, color: t.text, borderRadius: t.radiusMd, outline: 'none', colorScheme: 'dark' }}
                  />
                </div>
              </div>

              <div>
                <label style={{ display: 'block', fontSize: 12, color: t.textMuted, marginBottom: 6 }}>Descrição (Opcional)</label>
                <textarea 
                  rows={3} value={form.description} onChange={e => setForm({...form, description: e.target.value})} placeholder="Pauta ou anotações..."
                  style={{ width: '100%', padding: '10px 14px', background: 'transparent', border: `1px solid ${t.border}`, color: t.text, borderRadius: t.radiusMd, outline: 'none', resize: 'none' }}
                />
              </div>

              <div style={{ display: 'flex', gap: 12, marginTop: 8 }}>
                <Btn type="button" variant="ghost" onClick={() => setModalOpen(false)} style={{ flex: 1 }}>Cancelar</Btn>
                <Btn type="submit" style={{ flex: 1 }}>Agendar</Btn>
              </div>
            </form>
          </div>
        </div>
      )}

    </div>
  );
};

window.Appointments = Appointments;
