// ServicesPage.jsx
'use strict';
const { useState, useEffect } = React;

const SVC_CATS = ['Informática','Celular','Eletrônico','Geral','Outro'];
const CAT_COLORS = { Informática:'#3B82F6', Celular:'#10B981', Eletrônico:'#F59E0B', Geral:'#6366F1', Outro:'#94A3B8' };
const CAT_ICONS  = { Informática:'Laptop', Celular:'Smartphone', Eletrônico:'Tv', Geral:'Wrench', Outro:'Settings' };

function ServiceModal({ open, onClose, onSave, editSvc }) {
  const empty = { name:'', category:'Informática', description:'', basePrice:0, estimatedTime:60 };
  const [form, setForm] = useState(empty);
  const [errors, setErrors] = useState({});
  useEffect(()=>{ if(open){ setForm(editSvc?{...editSvc}:{...empty}); setErrors({}); } },[open,editSvc]);
  const set=(k,v)=>setForm(f=>({...f,[k]:v}));
  const validate=()=>{ const e={}; if(!form.name.trim())e.name='Nome obrigatório'; if(!form.basePrice)e.basePrice='Informe o valor'; setErrors(e); return Object.keys(e).length===0; };
  const handleSave=()=>{ if(!validate())return; onSave(form); onClose(); };
  return (
    <Modal open={open} onClose={onClose} title={editSvc?'Editar Serviço':'Novo Serviço'} width="max-w-md">
      <div className="space-y-4">
        <FormField label="Nome do serviço" required error={errors.name}>
          <Input value={form.name} onChange={e=>set('name',e.target.value)} placeholder="Ex: Formatação de PC" error={!!errors.name}/>
        </FormField>
        <div className="grid grid-cols-2 gap-4">
          <FormField label="Categoria">
            <Select value={form.category} onChange={e=>set('category',e.target.value)}>
              {SVC_CATS.map(c=><option key={c}>{c}</option>)}
            </Select>
          </FormField>
          <FormField label="Tempo estimado (min)">
            <Input type="number" min="0" value={form.estimatedTime} onChange={e=>set('estimatedTime',+e.target.value)} placeholder="60"/>
          </FormField>
        </div>
        <FormField label="Valor base (R$)" required error={errors.basePrice}>
          <Input type="number" min="0" step="0.01" value={form.basePrice} onChange={e=>set('basePrice',+e.target.value)} placeholder="0,00" error={!!errors.basePrice}/>
        </FormField>
        <FormField label="Descrição">
          <Textarea rows={3} value={form.description} onChange={e=>set('description',e.target.value)} placeholder="Descreva o serviço detalhadamente..."/>
        </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}>{editSvc?'Salvar alterações':'Cadastrar serviço'}</Btn>
        </div>
      </div>
    </Modal>
  );
}

// ── Service Detail Modal ────────────────────────────────────────────────────
function ServiceDetailModal({ open, onClose, service, workOrders, onEdit, onDelete }) {
  if (!service) return null;
  const cat = service.category;
  const catColor = CAT_COLORS[cat] || '#64748b';
  const catIcon = CAT_ICONS[cat] || 'Wrench';

  // Cruza com workOrders para calcular estatisticas de uso (match exato pelo nome do item)
  const stats = (() => {
    const matches = [];
    let totalRevenue = 0;
    let totalQty = 0;
    (workOrders || []).forEach(os => {
      (os.items || []).forEach(item => {
        if (item.desc === service.name) {
          matches.push({ os, item });
          totalRevenue += item.total || 0;
          totalQty += item.qty || 0;
        }
      });
    });
    matches.sort((a, b) => (b.os.entryDate || '').localeCompare(a.os.entryDate || ''));
    return { matches, totalRevenue, totalQty, count: matches.length };
  })();

  const hours = Math.floor((service.estimatedTime || 0) / 60);
  const mins  = (service.estimatedTime || 0) % 60;
  const timeLabel = hours > 0 ? (mins ? `${hours}h ${mins}min` : `${hours}h`) : `${mins}min`;

  return (
    <Modal open={open} onClose={onClose} title="Detalhes do Serviço" width="max-w-2xl" noPad>
      {/* Hero */}
      <div className="relative overflow-hidden px-7 pt-7 pb-6"
        style={{ background: `linear-gradient(135deg, ${catColor}10 0%, ${catColor}05 60%, transparent 100%)` }}>
        <div aria-hidden style={{
          position:'absolute', top:-60, right:-40, width:200, height:200, borderRadius:'50%',
          background:`radial-gradient(circle, ${catColor}25 0%, transparent 70%)`, pointerEvents:'none',
        }} />
        <div className="relative flex items-start gap-4">
          <div className="w-14 h-14 rounded-2xl flex items-center justify-center flex-shrink-0"
            style={{ background:`linear-gradient(135deg, ${catColor} 0%, ${catColor}cc 100%)`,
              boxShadow:`0 8px 20px -6px ${catColor}80, inset 0 1px 0 rgba(255,255,255,0.2)` }}>
            <Icon name={catIcon} size={26} color="white"/>
          </div>
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 flex-wrap mb-1.5">
              <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-bold"
                style={{ background:catColor+'20', color:catColor }}>
                <Icon name={catIcon} size={11} color={catColor}/>{cat}
              </span>
              <span className="text-[11px] text-slate-400 font-mono">#{service.id}</span>
            </div>
            <h2 className="text-xl font-bold leading-tight" style={{ color:'#0A1F44' }}>{service.name}</h2>
          </div>
        </div>
      </div>

      {/* Metric tiles */}
      <div className="px-7 -mt-3 grid grid-cols-2 gap-3 relative z-10">
        <div className="rounded-2xl p-4 bg-white border border-slate-100 shadow-card">
          <div className="text-[10px] font-bold uppercase text-slate-400 tracking-wider mb-1">Valor Base</div>
          <div className="text-2xl font-extrabold" style={{ color:'#FF6B35' }}>{fmtCurrency(service.basePrice)}</div>
        </div>
        <div className="rounded-2xl p-4 bg-white border border-slate-100 shadow-card">
          <div className="text-[10px] font-bold uppercase text-slate-400 tracking-wider mb-1">Tempo Estimado</div>
          <div className="flex items-center gap-2">
            <Icon name="Clock" size={18} color="#0A1F44"/>
            <span className="text-2xl font-extrabold" style={{ color:'#0A1F44' }}>{timeLabel}</span>
          </div>
        </div>
      </div>

      {/* Body */}
      <div className="p-7 pt-5 space-y-5">
        {/* Description */}
        {service.description && (
          <div>
            <div className="text-[10px] font-bold uppercase text-slate-400 tracking-wider mb-2">Descrição</div>
            <div className="rounded-xl p-4 text-sm leading-relaxed text-slate-600"
              style={{ background:'#F8FAFC', borderLeft:`3px solid ${catColor}` }}>{service.description}</div>
          </div>
        )}

        {/* Stats */}
        <div>
          <div className="text-[10px] font-bold uppercase text-slate-400 tracking-wider mb-2">Histórico de Uso</div>
          <div className="grid grid-cols-3 gap-3">
            <div className="rounded-xl p-3 bg-white border border-slate-100 text-center">
              <div className="text-[10px] font-semibold text-slate-400 uppercase mb-1">OSs</div>
              <div className="text-xl font-bold" style={{ color:'#0A1F44' }}>{stats.count}</div>
            </div>
            <div className="rounded-xl p-3 bg-white border border-slate-100 text-center">
              <div className="text-[10px] font-semibold text-slate-400 uppercase mb-1">Faturamento</div>
              <div className="text-xl font-bold" style={{ color:'#10B981' }}>{fmtCurrency(stats.totalRevenue)}</div>
            </div>
            <div className="rounded-xl p-3 bg-white border border-slate-100 text-center">
              <div className="text-[10px] font-semibold text-slate-400 uppercase mb-1">Unidades</div>
              <div className="text-xl font-bold" style={{ color:'#0A1F44' }}>{stats.totalQty}</div>
            </div>
          </div>
        </div>

        {/* Recent OSs */}
        {stats.matches.length > 0 ? (
          <div>
            <div className="flex items-center justify-between mb-2">
              <div className="text-[10px] font-bold uppercase text-slate-400 tracking-wider">Últimas Ordens de Serviço</div>
              {stats.matches.length > 5 && <span className="text-[10px] text-slate-400">mostrando 5 de {stats.matches.length}</span>}
            </div>
            <div className="rounded-xl border border-slate-100 overflow-hidden">
              {stats.matches.slice(0, 5).map(({ os, item }, i) => (
                <div key={`${os.id}-${i}`} className={`flex items-center gap-3 px-4 py-2.5 ${i > 0 ? 'border-t border-slate-50' : ''} hover:bg-slate-50 transition-colors`}>
                  <span className="font-mono text-xs font-bold flex-shrink-0" style={{ color:'#0A1F44' }}>#{os.num}</span>
                  <div className="flex-1 min-w-0">
                    <div className="text-sm font-medium text-slate-700 truncate">{os.clientName}</div>
                    <div className="text-[11px] text-slate-400">{fmtDate(os.entryDate)} • Qtd. {item.qty}</div>
                  </div>
                  <StatusBadge status={os.status} size="xs"/>
                  <span className="text-sm font-bold flex-shrink-0" style={{ color:'#FF6B35' }}>{fmtCurrency(item.total)}</span>
                </div>
              ))}
            </div>
          </div>
        ) : (
          <div className="rounded-xl p-6 text-center bg-slate-50 border border-dashed border-slate-200">
            <Icon name="FileText" size={20} color="#94A3B8" style={{ display:'inline-block', marginBottom:6 }}/>
            <div className="text-xs text-slate-500">Este serviço ainda não foi usado em nenhuma OS.</div>
          </div>
        )}

        {/* Actions */}
        <div className="flex gap-3 pt-3 border-t border-slate-100">
          <Btn variant="outline" onClick={onClose} className="mr-auto">Fechar</Btn>
          <Btn variant="ghost" icon="Trash2" onClick={() => { onDelete(service); onClose(); }}
            className="text-red-500 hover:bg-red-50">Excluir</Btn>
          <Btn icon="Edit" onClick={() => { onEdit(service); onClose(); }}>Editar Serviço</Btn>
        </div>
      </div>
    </Modal>
  );
}

function ServicesPage({ services, workOrders, onAdd, onUpdate, onDelete, addToast }) {
  const [search, setSearch] = useState('');
  const [catFilter, setCatFilter] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [editSvc, setEditSvc] = useState(null);
  const [detailSvc, setDetailSvc] = useState(null);
  const [confirm, setConfirm] = useState(null);
  const [loading, setLoading] = useState(true);
  useEffect(()=>{ const t=setTimeout(()=>setLoading(false),400); return()=>clearTimeout(t); },[]);

  const filtered = services.filter(s=>{
    const q=search.toLowerCase();
    const mQ=!q||s.name?.toLowerCase().includes(q)||s.description?.toLowerCase().includes(q);
    const mC=!catFilter||s.category===catFilter;
    return mQ&&mC;
  });

  const handleSave=form=>{
    if(editSvc){ onUpdate(editSvc.id,form); addToast({type:'success',msg:'Serviço atualizado!'}); }
    else{ onAdd({...form,id:'SVC'+String(services.length+1).padStart(3,'0')}); addToast({type:'success',msg:'Serviço cadastrado!'}); }
  };

  const cats = [...new Set(services.map(s=>s.category))];

  return (
    <div className="anim-fade">
      <PageHeader title="Catálogo de Serviços" subtitle={`${services.length} serviços cadastrados`}
        action={<Btn icon="Plus" onClick={()=>{setEditSvc(null);setShowModal(true);}}>Novo Serviço</Btn>}/>

      {/* Category filter */}
      <div className="flex flex-wrap gap-2 mb-4">
        <button onClick={()=>setCatFilter('')}
          className={`px-3 py-1.5 rounded-full text-xs font-semibold transition-all ${!catFilter?'text-white':'text-slate-500 bg-white border border-slate-200 hover:border-slate-300'}`}
          style={!catFilter?{background:'#0A1F44'}:{}}>Todas</button>
        {cats.map(c=>(
          <button key={c} onClick={()=>setCatFilter(catFilter===c?'':c)}
            className={`px-3 py-1.5 rounded-full text-xs font-semibold transition-all ${catFilter===c?'text-white border-transparent':'text-slate-500 bg-white border border-slate-200 hover:border-slate-300'}`}
            style={catFilter===c?{background:CAT_COLORS[c]||'#64748b'}:{}}>
            {c} <span className="opacity-60 ml-1">{services.filter(s=>s.category===c).length}</span>
          </button>
        ))}
      </div>

      <div className="mb-4"><SearchInput value={search} onChange={setSearch} placeholder="Buscar serviço..." className="max-w-xs"/></div>

      {/* Cards grid */}
      {loading ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {Array.from({length:6}).map((_,i)=><Card key={i} className="p-5"><Skeleton className="h-6 w-3/4 mb-3"/><Skeleton className="h-4 w-1/3 mb-4"/><Skeleton className="h-3 w-full mb-2"/><Skeleton className="h-3 w-2/3"/></Card>)}
        </div>
      ) : filtered.length===0 ? (
        <EmptyState icon="Wrench" title="Nenhum serviço encontrado" message="Cadastre serviços no catálogo para usá-los nas ordens de serviço." actionLabel="Novo Serviço" onAction={()=>setShowModal(true)}/>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filtered.map(s=>{
            const catColor = CAT_COLORS[s.category]||'#94A3B8';
            const catIcon = CAT_ICONS[s.category]||'Wrench';
            return (
              <Card key={s.id} onClick={()=>setDetailSvc(s)}
                className="p-5 group relative overflow-hidden transition-all hover:-translate-y-0.5 hover:shadow-card-md">
                {/* Decorative side accent */}
                <span aria-hidden style={{
                  position:'absolute', left:0, top:0, bottom:0, width:3,
                  background:`linear-gradient(180deg, ${catColor} 0%, ${catColor}40 100%)`,
                  opacity:0.6,
                }} />
                <div className="flex items-start gap-3 mb-3">
                  <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0 transition-transform group-hover:scale-105"
                    style={{ background:catColor+'15', color:catColor }}>
                    <Icon name={catIcon} size={18} color={catColor}/>
                  </div>
                  <div className="flex-1 min-w-0">
                    <h3 className="font-bold text-sm leading-snug line-clamp-2" style={{color:'#0A1F44'}}>{s.name}</h3>
                    <span className="inline-flex items-center mt-1 px-2 py-0.5 rounded-full text-[10px] font-semibold"
                      style={{background:catColor+'18',color:catColor}}>{s.category}</span>
                  </div>
                </div>
                {s.description && <p className="text-xs text-slate-500 leading-relaxed mb-4 line-clamp-2">{s.description}</p>}
                <div className="flex items-end justify-between pt-3 border-t border-slate-50">
                  <div className="text-[11px] text-slate-400 flex items-center gap-1">
                    <Icon name="Clock" size={11} color="#94A3B8"/>{s.estimatedTime}min
                  </div>
                  <div className="text-right">
                    <div className="text-lg font-extrabold leading-none" style={{color:'#FF6B35'}}>{fmtCurrency(s.basePrice)}</div>
                  </div>
                </div>
                {/* Hover hint */}
                <div className="absolute top-3 right-3 opacity-0 group-hover:opacity-100 transition-opacity">
                  <Icon name="ChevronDoubleRight" size={14} color={catColor}/>
                </div>
              </Card>
            );
          })}
        </div>
      )}

      <ServiceModal open={showModal} onClose={()=>{setShowModal(false);setEditSvc(null);}} onSave={handleSave} editSvc={editSvc}/>
      <ServiceDetailModal open={!!detailSvc} onClose={()=>setDetailSvc(null)} service={detailSvc} workOrders={workOrders}
        onEdit={s=>{setEditSvc(s);setShowModal(true);}}
        onDelete={s=>setConfirm(s.id)}/>
      <ConfirmDialog open={!!confirm} onClose={()=>setConfirm(null)}
        onConfirm={()=>{onDelete(confirm);addToast({type:'info',msg:'Serviço excluído.'});}}
        message="Excluir este serviço do catálogo?"/>
    </div>
  );
}

Object.assign(window, { ServicesPage });
