'use client';

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

import Link from 'next/link';

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

type GuideRow = {
  id: number;
  title: string;
  description: string | null;
  youtube_id: string;
};

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

  const load = useCallback(async () => {
    setError('');
    const res = await fetch('/api/admin/guide', { 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: GuideRow[] }).items ?? []);
    setLoading(false);
  }, []);

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

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

  async function save(row: GuideRow) {
    setError('');
    const res = await fetch(`/api/admin/guide/${row.id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({
        title: row.title,
        description: row.description ?? '',
        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 this entry?')) return;
    setError('');
    const res = await fetch(`/api/admin/guide/${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/guide', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ title, description, youtube_id: youtubeId }),
    });
    const data = await res.json().catch(() => ({}));
    if (!res.ok) {
      setError((data as { error?: string }).error ?? 'Create failed');
      return;
    }
    setTitle('');
    setDescription('');
    setYoutubeId('');
    await load();
  }

  return (
    <div className={style.card}>
      <p>
        <Link href="/admin">← Dashboard</Link>
      </p>
      <h1 className={style.title}>Guide</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}>
              description
              <textarea
                className={`${style.input} ${style.textarea}`}
                value={row.description ?? ''}
                onChange={(e) => updateLocal(row.id, { description: 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}>
          description
          <textarea
            className={`${style.input} ${style.textarea}`}
            value={description}
            onChange={(e) => setDescription(e.target.value)}
          />
        </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>
  );
}
