'use client';

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

import Link from 'next/link';

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

type ContactRow = {
  id: number;
  question: string;
  answer: string;
};

export function QaAdminClient() {
  const [items, setItems] = useState<ContactRow[]>([]);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(true);
  const [question, setQuestion] = useState('');
  const [answer, setAnswer] = useState('');

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

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

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

  async function save(row: ContactRow) {
    setError('');
    const res = await fetch(`/api/admin/contact/${row.id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ question: row.question, answer: row.answer }),
    });
    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/contact/${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/contact', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ question, answer }),
    });
    const data = await res.json().catch(() => ({}));
    if (!res.ok) {
      setError((data as { error?: string }).error ?? 'Create failed');
      return;
    }
    setQuestion('');
    setAnswer('');
    await load();
  }

  return (
    <div className={style.card}>
      <p>
        <Link href="/admin">← Dashboard</Link>
      </p>
      <h1 className={style.title}>Q&amp;A</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}>
              question
              <textarea
                className={`${style.input} ${style.textarea}`}
                value={row.question}
                onChange={(e) => updateLocal(row.id, { question: e.target.value })}
              />
            </label>
            <label className={style.label}>
              answer
              <textarea
                className={`${style.input} ${style.textarea}`}
                value={row.answer}
                onChange={(e) => updateLocal(row.id, { answer: 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 Q&amp;A
      </h2>
      <form className={style.form} style={{ maxWidth: 480 }} onSubmit={add}>
        <label className={style.label}>
          question
          <textarea
            className={`${style.input} ${style.textarea}`}
            value={question}
            onChange={(e) => setQuestion(e.target.value)}
            required
          />
        </label>
        <label className={style.label}>
          answer
          <textarea
            className={`${style.input} ${style.textarea}`}
            value={answer}
            onChange={(e) => setAnswer(e.target.value)}
            required
          />
        </label>
        <button className={style.btn} type="submit">
          Add
        </button>
      </form>
    </div>
  );
}
