'use client';

import { useCallback, useEffect, useState } from 'react';

import Link from 'next/link';

import style from '@/styles/admin.module.scss';

type ArchiveRow = {
  id: number;
  title: string;
  youtube_id: string;
};

export function ArchiveAdminClient() {
  const [items, setItems] = useState<ArchiveRow[]>([]);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(true);
  const [title, setTitle] = useState('');
  const [youtubeId, setYoutubeId] = useState('');

  const load = useCallback(async () => {
    setError('');
    const res = await fetch('/api/admin/archive', { credentials: 'include' });
    const data = await res.json().catch(() => ({}));
    if (!res.ok) {
      setError((data as { error?: string }).error ?? 'Failed to load');
      setLoading(false);
      return;
    }
    setItems((data as { items: ArchiveRow[] }).items ?? []);
    setLoading(false);
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  function updateLocal(id: number, patch: Partial<ArchiveRow>) {
    setItems((prev) => prev.map((r) => (r.id === id ? { ...r, ...patch } : r)));
  }

  async function save(row: ArchiveRow) {
    setError('');
    const res = await fetch(`/api/admin/archive/${row.id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ title: row.title, youtube_id: row.youtube_id }),
    });
    const data = await res.json().catch(() => ({}));
    if (!res.ok) {
      setError((data as { error?: string }).error ?? 'Save failed');
      return;
    }
    await load();
  }

  async function remove(id: number) {
    if (!window.confirm('Delete?')) return;
    setError('');
    const res = await fetch(`/api/admin/archive/${id}`, { method: 'DELETE', credentials: 'include' });
    if (!res.ok) {
      const data = await res.json().catch(() => ({}));
      setError((data as { error?: string }).error ?? 'Delete failed');
      return;
    }
    await load();
  }

  async function add(e: React.FormEvent) {
    e.preventDefault();
    setError('');
    const res = await fetch('/api/admin/archive', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ title, youtube_id: youtubeId }),
    });
    const data = await res.json().catch(() => ({}));
    if (!res.ok) {
      setError((data as { error?: string }).error ?? 'Create failed');
      return;
    }
    setTitle('');
    setYoutubeId('');
    await load();
  }

  return (
    <div className={style.card}>
      <p>
        <Link href="/admin">← Dashboard</Link>
      </p>
      <h1 className={style.title}>Archive</h1>
      {error ? <p className={style.error}>{error}</p> : null}
      {loading ? <p>Loading…</p> : null}
      {!loading &&
        items.map((row) => (
          <div key={row.id} style={{ marginBottom: 24, paddingBottom: 16, borderBottom: '1px solid #eee' }}>
            <label className={style.label}>
              title
              <input
                className={style.input}
                value={row.title}
                onChange={(e) => updateLocal(row.id, { title: e.target.value })}
              />
            </label>
            <label className={style.label}>
              youtube_id
              <input
                className={style.input}
                value={row.youtube_id}
                onChange={(e) => updateLocal(row.id, { youtube_id: e.target.value })}
              />
            </label>
            <div className={style.rowActions}>
              <button type="button" className={style.btn} onClick={() => save(row)}>
                Save
              </button>
              <button type="button" className={style.btnDanger} onClick={() => remove(row.id)}>
                Delete
              </button>
            </div>
          </div>
        ))}

      <hr className={style.hr} />
      <h2 className={style.title} style={{ fontSize: '1.1rem' }}>
        New entry
      </h2>
      <form className={style.form} style={{ maxWidth: 480 }} onSubmit={add}>
        <label className={style.label}>
          title
          <input className={style.input} value={title} onChange={(e) => setTitle(e.target.value)} required />
        </label>
        <label className={style.label}>
          youtube_id
          <input className={style.input} value={youtubeId} onChange={(e) => setYoutubeId(e.target.value)} required />
        </label>
        <button className={style.btn} type="submit">
          Add
        </button>
      </form>
    </div>
  );
}
