
// Events / Calendar Module

function Events() {
  const [view, setView] = React.useState('month');
  const [events, setEvents] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [selectedEvent, setSelectedEvent] = React.useState(null);
  const [addModal, setAddModal] = React.useState(false);
  const [form, setForm] = React.useState({ name: '', client: '', type: 'Corporativo', date: '2026-04-22', time: '09:00', location: '', budget: '' });
  const [toast, setToast] = React.useState(null);
  const showToast = (msg, type = 'success') => { setToast({ msg, type }); setTimeout(() => setToast(null), 3000); };

  const mapRow = (row) => {
    const d = row.event_date ? new Date(row.event_date + 'T00:00:00') : null;
    return {
      id: row.id,
      name: row.name,
      client: row.client_name,
      type: row.type,
      day: d ? d.getDate() : 1,
      month: d ? d.getMonth() + 1 : 1,
      time: row.event_time || '',
      duration: row.duration || '',
      color: row.color || '#3B82F6',
      status: row.status || 'Planejamento',
      team: row.team || [],
      budget: row.budget || 0,
      location: row.location || '',
    };
  };

  React.useEffect(() => {
    sb.from('events').select('*').order('event_date').then(({ data, error }) => {
      if (data) setEvents(data.map(mapRow));
      setLoading(false);
    });
  }, []);

  const addEvent = async () => {
    if (!form.name.trim()) return;
    const { data, error } = await sb.from('events').insert({
      name: form.name,
      client_name: form.client,
      type: form.type,
      event_date: form.date,
      event_time: form.time,
      duration: '1 dia',
      color: '#3B82F6',
      status: 'Planejamento',
      team: [],
      budget: parseFloat(form.budget) || 0,
      location: form.location,
    }).select().single();
    if (data) {
      setEvents(prev => [...prev, mapRow(data)]);
      showToast('Evento criado com sucesso!');
    } else {
      showToast('Erro ao criar evento', 'danger');
    }
    setAddModal(false);
    setForm({ name: '', client: '', type: 'Corporativo', date: '2026-04-22', time: '09:00', location: '', budget: '' });
  };

  const checklist = [
    { label: 'Confirmação do espaço', done: true },
    { label: 'Contratação de equipe técnica', done: true },
    { label: 'Briefing aprovado pelo cliente', done: true },
    { label: 'Decoração definida', done: false },
    { label: 'Sonorização contratada', done: false },
    { label: 'Transporte da equipe confirmado', done: false },
    { label: 'Montagem agendada', done: false },
  ];
  const [checks, setChecks] = React.useState(checklist);

  const typeColor = { 'Corporativo': '#3B82F6', 'Casamento': '#8B5CF6', 'Social': '#10B981', 'Institucional': '#F59E0B' };
  const statusVariant = { 'Confirmado': 'success', 'Planejamento': 'warning', 'Orçamento': 'default', 'Em andamento': 'primary' };

  const daysInMonth = 30;
  const startDay = 3;
  const today = 22;

  const getEventsForDay = (day) => events.filter(e => e.day === day && e.month === 4);

  const MonthView = () => (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 0 }}>
        {['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'].map(d => (
          <div key={d} style={{ padding: '10px 12px', fontSize: 11, fontWeight: 700, color: DS.colors.textMuted, textTransform: 'uppercase', letterSpacing: '0.06em', borderBottom: `1px solid ${DS.colors.border}` }}>{d}</div>
        ))}
        {Array.from({ length: startDay }).map((_, i) => (
          <div key={`empty-${i}`} style={{ minHeight: 100, background: '#FAFAFA', borderRight: `1px solid ${DS.colors.border}`, borderBottom: `1px solid ${DS.colors.border}` }} />
        ))}
        {Array.from({ length: daysInMonth }).map((_, i) => {
          const day = i + 1;
          const dayEvents = getEventsForDay(day);
          const isToday = day === today;
          return (
            <div key={day} style={{ minHeight: 100, borderRight: `1px solid ${DS.colors.border}`, borderBottom: `1px solid ${DS.colors.border}`, padding: 8, background: isToday ? '#EFF6FF' : '#fff' }}>
              <div style={{
                width: 24, height: 24, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 12, fontWeight: isToday ? 800 : 500,
                background: isToday ? DS.colors.primary : 'transparent',
                color: isToday ? '#fff' : DS.colors.text, marginBottom: 4,
              }}>{day}</div>
              {dayEvents.map(ev => (
                <div key={ev.id} onClick={() => setSelectedEvent(ev)}
                  style={{ background: ev.color, color: '#fff', borderRadius: 4, padding: '2px 6px', fontSize: 10, fontWeight: 600, marginBottom: 2, cursor: 'pointer', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
                  {ev.time} {ev.name}
                </div>
              ))}
            </div>
          );
        })}
      </div>
    </div>
  );

  const ListView = () => (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {events.sort((a, b) => a.day - b.day).map(ev => (
        <Card key={ev.id} hover onClick={() => setSelectedEvent(ev)} style={{ padding: '16px 20px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <div style={{ width: 4, borderRadius: 2, alignSelf: 'stretch', background: ev.color, flexShrink: 0 }} />
            <div style={{ width: 52, height: 52, borderRadius: DS.radius.sm, background: ev.color + '15', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <div style={{ fontSize: 20, fontWeight: 800, color: ev.color, lineHeight: 1 }}>{ev.day}</div>
              <div style={{ fontSize: 10, color: ev.color, fontWeight: 600 }}>ABR</div>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: DS.colors.text }}>{ev.name}</div>
              <div style={{ fontSize: 12, color: DS.colors.textSec, marginTop: 2 }}>{ev.client} · {ev.location}</div>
            </div>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              <Badge variant="default">{ev.type}</Badge>
              <Badge variant={statusVariant[ev.status] || 'default'}>{ev.status}</Badge>
              <div style={{ fontSize: 13, fontWeight: 700, color: DS.colors.text, minWidth: 90, textAlign: 'right' }}>R$ {ev.budget.toLocaleString('pt-BR')}</div>
            </div>
          </div>
        </Card>
      ))}
    </div>
  );

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 28 }}>
        <div>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: DS.colors.text, margin: 0, letterSpacing: '-0.02em' }}>Agenda de Eventos</h1>
          <p style={{ fontSize: 13, color: DS.colors.textSec, margin: '4px 0 0' }}>Abril 2026 · {events.length} eventos programados</p>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <div style={{ display: 'flex', gap: 2, background: '#F1F5F9', padding: 3, borderRadius: DS.radius.sm }}>
            {[['month', 'Mensal'], ['week', 'Semanal'], ['list', 'Lista']].map(([v, l]) => (
              <button key={v} onClick={() => setView(v)} style={{
                padding: '5px 12px', borderRadius: 6, border: 'none', fontSize: 12, fontWeight: 600, cursor: 'pointer',
                background: view === v ? '#fff' : 'transparent', color: view === v ? DS.colors.text : DS.colors.textSec,
                boxShadow: view === v ? DS.shadow.sm : 'none', transition: 'all 0.15s',
              }}>{l}</button>
            ))}
          </div>
          <Btn icon="plus" onClick={() => setAddModal(true)}>Novo evento</Btn>
        </div>
      </div>

      <Card>
        {loading ? <Spinner /> : (
          <>
            {(view === 'month' || view === 'week') && <MonthView />}
            {view === 'list' && <div style={{ padding: 20 }}><ListView /></div>}
          </>
        )}
      </Card>

      {/* Event detail modal */}
      <Modal open={!!selectedEvent} onClose={() => setSelectedEvent(null)} title={selectedEvent?.name || ''} width={600}>
        {selectedEvent && (
          <div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 20 }}>
              {[
                { label: 'Cliente', value: selectedEvent.client },
                { label: 'Data e hora', value: `${selectedEvent.day} Abr · ${selectedEvent.time}` },
                { label: 'Tipo', value: selectedEvent.type },
                { label: 'Local', value: selectedEvent.location },
                { label: 'Duração', value: selectedEvent.duration },
                { label: 'Status', value: selectedEvent.status },
              ].map(({ label, value }) => (
                <div key={label} style={{ padding: '12px 16px', background: '#F8FAFC', borderRadius: DS.radius.sm }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: DS.colors.textMuted, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 }}>{label}</div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: DS.colors.text }}>{value}</div>
                </div>
              ))}
            </div>
            <div style={{ marginBottom: 20 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: DS.colors.text, marginBottom: 12 }}>Equipe vinculada</div>
              {selectedEvent.team.length > 0 ? (
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  {selectedEvent.team.map(name => (
                    <div key={name} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 12px', background: '#F1F5F9', borderRadius: DS.radius.full }}>
                      <Avatar name={name} size={22} />
                      <span style={{ fontSize: 12, fontWeight: 600, color: DS.colors.text }}>{name}</span>
                    </div>
                  ))}
                </div>
              ) : <span style={{ fontSize: 12, color: DS.colors.textMuted }}>Nenhuma equipe vinculada ainda</span>}
            </div>
            <div>
              <div style={{ fontSize: 13, fontWeight: 700, color: DS.colors.text, marginBottom: 12 }}>Checklist</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {checks.map((c, i) => (
                  <div key={i} onClick={() => setChecks(ch => ch.map((item, idx) => idx === i ? { ...item, done: !item.done } : item))}
                    style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', borderRadius: DS.radius.sm, cursor: 'pointer', background: c.done ? DS.colors.successLight : '#F8FAFC', transition: 'background 0.15s' }}>
                    <div style={{ width: 18, height: 18, borderRadius: 4, border: `2px solid ${c.done ? DS.colors.success : DS.colors.border}`, background: c.done ? DS.colors.success : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, transition: 'all 0.15s' }}>
                      {c.done && <Icon name="check" size={11} color="#fff" />}
                    </div>
                    <span style={{ fontSize: 13, color: c.done ? DS.colors.success : DS.colors.text, textDecoration: c.done ? 'line-through' : 'none', fontWeight: c.done ? 400 : 500 }}>{c.label}</span>
                  </div>
                ))}
              </div>
              <div style={{ marginTop: 16, display: 'flex', gap: 8 }}>
                <Btn icon="briefcase" onClick={() => showToast('Indo para tarefas...')}>Ver tarefas</Btn>
                <Btn variant="secondary" icon="edit">Editar evento</Btn>
              </div>
            </div>
          </div>
        )}
      </Modal>

      {/* Add event modal */}
      <Modal open={addModal} onClose={() => setAddModal(false)} title="Novo Evento">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Input label="Nome do evento" value={form.name} onChange={v => setForm(f => ({ ...f, name: v }))} placeholder="Ex: Congresso Tech 2027" />
          <Input label="Cliente" value={form.client} onChange={v => setForm(f => ({ ...f, client: v }))} placeholder="Ex: TechCorp Brasil" />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Select label="Tipo" value={form.type} onChange={v => setForm(f => ({ ...f, type: v }))} options={[
              { value: 'Corporativo', label: 'Corporativo' },
              { value: 'Casamento', label: 'Casamento' },
              { value: 'Social', label: 'Social' },
              { value: 'Institucional', label: 'Institucional' },
            ]} />
            <Input label="Horário" value={form.time} onChange={v => setForm(f => ({ ...f, time: v }))} placeholder="09:00" />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Input label="Data" value={form.date} onChange={v => setForm(f => ({ ...f, date: v }))} type="date" />
            <Input label="Orçamento (R$)" value={form.budget} onChange={v => setForm(f => ({ ...f, budget: v }))} placeholder="Ex: 50000" type="number" />
          </div>
          <Input label="Local" value={form.location} onChange={v => setForm(f => ({ ...f, location: v }))} placeholder="Ex: Centro de Convenções SP" />
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>
            <Btn variant="secondary" onClick={() => setAddModal(false)}>Cancelar</Btn>
            <Btn onClick={addEvent}>Criar evento</Btn>
          </div>
        </div>
      </Modal>

      {toast && <Toast message={toast.msg} type={toast.type} onClose={() => setToast(null)} />}
    </div>
  );
}

Object.assign(window, { Events });
