// CalendarPage.jsx
'use strict';
const { useState, useMemo } = React;

const MONTHS = ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];
const DAYS_SHORT = ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb'];
const TYPE_COLORS = { 'Visita técnica':'#3B82F6','Retirada':'#10B981','Entrega':'#FF6B35','Retorno':'#8B5CF6' };
const APPT_TYPES = Object.keys(TYPE_COLORS);
const HOURS = Array.from({length:11},(_,i)=>`${(i+8).toString().padStart(2,'0')}:00`);

function ApptModal({ open, onClose, onSave, editAppt, clients, selectedDate }) {
  const empty = { title:'', clientId:'', clientName:'', type:'Visita técnica', date: selectedDate||new Date().toISOString().split('T')[0], time:'09:00', duration:60, notes:'' };
  const [form, setForm] = useState(empty);
  const [errors, setErrors] = useState({});
  React.useEffect(()=>{ if(open){ setForm(editAppt?{...editAppt}:{...empty, date:selectedDate||empty.date}); setErrors({}); } },[open,editAppt,selectedDate]);
  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-3 gap-3">
          <FormField label="Data" required error={errors.date} className="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)}>
              {Array.from({length:20},(_,i)=>{const h=Math.floor(i*0.5)+8;const m=i%2===0?'00':'30';return`${String(h).padStart(2,'0')}:${m}`;}).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>
  );
}

function MonthView({ year, month, appointments, onDayClick, onApptClick, filterType }) {
  const firstDay = new Date(year, month, 1).getDay();
  const daysInMonth = new Date(year, month+1, 0).getDate();
  const today = new Date().toISOString().split('T')[0];
  const cells = [];
  for(let i=0;i<firstDay;i++) cells.push(null);
  for(let d=1;d<=daysInMonth;d++) cells.push(d);
  while(cells.length%7!==0) cells.push(null);

  const getAppts = d => {
    if(!d) return [];
    const dateStr = `${year}-${String(month+1).padStart(2,'0')}-${String(d).padStart(2,'0')}`;
    return appointments.filter(a=>a.date===dateStr && (!filterType||a.type===filterType));
  };

  return (
    <div>
      <div className="grid grid-cols-7 mb-1">
        {DAYS_SHORT.map(d=><div key={d} className="text-center text-xs font-semibold text-slate-400 py-2">{d}</div>)}
      </div>
      <div className="grid grid-cols-7 gap-1">
        {cells.map((d,i)=>{
          const dateStr = d ? `${year}-${String(month+1).padStart(2,'0')}-${String(d).padStart(2,'0')}` : '';
          const isToday = dateStr===today;
          const appts = getAppts(d);
          return (
            <div key={i} onClick={()=>d&&onDayClick(dateStr)}
              className={`min-h-24 rounded-xl p-1.5 border cursor-pointer transition-all ${d?'hover:border-blue-200 hover:bg-blue-50':'border-transparent bg-transparent'} ${isToday?'border-orange-300 bg-orange-50':'border-slate-100'}`}>
              {d&&<>
                <div className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-semibold mb-1 ${isToday?'text-white':'text-slate-600'}`}
                  style={isToday?{background:'#FF6B35'}:{}}>{d}</div>
                <div className="space-y-0.5">
                  {appts.slice(0,3).map(a=>(
                    <div key={a.id} onClick={e=>{e.stopPropagation();onApptClick(a);}}
                      className="calendar-event text-xs px-1.5 py-0.5 rounded-md font-medium truncate"
                      style={{background:a.color+'20',color:a.color}}>{a.time} {a.title}</div>
                  ))}
                  {appts.length>3&&<div className="text-xs text-slate-400 pl-1">+{appts.length-3}</div>}
                </div>
              </>}
            </div>
          );
        })}
      </div>
    </div>
  );
}

function WeekView({ weekStart, appointments, onSlotClick, onApptClick, filterType }) {
  const days = Array.from({length:7},(_,i)=>{ const d=new Date(weekStart); d.setDate(d.getDate()+i); return d; });
  const today = new Date().toISOString().split('T')[0];
  const getAppts = (d, hour) => {
    const ds = d.toISOString().split('T')[0];
    const h = String(hour).padStart(2,'0');
    return appointments.filter(a=>a.date===ds && a.time?.startsWith(h) && (!filterType||a.type===filterType));
  };
  return (
    <div className="overflow-x-auto">
      <div className="min-w-[600px]">
        <div className="grid grid-cols-8 border-b border-slate-100 mb-1">
          <div className="w-14"/>
          {days.map((d,i)=>{
            const ds = d.toISOString().split('T')[0];
            const isToday = ds===today;
            return (
              <div key={i} className="text-center py-2">
                <div className="text-xs text-slate-400">{DAYS_SHORT[d.getDay()]}</div>
                <div className={`w-7 h-7 mx-auto mt-0.5 rounded-full flex items-center justify-center text-sm font-bold ${isToday?'text-white':'text-slate-600'}`}
                  style={isToday?{background:'#FF6B35'}:{}}>{d.getDate()}</div>
              </div>
            );
          })}
        </div>
        {HOURS.map(h=>{
          const hour = parseInt(h);
          return (
            <div key={h} className="grid grid-cols-8 border-b border-slate-50">
              <div className="w-14 text-right pr-3 py-2 text-xs text-slate-400 self-start pt-1.5">{h}</div>
              {days.map((d,di)=>{
                const appts = getAppts(d, hour);
                const ds = d.toISOString().split('T')[0];
                return (
                  <div key={di} className="border-l border-slate-50 min-h-12 p-0.5 hover:bg-slate-50 cursor-pointer transition-colors"
                    onClick={()=>onSlotClick(ds, h)}>
                    {appts.map(a=>(
                      <div key={a.id} onClick={e=>{e.stopPropagation();onApptClick(a);}}
                        className="calendar-event text-xs px-1.5 py-0.5 rounded-md font-medium mb-0.5 truncate"
                        style={{background:a.color,color:'white'}}>{a.clientName?.split(' ')[0]||a.title}</div>
                    ))}
                  </div>
                );
              })}
            </div>
          );
        })}
      </div>
    </div>
  );
}

function ApptDetailModal({ open, onClose, appt, onEdit, onDelete, addToast }) {
  if (!appt) return null;
  const [confirm, setConfirm] = useState(false);
  return (
    <>
      <Modal open={open} onClose={onClose} title="Detalhes do Agendamento" width="max-w-sm">
        <div className="space-y-4">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0" style={{background:(TYPE_COLORS[appt.type]||'#94A3B8')+'20'}}>
              <Icon name="Calendar" size={18} color={TYPE_COLORS[appt.type]||'#94A3B8'}/>
            </div>
            <div>
              <p className="font-bold text-sm" style={{color:'#0A1F44'}}>{appt.title}</p>
              <p className="text-xs" style={{color:TYPE_COLORS[appt.type]}}>{appt.type}</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"/>{appt.clientName}</div>
            <div className="flex items-center gap-2 text-slate-600"><Icon name="Calendar" size={14} color="#94A3B8"/>{fmtDate(appt.date)} às {appt.time} ({appt.duration}min)</div>
            {appt.notes&&<div className="p-3 rounded-xl bg-slate-50 text-xs text-slate-600">{appt.notes}</div>}
          </div>
          <div className="flex gap-3 pt-2 border-t border-slate-100">
            <Btn variant="outline" onClick={onClose} className="mr-auto">Fechar</Btn>
            <Btn variant="ghost" icon="Trash2" onClick={()=>setConfirm(true)} className="text-red-500 hover:bg-red-50">Excluir</Btn>
            <Btn variant="ghost" icon="Edit" onClick={()=>{onClose();onEdit(appt);}}>Editar</Btn>
          </div>
        </div>
      </Modal>
      <ConfirmDialog open={confirm} onClose={()=>setConfirm(false)}
        onConfirm={()=>{onDelete(appt.id);addToast({type:'info',msg:'Agendamento excluído.'});onClose();}}
        message="Excluir este agendamento?"/>
    </>
  );
}

function CalendarPage({ appointments, clients, onAdd, onUpdate, onDelete, addToast }) {
  const today = new Date();
  const [viewMode, setViewMode] = useState('month');
  const [currentDate, setCurrentDate] = useState(today);
  const [showModal, setShowModal] = useState(false);
  const [editAppt, setEditAppt] = useState(null);
  const [detailAppt, setDetailAppt] = useState(null);
  const [selectedDate, setSelectedDate] = useState('');
  const [filterType, setFilterType] = useState('');

  const year = currentDate.getFullYear();
  const month = currentDate.getMonth();

  const getWeekStart = d => { const s=new Date(d); s.setDate(s.getDate()-s.getDay()); return s; };
  const weekStart = getWeekStart(currentDate);

  const navigate = dir => {
    const d = new Date(currentDate);
    if (viewMode==='month') d.setMonth(d.getMonth()+dir);
    else d.setDate(d.getDate()+dir*7);
    setCurrentDate(d);
  };

  const headerLabel = viewMode==='month'
    ? `${MONTHS[month]} ${year}`
    : `${weekStart.getDate()}/${weekStart.getMonth()+1} — ${new Date(weekStart.getTime()+6*86400000).getDate()}/${new Date(weekStart.getTime()+6*86400000).getMonth()+1}/${year}`;

  const handleDayClick = date => { setSelectedDate(date); setEditAppt(null); setShowModal(true); };
  const handleSlotClick = (date, time) => { setSelectedDate(date); setEditAppt(null); setShowModal(true); };
  const handleApptClick = a => setDetailAppt(a);

  const handleSave = form => {
    if (editAppt) { onUpdate(editAppt.id, form); addToast({type:'success',msg:'Agendamento atualizado!'}); }
    else { onAdd({...form, id:'AGD'+String(appointments.length+1).padStart(3,'0')}); addToast({type:'success',msg:'Agendamento criado!'}); }
  };

  const countByType = APPT_TYPES.reduce((acc,t)=>({...acc,[t]:appointments.filter(a=>a.type===t).length}),{});

  return (
    <div className="anim-fade">
      <PageHeader title="Agenda" subtitle={`${appointments.length} agendamentos`}
        action={<Btn icon="Plus" onClick={()=>{setEditAppt(null);setSelectedDate('');setShowModal(true);}}>Novo Agendamento</Btn>}/>

      <div className="flex flex-col lg:flex-row gap-4">
        {/* Sidebar filters */}
        <div className="lg:w-52 flex-shrink-0 space-y-3">
          <Card className="p-4">
            <p className="text-xs font-bold uppercase text-slate-400 mb-3">Filtrar por tipo</p>
            <div className="space-y-1">
              <button onClick={()=>setFilterType('')}
                className={`w-full flex items-center gap-2 px-3 py-2 rounded-xl text-sm font-medium transition-all ${!filterType?'text-white':'text-slate-500 hover:bg-slate-50'}`}
                style={!filterType?{background:'#0A1F44'}:{}}>
                <Icon name="LayoutDashboard" size={14} color={!filterType?'white':'#94A3B8'}/>
                <span>Todos</span>
                <span className="ml-auto text-xs opacity-60">{appointments.length}</span>
              </button>
              {APPT_TYPES.map(t=>(
                <button key={t} onClick={()=>setFilterType(filterType===t?'':t)}
                  className={`w-full flex items-center gap-2 px-3 py-2 rounded-xl text-sm font-medium transition-all ${filterType===t?'text-white':'text-slate-500 hover:bg-slate-50'}`}
                  style={filterType===t?{background:TYPE_COLORS[t]}:{}}>
                  <span className="w-2 h-2 rounded-full flex-shrink-0" style={{background:filterType===t?'white':TYPE_COLORS[t]}}/>
                  <span className="truncate">{t}</span>
                  <span className="ml-auto text-xs opacity-60">{countByType[t]||0}</span>
                </button>
              ))}
            </div>
          </Card>

          <Card className="p-4">
            <p className="text-xs font-bold uppercase text-slate-400 mb-3">Próximos 3 dias</p>
            {Array.from({length:3},(_,i)=>{
              const d=new Date(today); d.setDate(d.getDate()+i);
              const ds=d.toISOString().split('T')[0];
              const dayAppts=appointments.filter(a=>a.date===ds&&(!filterType||a.type===filterType));
              return (
                <div key={ds} className="mb-2">
                  <p className="text-xs font-semibold text-slate-500 mb-1">{i===0?'Hoje':i===1?'Amanhã':DAYS_SHORT[d.getDay()]+' '+d.getDate()}</p>
                  {dayAppts.length===0 ? <p className="text-xs text-slate-300 pl-1">—</p> :
                    dayAppts.map(a=><div key={a.id} className="text-xs px-2 py-1 rounded-lg mb-0.5 font-medium truncate" style={{background:a.color+'15',color:a.color}}>{a.time} {a.title}</div>)}
                </div>
              );
            })}
          </Card>
        </div>

        {/* Calendar */}
        <Card className="flex-1 p-5">
          <div className="flex items-center justify-between mb-5">
            <div className="flex items-center gap-2">
              <button onClick={()=>navigate(-1)} className="w-8 h-8 rounded-lg flex items-center justify-center hover:bg-slate-100 transition-colors">
                <Icon name="ChevronLeft" size={18} color="#64748b"/>
              </button>
              <h2 className="text-base font-bold capitalize" style={{color:'#0A1F44',minWidth:180,textAlign:'center'}}>{headerLabel}</h2>
              <button onClick={()=>navigate(1)} className="w-8 h-8 rounded-lg flex items-center justify-center hover:bg-slate-100 transition-colors">
                <Icon name="ChevronRight" size={18} color="#64748b"/>
              </button>
              <button onClick={()=>setCurrentDate(new Date())} className="ml-1 px-3 py-1.5 rounded-lg text-xs font-semibold text-slate-500 hover:bg-slate-100 transition-colors">Hoje</button>
            </div>
            <Tabs tabs={[{id:'month',label:'Mês'},{id:'week',label:'Semana'}]} active={viewMode} onChange={setViewMode}/>
          </div>
          {viewMode==='month'
            ? <MonthView year={year} month={month} appointments={appointments} onDayClick={handleDayClick} onApptClick={handleApptClick} filterType={filterType}/>
            : <WeekView weekStart={weekStart} appointments={appointments} onSlotClick={handleSlotClick} onApptClick={handleApptClick} filterType={filterType}/>
          }
        </Card>
      </div>

      <ApptModal open={showModal} onClose={()=>{setShowModal(false);setEditAppt(null);}} onSave={handleSave} editAppt={editAppt} clients={clients} selectedDate={selectedDate}/>
      <ApptDetailModal open={!!detailAppt} onClose={()=>setDetailAppt(null)} appt={detailAppt}
        onEdit={a=>{setEditAppt(a);setShowModal(true);setDetailAppt(null);}}
        onDelete={id=>{onDelete(id);setDetailAppt(null);}} addToast={addToast}/>
    </div>
  );
}

Object.assign(window, { CalendarPage });
