"use client";
import useSWR from "swr";
import { useState } from "react";

const fetcher = (url: string) => fetch(url).then((r) => r.json());

export default function AdminBoardsPage() {
  const { data, mutate } = useSWR<{ boards: any[] }>("/api/admin/boards", fetcher);
  const boards = data?.boards ?? [];
  const [savingId, setSavingId] = useState<string | null>(null);
  async function save(b: any) {
    setSavingId(b.id);
    await fetch(`/api/admin/boards/${b.id}`, { method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify(b) });
    setSavingId(null);
    mutate();
  }
  return (
    <div>
      <h1>게시판 설정</h1>
      <table style={{ width: "100%", borderCollapse: "collapse" }}>
        <thead>
          <tr>
            <th>이름</th>
            <th>slug</th>
            <th>읽기</th>
            <th>쓰기</th>
            <th>익명</th>
            <th>비밀댓</th>
            <th>승인</th>
            <th>정렬</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          {boards.map((b) => (
            <Row key={b.id} b={b} onSave={save} saving={savingId === b.id} />
          ))}
        </tbody>
      </table>
    </div>
  );
}

function Row({ b, onSave, saving }: { b: any; onSave: (b: any) => void; saving: boolean }) {
  const [edit, setEdit] = useState(b);
  return (
    <tr>
      <td><input value={edit.name} onChange={(e) => setEdit({ ...edit, name: e.target.value })} /></td>
      <td><input value={edit.slug} onChange={(e) => setEdit({ ...edit, slug: e.target.value })} /></td>
      <td>
        <select value={edit.readLevel} onChange={(e) => setEdit({ ...edit, readLevel: e.target.value })}>
          <option value="public">public</option>
          <option value="member">member</option>
          <option value="moderator">moderator</option>
          <option value="admin">admin</option>
        </select>
      </td>
      <td>
        <select value={edit.writeLevel} onChange={(e) => setEdit({ ...edit, writeLevel: e.target.value })}>
          <option value="public">public</option>
          <option value="member">member</option>
          <option value="moderator">moderator</option>
          <option value="admin">admin</option>
        </select>
      </td>
      <td><input type="checkbox" checked={edit.allowAnonymousPost} onChange={(e) => setEdit({ ...edit, allowAnonymousPost: e.target.checked })} /></td>
      <td><input type="checkbox" checked={edit.allowSecretComment} onChange={(e) => setEdit({ ...edit, allowSecretComment: e.target.checked })} /></td>
      <td><input type="checkbox" checked={edit.requiresApproval} onChange={(e) => setEdit({ ...edit, requiresApproval: e.target.checked })} /></td>
      <td><input type="number" value={edit.sortOrder} onChange={(e) => setEdit({ ...edit, sortOrder: Number(e.target.value) })} style={{ width: 80 }} /></td>
      <td><button onClick={() => onSave(edit)} disabled={saving}>{saving ? "저장중" : "저장"}</button></td>
    </tr>
  );
}


