// CalendarPage.jsx — agenda da assistencia (usa o GCalendar, estilo Google Agenda)
'use strict';
const { useState, useMemo } = React;

const TYPE_COLORS = { 'Visita técnica':'#3B82F6','Retirada':'#10B981','Entrega':'#FF6B35','Retorno':'#8B5CF6' };
const APPT_TYPES = Object.keys(TYPE_COLORS);
const PRAZO_CAT = 'Prazo de OS';
const PRAZO_COLOR = '#E11D48';
const OS_FECHADAS = ['Concluída', 'Entregue'];
const APPT_TIMES = Array.from({ length: 26 }, (_, i) => `${String(7 + Math.floor(i / 2)).padStart(2, '0')}:${i % 2 ? '30' : '00'}`);
const CATEGORIES = [...APPT_TYPES.map(t => ({ id: t, label: t, color: TYPE_COLORS[t] })), { id: PRAZO_CAT, label: PRAZO_CAT, color: PRAZO_COLOR }];

function ApptModal({ open, onClose, onSave, editAppt, clients, slot }) {
  const blank = () => ({ title:'', clientId:'', clientName:'', type:'Visita técnica', date: slot?.date || gcIso(new Date()), time: slot?.time || '09:00', duration:60, notes:'' });
  const [form, setForm] = useState(blank);
  const [errors, setErrors] = useState({});
  React.useEffect(() => { if (open) { setForm(editAppt ? { ...editAppt } : blank()); setErrors({}); } }, [open, editAppt, slot]);
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const onClientChange = id => { const c = clients.find(x => x.id === id); setForm(f => ({ ...f, clientId:id, clientName:c?.name || '', title:`${f.type} — ${c?.name || ''}` })); };
  const onTypeChange = t => setForm(f => ({ ...f, type:t, title:`${t} — ${f.clientName}` }));
  const validate = () => { const e = {}; if (!form.clientId) e.clientId = 'Selecione o cliente'; if (!form.date) e.date = 'Informe a data'; setErrors(e); return Object.keys(e).length === 0; };
  const handleSave = () => { if (!validate()) return; onSave({ ...form, color: TYPE_COLORS[form.type] || '#64748b' }); onClose(); };
  return (
    <Modal open={open} onClose={onClose} title={editAppt ? 'Editar Agendamento' : 'Novo Agendamento'} width="max-w-md">
      <div className="space-y-4">
        <FormField label="Cliente" required error={errors.clientId}>
          <Select value={form.clientId} onChange={e => onClientChange(e.target.value)}>
            <option value="">Selecionar cliente...</option>
            {clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
          </Select>
        </FormField>
        <FormField label="Tipo de Agendamento">
          <div className="grid grid-cols-2 gap-2">
            {APPT_TYPES.map(t => (
              <button key={t} onClick={() => onTypeChange(t)}
                className="px-3 py-2 rounded-xl border text-sm font-medium transition-all text-left"
                style={{ borderColor: form.type === t ? TYPE_COLORS[t] : '#E2E8F0', background: form.type === t ? TYPE_COLORS[t] + '15' : 'white', color: form.type === t ? TYPE_COLORS[t] : '#64748b' }}>
                <span className="w-2 h-2 rounded-full inline-block mr-2" style={{ background: TYPE_COLORS[t] }}/>
                {t}
              </button>
            ))}
          </div>
        </FormField>
        <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
          <FormField label="Data" required error={errors.date} className="col-span-2 sm:col-span-1">
            <Input type="date" value={form.date} onChange={e => set('date', e.target.value)}/>
          </FormField>
          <FormField label="Horário">
            <Select value={form.time} onChange={e => set('time', e.target.value)}>
              {APPT_TIMES.map(t => <option key={t}>{t}</option>)}
            </Select>
          </FormField>
          <FormField label="Duração">
            <Select value={form.duration} onChange={e => set('duration', +e.target.value)}>
              {[30, 45, 60, 90, 120].map(d => <option key={d} value={d}>{d}min</option>)}
            </Select>
          </FormField>
        </div>
        <FormField label="Título / Descrição">
          <Input value={form.title} onChange={e => set('title', e.target.value)} placeholder="Descreva o agendamento..."/>
        </FormField>
        <FormField label="Observações">
          <Textarea rows={2} value={form.notes} onChange={e => set('notes', e.target.value)} placeholder="Informações adicionais..."/>
        </FormField>
        <div className="flex gap-3 pt-2 border-t border-slate-100">
          <Btn variant="outline" onClick={onClose} className="mr-auto">Cancelar</Btn>
          <Btn icon="Check" onClick={handleSave}>{editAppt ? 'Salvar' : 'Agendar'}</Btn>
        </div>
      </div>
    </Modal>
  );
}

// Detalhe de um evento: agendamento (editavel) ou prazo de OS (so leitura).
function EventDetailModal({ ev, onClose, onEdit, onDelete, addToast }) {
  const [confirm, setConfirm] = useState(false);
  if (!ev) return null;
  const isOS = ev.kind === 'os';
  const a = ev.ref;
  return (
    <>
      <Modal open onClose={onClose} title={isOS ? 'Prazo da Ordem de Serviço' : 'Detalhes do Agendamento'} width="max-w-sm">
        <div className="space-y-4">
          <div className="flex items-start gap-3">
            <span className="w-3.5 h-3.5 mt-1 rounded flex-shrink-0" style={{ background: ev.color }}/>
            <div className="min-w-0">
              <p className="font-bold text-base leading-snug" style={{ color:'#0A1F44' }}>{ev.title}</p>
              <p className="text-sm text-slate-500 mt-0.5">
                {fmtDate(ev.date)} · {ev.time ? `${ev.time} (${ev.duration}min)` : 'Dia inteiro'}
              </p>
            </div>
          </div>
          <div className="space-y-2 text-sm">
            <div className="flex items-center gap-2 text-slate-600"><Icon name="User" size={14} color="#94A3B8"/>{a.clientName}</div>
            {isOS
              ? <>
                  <div className="flex items-center gap-2 text-slate-600"><Icon name="Smartphone" size={14} color="#94A3B8"/>{a.equipment?.type} {a.equipment?.brand} {a.equipment?.model}</div>
                  <div className="flex items-center gap-2"><StatusBadge status={a.status}/></div>
                  {a.defect && <div className="p-3 rounded-xl bg-slate-50 text-xs text-slate-600">{a.defect}</div>}
                </>
              : <>
                  <div className="flex items-center gap-2 text-slate-600"><span className="w-2 h-2 rounded-full mx-1" style={{ background: ev.color }}/>{a.type}</div>
                  {a.osId && <div className="flex items-center gap-2 text-slate-600"><Icon name="FileText" size={14} color="#94A3B8"/>{a.osId}</div>}
                  {a.notes && <div className="p-3 rounded-xl bg-slate-50 text-xs text-slate-600">{a.notes}</div>}
                </>}
          </div>
          <div className="flex gap-2 pt-2 border-t border-slate-100">
            <Btn variant="outline" onClick={onClose} className="mr-auto">Fechar</Btn>
            {!isOS && <Btn variant="ghost" icon="Trash2" onClick={() => setConfirm(true)} className="text-red-500 hover:bg-red-50">Excluir</Btn>}
            {!isOS && <Btn variant="ghost" icon="Edit" onClick={() => { onClose(); onEdit(a); }}>Editar</Btn>}
          </div>
        </div>
      </Modal>
      <ConfirmDialog open={confirm} onClose={() => setConfirm(false)}
        onConfirm={() => { onDelete(a.id); addToast({ type:'info', msg:'Agendamento excluído.' }); onClose(); }}
        message="Excluir este agendamento?"/>
    </>
  );
}

// Proximos compromissos na lateral da agenda
function UpcomingList({ events, onEvent }) {
  const now = new Date();
  const todayIso = gcIso(now);
  const nowHHMM = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
  const upcoming = events
    .filter(e => e.time && (e.date > todayIso || (e.date === todayIso && e.time >= nowHHMM)))
    .sort((a, b) => (a.date + a.time).localeCompare(b.date + b.time))
    .slice(0, 4);
  return (
    <div className="bg-white rounded-2xl border border-slate-100 shadow-sm p-3">
      <p className="text-[11px] font-bold uppercase tracking-wide text-slate-400 px-1 mb-2">Próximos compromissos</p>
      {upcoming.length === 0 && <p className="text-xs text-slate-400 px-1 pb-1">Nenhum compromisso pela frente.</p>}
      {upcoming.map(e => (
        <button key={e.id} onClick={() => onEvent(e)} className="w-full flex gap-2.5 text-left px-1.5 py-2 rounded-lg hover:bg-slate-50">
          <span className="w-1 rounded-full flex-shrink-0" style={{ background: e.color }}/>
          <span className="min-w-0">
            <span className="block text-[13px] font-semibold text-slate-700 truncate">{e.title}</span>
            <span className="block text-[11.5px] text-slate-400">{e.date === todayIso ? 'Hoje' : fmtDate(e.date).slice(0, 5)} · {e.time}</span>
          </span>
        </button>
      ))}
    </div>
  );
}

function CalendarPage({ appointments, workOrders = [], clients, onAdd, onUpdate, onDelete, addToast }) {
  const [showModal, setShowModal] = useState(false);
  const [editAppt, setEditAppt] = useState(null);
  const [slot, setSlot] = useState(null);
  const [detail, setDetail] = useState(null);

  const events = useMemo(() => [
    ...appointments.map(a => ({
      id: a.id, date: a.date, time: a.time, duration: a.duration, title: a.title,
      subtitle: a.clientName, color: TYPE_COLORS[a.type] || a.color, category: a.type, kind: 'appt', ref: a,
    })),
    ...workOrders.filter(o => o.deadline && !OS_FECHADAS.includes(o.status)).map(o => ({
      id: 'prazo-' + o.id, date: o.deadline, time: null, title: `Prazo OS ${o.num}`,
      subtitle: `${o.clientName} · ${o.equipment?.type || ''}`, color: PRAZO_COLOR, category: PRAZO_CAT, kind: 'os', ref: o,
    })),
  ], [appointments, workOrders]);

  const todayIso = gcIso(new Date());
  const todayCount = appointments.filter(a => a.date === todayIso).length;

  const openCreate = s => { setSlot(s); setEditAppt(null); setShowModal(true); };
  const handleSave = form => {
    if (editAppt) { onUpdate(editAppt.id, form); addToast({ type:'success', msg:'Agendamento atualizado!' }); }
    else { onAdd({ ...form, id: nextId(appointments, 'AGD') }); addToast({ type:'success', msg:'Agendamento criado!' }); }
  };

  return (
    <div className="anim-fade">
      <PageHeader title="Agenda"
        subtitle={`${todayCount} ${todayCount === 1 ? 'compromisso' : 'compromissos'} hoje · ${appointments.length} agendamentos no total`}
        action={<div className="hidden sm:block lg:hidden"><Btn icon="Plus" onClick={() => openCreate(null)}>Novo Agendamento</Btn></div>}/>

      <GCalendar events={events} categories={CATEGORIES} createLabel="Novo agendamento"
        onCreate={openCreate} onEventClick={setDetail}
        asideExtra={<UpcomingList events={events} onEvent={setDetail}/>}/>

      <ApptModal open={showModal} onClose={() => { setShowModal(false); setEditAppt(null); }} onSave={handleSave}
        editAppt={editAppt} clients={clients} slot={slot}/>
      <EventDetailModal ev={detail} onClose={() => setDetail(null)}
        onEdit={a => { setEditAppt(a); setShowModal(true); }}
        onDelete={id => { onDelete(id); setDetail(null); }} addToast={addToast}/>
    </div>
  );
}

Object.assign(window, { CalendarPage });
