// Settings.jsx
'use strict';
const { useState } = React;

const PERMISSION_LEVELS = ['Administrador','Técnico','Atendente','Somente leitura'];

const MOCK_USERS = [
  { id:'U1', name:'Ademir Machado',    email:'demo@juflow.com',       role:'Administrador', active:true,  avatar:'AM' },
  { id:'U2', name:'Carlos Ferreira',   email:'carlos@juflow.com',     role:'Técnico',       active:true,  avatar:'CF' },
  { id:'U3', name:'Ana Paula Souza',   email:'ana.paula@juflow.com',  role:'Técnico',       active:true,  avatar:'AS' },
  { id:'U4', name:'Ricardo Alves',     email:'ricardo@juflow.com',    role:'Técnico',       active:true,  avatar:'RA' },
  { id:'U5', name:'Mariana Castro',    email:'mariana@juflow.com',    role:'Atendente',     active:false, avatar:'MC' },
];

const THEME_PRESETS = [
  { label:'JuFlow Original', primary:'#0A1F44', accent:'#FF6B35' },
  { label:'Oceano',          primary:'#0E4C8A', accent:'#00C4CC' },
  { label:'Floresta',        primary:'#1B4332', accent:'#40C057' },
  { label:'Pôr do Sol',      primary:'#6B2D4E', accent:'#F97316' },
];

function CompanyTab({ company, onSave, addToast }) {
  const [form, setForm] = useState(company);
  const [saved, setSaved] = useState(false);
  const set=(k,v)=>{setForm(f=>({...f,[k]:v}));setSaved(false);};
  const save=()=>{
    onSave(form);
    setSaved(true);
    if (addToast) addToast({ type:'success', msg:'Configurações salvas — refletem no PDF da OS.' });
  };
  return (
    <div className="space-y-5 max-w-2xl">
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <FormField label="Nome da Empresa" className="sm:col-span-2">
          <Input value={form.name} onChange={e=>set('name',e.target.value)}/>
        </FormField>
        <FormField label="CNPJ">
          <Input value={form.cnpj} onChange={e=>set('cnpj',e.target.value)} placeholder="00.000.000/0001-00"/>
        </FormField>
        <FormField label="Telefone">
          <Input value={form.phone} onChange={e=>set('phone',e.target.value)}/>
        </FormField>
        <FormField label="E-mail">
          <Input type="email" value={form.email} onChange={e=>set('email',e.target.value)}/>
        </FormField>
        <FormField label="Website">
          <Input value={form.website} onChange={e=>set('website',e.target.value)}/>
        </FormField>
        <FormField label="Endereço completo" className="sm:col-span-2">
          <Input value={form.address} onChange={e=>set('address',e.target.value)}/>
        </FormField>
        <FormField label="Termos e Condições (aparece no PDF da OS)" className="sm:col-span-2">
          <Textarea rows={3} value={form.terms} onChange={e=>set('terms',e.target.value)}/>
        </FormField>
      </div>
      <div className="flex items-center gap-3">
        <Btn icon="Save" onClick={save}>Salvar Configurações</Btn>
        {saved && <span className="flex items-center gap-1.5 text-sm text-emerald-600 font-medium"><Icon name="CheckCircle" size={15} color="#059669"/>Salvo com sucesso!</span>}
      </div>
    </div>
  );
}

function UsersTab() {
  const [users, setUsers] = useState(MOCK_USERS);
  const [showInvite, setShowInvite] = useState(false);
  const [inviteEmail, setInviteEmail] = useState('');
  const [inviteRole, setInviteRole] = useState('Técnico');
  const toggleUser=(id)=>setUsers(us=>us.map(u=>u.id===id?{...u,active:!u.active}:u));
  const invite=()=>{ setShowInvite(false); setInviteEmail(''); };
  const roleColor={'Administrador':'#0A1F44','Técnico':'#3B82F6','Atendente':'#10B981','Somente leitura':'#94A3B8'};
  return (
    <div className="max-w-2xl space-y-4">
      <div className="flex items-center justify-between">
        <p className="text-sm text-slate-500">{users.filter(u=>u.active).length} usuário(s) ativo(s)</p>
        <Btn icon="Plus" size="sm" onClick={()=>setShowInvite(v=>!v)}>Convidar Usuário</Btn>
      </div>
      {showInvite && (
        <Card className="p-4">
          <p className="text-sm font-semibold mb-3" style={{color:'#0A1F44'}}>Convidar novo usuário</p>
          <div className="grid grid-cols-2 gap-3 mb-3">
            <FormField label="E-mail"><Input type="email" value={inviteEmail} onChange={e=>setInviteEmail(e.target.value)} placeholder="usuario@email.com"/></FormField>
            <FormField label="Perfil de acesso"><Select value={inviteRole} onChange={e=>setInviteRole(e.target.value)}>{PERMISSION_LEVELS.map(p=><option key={p}>{p}</option>)}</Select></FormField>
          </div>
          <div className="flex gap-2"><Btn size="sm" icon="Check" onClick={invite}>Enviar convite</Btn><Btn size="sm" variant="ghost" onClick={()=>setShowInvite(false)}>Cancelar</Btn></div>
        </Card>
      )}
      <div className="space-y-2">
        {users.map(u=>(
          <Card key={u.id} className="p-4">
            <div className="flex items-center gap-4">
              <div className={`w-10 h-10 rounded-full flex items-center justify-center text-sm font-bold text-white flex-shrink-0 ${u.active?'':'opacity-40'}`}
                style={{background:roleColor[u.role]||'#64748b'}}>{u.avatar}</div>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 flex-wrap">
                  <span className={`font-semibold text-sm ${u.active?'text-slate-800':'text-slate-400'}`}>{u.name}</span>
                  <span className="text-xs px-2 py-0.5 rounded-full font-semibold"
                    style={{background:(roleColor[u.role]||'#94A3B8')+'18',color:roleColor[u.role]||'#94A3B8'}}>{u.role}</span>
                  {!u.active&&<span className="text-xs text-slate-300">Inativo</span>}
                </div>
                <p className="text-xs text-slate-400 mt-0.5">{u.email}</p>
              </div>
              {u.id!=='U1'&&(
                <button onClick={()=>toggleUser(u.id)}
                  className={`text-xs font-semibold px-3 py-1.5 rounded-lg transition-colors ${u.active?'text-red-500 hover:bg-red-50':'text-emerald-600 hover:bg-emerald-50'}`}>
                  {u.active?'Desativar':'Ativar'}
                </button>
              )}
            </div>
          </Card>
        ))}
      </div>
    </div>
  );
}

function AppearanceTab() {
  const [primary, setPrimary] = useState('#0A1F44');
  const [accent, setAccent] = useState('#FF6B35');
  const [preset, setPreset] = useState(0);
  const applyPreset=i=>{ const p=THEME_PRESETS[i]; setPrimary(p.primary); setAccent(p.accent); setPreset(i); };
  return (
    <div className="max-w-lg space-y-6">
      <div>
        <p className="text-sm font-semibold text-slate-600 mb-3">Temas Predefinidos</p>
        <div className="grid grid-cols-2 gap-3">
          {THEME_PRESETS.map((t,i)=>(
            <button key={i} onClick={()=>applyPreset(i)}
              className={`p-3 rounded-xl border-2 flex items-center gap-3 transition-all ${preset===i?'border-blue-400 bg-blue-50':' border-slate-200 hover:border-slate-300'}`}>
              <div className="flex gap-1.5">
                <span className="w-5 h-5 rounded-md" style={{background:t.primary}}/>
                <span className="w-5 h-5 rounded-md" style={{background:t.accent}}/>
              </div>
              <span className="text-xs font-semibold text-slate-600">{t.label}</span>
              {preset===i&&<Icon name="Check" size={13} color="#3B82F6" style={{marginLeft:'auto'}}/>}
            </button>
          ))}
        </div>
      </div>
      <div>
        <p className="text-sm font-semibold text-slate-600 mb-3">Personalização Manual</p>
        <div className="grid grid-cols-2 gap-4">
          <FormField label="Cor Primária">
            <div className="flex items-center gap-2">
              <input type="color" value={primary} onChange={e=>setPrimary(e.target.value)} className="w-10 h-10 rounded-xl border border-slate-200 cursor-pointer"/>
              <Input value={primary} onChange={e=>setPrimary(e.target.value)} className="font-mono text-sm"/>
            </div>
          </FormField>
          <FormField label="Cor de Destaque">
            <div className="flex items-center gap-2">
              <input type="color" value={accent} onChange={e=>setAccent(e.target.value)} className="w-10 h-10 rounded-xl border border-slate-200 cursor-pointer"/>
              <Input value={accent} onChange={e=>setAccent(e.target.value)} className="font-mono text-sm"/>
            </div>
          </FormField>
        </div>
      </div>
      {/* Live preview */}
      <div>
        <p className="text-sm font-semibold text-slate-600 mb-3">Preview ao Vivo</p>
        <Card className="p-4 overflow-hidden">
          <div className="flex gap-3 mb-3">
            <div className="w-24 rounded-xl flex flex-col p-3 gap-1" style={{background:primary,minHeight:100}}>
              <div className="w-6 h-6 rounded-lg flex items-center justify-center text-xs font-bold text-white mb-2" style={{background:accent}}>JF</div>
              {['Dashboard','OSs','Clientes'].map(n=><div key={n} className="text-xs rounded px-1.5 py-1 text-white opacity-60">{n}</div>)}
            </div>
            <div className="flex-1 space-y-2">
              <div className="h-6 rounded-lg" style={{background:primary+'15'}}/>
              <div className="grid grid-cols-2 gap-2">
                <div className="h-12 rounded-xl bg-white border border-slate-100 p-2"><div className="h-2 rounded w-3/4 mb-1 bg-slate-200"/><div className="h-3 rounded w-1/2" style={{background:accent+'50'}}/></div>
                <div className="h-12 rounded-xl bg-white border border-slate-100 p-2"><div className="h-2 rounded w-3/4 mb-1 bg-slate-200"/><div className="h-3 rounded w-1/2" style={{background:primary+'60'}}/></div>
              </div>
              <div className="h-7 rounded-xl flex items-center justify-center text-xs font-bold text-white" style={{background:accent}}>Botão de Ação</div>
            </div>
          </div>
        </Card>
      </div>
      <Btn icon="Save">Aplicar Tema</Btn>
    </div>
  );
}

function NotificationsTab() {
  const [prefs, setPrefs] = useState({
    osAtrasada:true, agendamento:true, contaVencer:true, osConcluida:true, emailDigest:false,
  });
  const toggle=k=>setPrefs(p=>({...p,[k]:!p[k]}));
  const items = [
    { key:'osAtrasada',  label:'OS com prazo vencido',           desc:'Alertar quando uma OS ultrapassar o prazo previsto' },
    { key:'agendamento', label:'Agendamento próximo',            desc:'Lembrete 1 hora antes do agendamento' },
    { key:'contaVencer', label:'Conta a receber vencendo',       desc:'Alertar sobre OSs com pagamento pendente há mais de 7 dias' },
    { key:'osConcluida', label:'OS concluída pelo técnico',      desc:'Notificar quando um técnico marcar uma OS como concluída' },
    { key:'emailDigest', label:'Resumo diário por e-mail',       desc:'Receber um e-mail com o resumo do dia todo manhã' },
  ];
  return (
    <div className="max-w-xl space-y-3">
      {items.map(item=>(
        <Card key={item.key} className="p-4">
          <div className="flex items-start gap-4">
            <div className="flex-1">
              <p className="text-sm font-semibold text-slate-700">{item.label}</p>
              <p className="text-xs text-slate-400 mt-0.5">{item.desc}</p>
            </div>
            <button onClick={()=>toggle(item.key)}
              className={`relative w-10 h-5.5 rounded-full transition-colors flex-shrink-0 mt-0.5 ${prefs[item.key]?'':'bg-slate-200'}`}
              style={{height:22,background:prefs[item.key]?'#FF6B35':'#E2E8F0'}}>
              <span className={`absolute top-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform ${prefs[item.key]?'translate-x-5':'translate-x-0.5'}`} style={{transitionDuration:'150ms'}}/>
            </button>
          </div>
        </Card>
      ))}
    </div>
  );
}

function Settings({ company, onSaveCompany, addToast }) {
  const [tab, setTab] = useState('empresa');
  const settingsTabs = [
    {id:'empresa',       label:'Empresa',       icon:'Building2'},
    {id:'usuarios',      label:'Usuários',      icon:'Users'},
    {id:'aparencia',     label:'Aparência',     icon:'Palette'},
    {id:'notificacoes',  label:'Notificações',  icon:'Bell'},
  ];
  return (
    <div className="anim-fade">
      <PageHeader title="Configurações" subtitle="Personalize o sistema conforme sua necessidade"/>
      <div className="flex flex-col lg:flex-row gap-6">
        {/* Tab sidebar */}
        <div className="lg:w-52 flex-shrink-0">
          <Card className="p-2">
            {settingsTabs.map(t=>(
              <button key={t.id} onClick={()=>setTab(t.id)}
                className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium transition-all mb-0.5 ${tab===t.id?'text-white':'text-slate-500 hover:bg-slate-50'}`}
                style={tab===t.id?{background:'#0A1F44'}:{}}>
                <Icon name={t.icon} size={16} color={tab===t.id?'#FF6B35':'#94A3B8'}/>
                {t.label}
              </button>
            ))}
          </Card>
        </div>
        {/* Content */}
        <Card className="flex-1 p-6">
          <h2 className="text-lg font-bold mb-5" style={{color:'#0A1F44'}}>{settingsTabs.find(t=>t.id===tab)?.label}</h2>
          {tab==='empresa'       && <CompanyTab company={company} onSave={onSaveCompany} addToast={addToast}/>}
          {tab==='usuarios'      && <UsersTab/>}
          {tab==='aparencia'     && <AppearanceTab/>}
          {tab==='notificacoes'  && <NotificationsTab/>}
        </Card>
      </div>
    </div>
  );
}

Object.assign(window, { Settings });
