import { useEffect, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Plus, Trash2, DatabaseBackup, Download } from 'lucide-react';
import { api, fmt } from '../api';
import { Card, Badge, Btn, Field, inputCls, Modal, Spinner, ErrorBox, Table } from '../components/ui';

const TABS = [
  { key: 'algemeen', label: 'Algemeen' },
  { key: 'gebruikers', label: 'Gebruikers' },
  { key: 'backups', label: 'Backups' },
  { key: 'audit', label: 'Audit-log' }
];

const ROLE_COLORS = { admin: 'accent', consultant: 'blue', viewer: 'muted' };
const ROLE_LABELS = { admin: 'Admin', consultant: 'Consultant', viewer: 'Viewer' };

const EMPTY_USER = { username: '', password: '', email: '', role: 'viewer' };

function Banner({ banner }) {
  if (!banner) return null;
  return (
    <div className={`rounded-lg px-4 py-3 text-[13px] border ${
      banner.type === 'green' ? 'bg-green/10 border-green/30 text-green' : 'bg-red/10 border-red/30 text-red'
    }`}>
      {banner.text}
    </div>
  );
}

// ============ Tab: Algemeen ============
function GeneralTab() {
  const [form, setForm] = useState(null);
  const [error, setError] = useState(null);
  const [saving, setSaving] = useState(false);
  const [banner, setBanner] = useState(null);

  const load = () => {
    setError(null);
    api.get('/settings').then(setForm).catch(setError);
  };
  useEffect(load, []);

  const save = async (e) => {
    e.preventDefault();
    setSaving(true);
    setBanner(null);
    try {
      await api.post('/settings', form);
      setBanner({ type: 'green', text: 'Instellingen opgeslagen' });
    } catch (err) {
      setBanner({ type: 'red', text: err.message || String(err) });
    } finally {
      setSaving(false);
    }
  };

  if (error) return <ErrorBox error={error} onRetry={load} />;
  if (!form) return <Spinner />;

  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  return (
    <Card title="Algemene instellingen">
      <form onSubmit={save} className="space-y-3 max-w-2xl">
        <Banner banner={banner} />
        <div className="grid grid-cols-2 gap-3">
          <Field label="Merknaam">
            <input className={inputCls} value={form.brand_name || ''} onChange={set('brand_name')} />
          </Field>
          <Field label="Taal">
            <select className={inputCls} value={form.language || 'nl'} onChange={set('language')}>
              <option value="nl">Nederlands</option>
              <option value="en">English</option>
            </select>
          </Field>
        </div>
        <div className="grid grid-cols-2 gap-3">
          <Field label="Thema">
            <input className={inputCls} value={form.theme || ''} onChange={set('theme')} />
          </Field>
          <Field label="Showcase URL">
            <input className={inputCls} value={form.showcase_url || ''} onChange={set('showcase_url')} />
          </Field>
        </div>
        <div className="grid grid-cols-3 gap-3">
          <Field label="Standaard pagina">
            <input className={inputCls} value={form.default_page || ''} onChange={set('default_page')} />
          </Field>
          <Field label="Auto-refresh">
            <select className={inputCls} value={String(form.auto_refresh ?? '0')} onChange={set('auto_refresh')}>
              <option value="0">Uit</option>
              <option value="1">Aan</option>
            </select>
          </Field>
          <Field label="Items per pagina">
            <input type="number" min="1" className={inputCls} value={form.items_per_page || ''} onChange={set('items_per_page')} />
          </Field>
        </div>
        <div className="text-[12px] text-muted font-medium pt-1">SMTP (uitgaande e-mail)</div>
        <div className="grid grid-cols-3 gap-3">
          <Field label="SMTP host" className="col-span-2">
            <input className={inputCls} value={form.smtp_host || ''} onChange={set('smtp_host')} />
          </Field>
          <Field label="SMTP poort">
            <input className={inputCls} value={form.smtp_port || ''} onChange={set('smtp_port')} />
          </Field>
        </div>
        <div className="grid grid-cols-2 gap-3">
          <Field label="SMTP gebruiker">
            <input className={inputCls} value={form.smtp_user || ''} onChange={set('smtp_user')} />
          </Field>
          <Field label="SMTP wachtwoord">
            <input type="password" className={inputCls} value={form.smtp_pass || ''} onChange={set('smtp_pass')} placeholder="••••••••" />
          </Field>
        </div>
        <Field label="Slack webhook">
          <input className={inputCls} value={form.slack_webhook || ''} onChange={set('slack_webhook')} />
        </Field>
        <div className="pt-1">
          <Btn type="submit" loading={saving}>Opslaan</Btn>
        </div>
      </form>
    </Card>
  );
}

// ============ Tab: Gebruikers ============
function UsersTab() {
  const [users, setUsers] = useState(null);
  const [error, setError] = useState(null);
  const [modal, setModal] = useState(false);
  const [editUser, setEditUser] = useState(null);
  const [form, setForm] = useState(EMPTY_USER);
  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState(null);

  const load = () => {
    setError(null);
    api.get('/users').then(setUsers).catch(setError);
  };
  useEffect(load, []);

  const openNew = () => {
    setEditUser(null);
    setForm(EMPTY_USER);
    setSaveError(null);
    setModal(true);
  };
  const openEdit = (u) => {
    setEditUser(u);
    setForm({ username: u.username, password: '', email: u.email || '', role: u.role || 'viewer' });
    setSaveError(null);
    setModal(true);
  };
  const save = async (e) => {
    e.preventDefault();
    if (!editUser && form.password.length < 6) {
      setSaveError(new Error('Wachtwoord moet minimaal 6 tekens zijn'));
      return;
    }
    setSaving(true);
    setSaveError(null);
    try {
      if (editUser) {
        await api.put(`/users/${editUser.id}`, { email: form.email, role: form.role, password: form.password || undefined });
      } else {
        await api.post('/users', form);
      }
      setModal(false);
      load();
    } catch (err) {
      setSaveError(err);
    } finally {
      setSaving(false);
    }
  };
  const remove = async () => {
    if (!editUser) return;
    if (!window.confirm(`Gebruiker "${editUser.username}" verwijderen?`)) return;
    setSaving(true);
    setSaveError(null);
    try {
      await api.del(`/users/${editUser.id}`);
      setModal(false);
      load();
    } catch (err) {
      setSaveError(err);
    } finally {
      setSaving(false);
    }
  };

  if (error) return <ErrorBox error={error} onRetry={load} />;
  if (!users) return <Spinner />;

  return (
    <Card
      title="Gebruikers"
      actions={<Btn size="sm" onClick={openNew}><Plus className="w-3.5 h-3.5" /> Nieuwe gebruiker</Btn>}
    >
      <Table
        columns={[
          { label: 'Username', render: u => <span className="font-medium">{u.username}</span> },
          { label: 'Email', render: u => <span className="text-muted">{u.email || '-'}</span> },
          { label: 'Rol', render: u => <Badge color={ROLE_COLORS[u.role] || 'muted'}>{ROLE_LABELS[u.role] || u.role}</Badge> },
          { label: 'Aangemaakt', render: u => <span className="text-muted">{fmt.date(u.created_at)}</span> }
        ]}
        rows={users}
        keyFn={u => u.id}
        onRowClick={openEdit}
      />

      <Modal open={modal} onClose={() => setModal(false)} title={editUser ? `Gebruiker "${editUser.username}" bewerken` : 'Nieuwe gebruiker'}>
        <form onSubmit={save} className="space-y-3">
          {saveError && <ErrorBox error={saveError} />}
          {!editUser && (
            <Field label="Gebruikersnaam *">
              <input className={inputCls} value={form.username} onChange={e => setForm({ ...form, username: e.target.value })} required />
            </Field>
          )}
          <Field label={editUser ? 'Nieuw wachtwoord (leeg = behouden)' : 'Wachtwoord * (min. 6 tekens)'}>
            <input
              type="password"
              className={inputCls}
              value={form.password}
              onChange={e => setForm({ ...form, password: e.target.value })}
              required={!editUser}
              minLength={editUser ? undefined : 6}
            />
          </Field>
          <Field label="Email">
            <input type="email" className={inputCls} value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} />
          </Field>
          <Field label="Rol">
            <select className={inputCls} value={form.role} onChange={e => setForm({ ...form, role: e.target.value })}>
              <option value="viewer">Viewer</option>
              <option value="consultant">Consultant</option>
              <option value="admin">Admin</option>
            </select>
          </Field>
          <div className="flex items-center justify-between gap-2 pt-1">
            <div>
              {editUser && (
                <Btn variant="danger" type="button" onClick={remove} loading={saving}>
                  <Trash2 className="w-3.5 h-3.5" /> Verwijderen
                </Btn>
              )}
            </div>
            <div className="flex gap-2">
              <Btn variant="secondary" type="button" onClick={() => setModal(false)}>Annuleren</Btn>
              <Btn type="submit" loading={saving}>Opslaan</Btn>
            </div>
          </div>
        </form>
      </Modal>
    </Card>
  );
}

// ============ Tab: Backups ============
function BackupsTab() {
  const [backups, setBackups] = useState(null);
  const [error, setError] = useState(null);
  const [creating, setCreating] = useState(false);
  const [banner, setBanner] = useState(null);

  const load = () => {
    setError(null);
    api.get('/backup').then(setBackups).catch(setError);
  };
  useEffect(load, []);

  const create = async () => {
    setCreating(true);
    setBanner(null);
    try {
      const res = await api.post('/backup/create');
      setBanner({ type: 'green', text: `Backup gemaakt: ${res.filename}` });
      load();
    } catch (err) {
      setBanner({ type: 'red', text: err.message || String(err) });
    } finally {
      setCreating(false);
    }
  };

  const remove = async (b) => {
    if (!window.confirm(`Backup "${b.filename}" verwijderen?`)) return;
    setBanner(null);
    try {
      await api.post(`/backup/delete/${encodeURIComponent(b.filename)}`);
      load();
    } catch (err) {
      setBanner({ type: 'red', text: err.message || String(err) });
    }
  };

  if (error) return <ErrorBox error={error} onRetry={load} />;
  if (!backups) return <Spinner />;

  return (
    <Card
      title="Backups"
      subtitle="Database- en bestandsbackups"
      actions={<Btn size="sm" onClick={create} loading={creating}><DatabaseBackup className="w-3.5 h-3.5" /> Backup maken</Btn>}
    >
      <div className="space-y-3">
        <Banner banner={banner} />
        <Table
          columns={[
            { label: 'Bestandsnaam', render: b => <span className="font-medium flex items-center gap-2"><Download className="w-3.5 h-3.5 text-muted" />{b.filename}</span> },
            { label: 'Grootte', render: b => <span className="text-muted">{b.sizeLabel || b.size || '-'}</span> },
            { label: 'Aangemaakt', render: b => <span className="text-muted">{fmt.datetime(b.created_at)}</span> },
            {
              label: '', className: 'text-right',
              render: b => (
                <button onClick={() => remove(b)} className="p-1.5 rounded-md text-muted hover:text-red hover:bg-red/10" title="Verwijderen">
                  <Trash2 className="w-3.5 h-3.5" />
                </button>
              )
            }
          ]}
          rows={backups}
          keyFn={b => b.filename}
          empty={<div className="text-center text-muted text-[13px] py-8">Nog geen backups</div>}
        />
      </div>
    </Card>
  );
}

// ============ Tab: Audit-log ============
function AuditTab() {
  const [page, setPage] = useState(1);
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  const load = () => {
    setError(null);
    api.get(`/audit?page=${page}`).then(setData).catch(setError);
  };
  useEffect(load, [page]);

  if (error) return <ErrorBox error={error} onRetry={load} />;
  if (!data) return <Spinner />;

  return (
    <Card title="Audit-log" subtitle={`${data.total} gebeurtenissen`}>
      <Table
        columns={[
          { label: 'Wanneer', render: r => <span className="text-muted whitespace-nowrap">{fmt.datetime(r.created_at)}</span> },
          { label: 'Gebruiker', render: r => r.username || '-' },
          { label: 'Actie', render: r => <Badge color="blue">{r.action}</Badge> },
          { label: 'Entiteit', render: r => <span className="text-muted">{[r.entity_type, r.entity_id].filter(v => v !== null && v !== undefined && v !== '').join(' #') || '-'}</span> },
          { label: 'Details', render: r => <span className="text-muted block max-w-sm truncate">{r.details || '-'}</span> }
        ]}
        rows={data.entries}
        keyFn={r => r.id}
        empty={<div className="text-center text-muted text-[13px] py-8">Nog geen activiteit</div>}
      />
      <div className="flex items-center justify-between pt-3 mt-1 border-t border-border-soft">
        <Btn variant="secondary" size="sm" disabled={page <= 1} onClick={() => setPage(p => p - 1)}>Vorige</Btn>
        <span className="text-[12px] text-muted">Pagina {data.page} van {data.totalPages || 1}</span>
        <Btn variant="secondary" size="sm" disabled={page >= (data.totalPages || 1)} onClick={() => setPage(p => p + 1)}>Volgende</Btn>
      </div>
    </Card>
  );
}

// ============ Settings-pagina ============
export default function Settings() {
  const [searchParams, setSearchParams] = useSearchParams();
  const tab = searchParams.get('tab') || 'algemeen';

  const setTab = (key) => setSearchParams({ tab: key });

  return (
    <div className="space-y-5 fade-in">
      <div>
        <h1 className="text-xl font-bold tracking-tight">Instellingen</h1>
        <p className="text-[13px] text-muted mt-0.5">Applicatie-instellingen, gebruikers, backups en audit-log</p>
      </div>

      <div className="flex gap-1 border-b border-border-soft">
        {TABS.map(t => (
          <button
            key={t.key}
            onClick={() => setTab(t.key)}
            className={`px-3.5 py-2 text-[13px] font-medium border-b-2 -mb-px transition-colors ${
              tab === t.key ? 'border-accent text-accent' : 'border-transparent text-muted hover:text-text'
            }`}
          >
            {t.label}
          </button>
        ))}
      </div>

      {tab === 'algemeen' && <GeneralTab />}
      {tab === 'gebruikers' && <UsersTab />}
      {tab === 'backups' && <BackupsTab />}
      {tab === 'audit' && <AuditTab />}
    </div>
  );
}
