/**
 * Admin view for technique pages — list with source/version counts,
 * expandable rows showing source videos, cross-links to pipeline admin.
 */

import React, { useCallback, useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { useDocumentTitle } from "../hooks/useDocumentTitle";
import {
  fetchAdminTechniquePages,
  fetchTechnique,
  type AdminTechniquePageItem,
  type SourceVideoSummary,
} from "../api";

// ── Helpers ──────────────────────────────────────────────────────────────────

function formatDate(iso: string | null): string {
  if (!iso) return "—";
  return new Date(iso).toLocaleString(undefined, {
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

function formatBadge(format: string): string {
  if (format === "v2_sections") return "v2";
  if (format === "v1_markdown") return "v1";
  return format;
}

// ── Main Component ───────────────────────────────────────────────────────────

export default function AdminTechniquePages() {
  useDocumentTitle("Admin — Technique Pages");

  // List state
  const [items, setItems] = useState<AdminTechniquePageItem[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Filters
  const [multiSourceOnly, setMultiSourceOnly] = useState(false);
  const [creatorFilter, setCreatorFilter] = useState("");
  const [sort, setSort] = useState("recent");

  // Expand state
  const [expandedSlug, setExpandedSlug] = useState<string | null>(null);
  const [expandedVideos, setExpandedVideos] = useState<SourceVideoSummary[]>([]);
  const [expandLoading, setExpandLoading] = useState(false);

  // Fetch list
  const fetchList = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await fetchAdminTechniquePages({
        multi_source_only: multiSourceOnly || undefined,
        creator: creatorFilter || undefined,
        sort,
        limit: 100,
      });
      setItems(data.items);
      setTotal(data.total);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setLoading(false);
    }
  }, [multiSourceOnly, creatorFilter, sort]);

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

  // Expand row — fetch technique detail for source videos
  const handleExpand = useCallback(
    async (slug: string) => {
      if (expandedSlug === slug) {
        setExpandedSlug(null);
        return;
      }
      setExpandedSlug(slug);
      setExpandLoading(true);
      try {
        const detail = await fetchTechnique(slug);
        setExpandedVideos(detail.source_videos ?? []);
      } catch {
        setExpandedVideos([]);
      } finally {
        setExpandLoading(false);
      }
    },
    [expandedSlug],
  );

  // Derived stats
  const uniqueCreators = new Set(items.map((i) => i.creator_slug)).size;

  return (
    <div className="admin-page">
      <div className="admin-page__header">
        <h1>Technique Pages</h1>
        <div className="admin-page__stats">
          <span className="admin-page__stat">{total} articles</span>
          <span className="admin-page__stat-sep">·</span>
          <span className="admin-page__stat">{uniqueCreators} creators</span>
        </div>
      </div>
      <p className="admin-page__description">
        Browse all synthesized technique pages. Filter by creator or multi-source status.
        Expand a row to see linked source videos and jump to pipeline details.
      </p>

      {/* Filter bar */}
      <div className="admin-page__filters">
        <label className="admin-page__checkbox">
          <input
            type="checkbox"
            checked={multiSourceOnly}
            onChange={(e) => setMultiSourceOnly(e.target.checked)}
          />
          Multi-source only
        </label>
        <input
          type="text"
          className="admin-page__search"
          placeholder="Filter by creator…"
          value={creatorFilter}
          onChange={(e) => setCreatorFilter(e.target.value)}
        />
        <select
          className="admin-page__select"
          value={sort}
          onChange={(e) => setSort(e.target.value)}
        >
          <option value="recent">Recent</option>
          <option value="alpha">A–Z</option>
          <option value="creator">By Creator</option>
        </select>
      </div>

      {error && <div className="admin-page__error">{error}</div>}

      {loading ? (
        <div className="admin-page__loading">Loading…</div>
      ) : items.length === 0 ? (
        <div className="admin-page__empty">No technique pages found.</div>
      ) : (
        <div className="admin-page__table-wrap">
          <table className="admin-page__table">
            <thead>
              <tr>
                <th></th>
                <th>Title</th>
                <th>Creator</th>
                <th>Category</th>
                <th>Format</th>
                <th>Sources</th>
                <th>Versions</th>
                <th>Updated</th>
              </tr>
            </thead>
            <tbody>
              {items.map((item) => (
                <React.Fragment key={item.id}>
                  <tr
                    className={`admin-page__row${expandedSlug === item.slug ? " admin-page__row--expanded" : ""}`}
                    onClick={() => handleExpand(item.slug)}
                    style={{ cursor: "pointer" }}
                  >
                    <td className="admin-page__expand-toggle">
                      {expandedSlug === item.slug ? "▾" : "▸"}
                    </td>
                    <td>
                      <Link
                        to={`/techniques/${item.slug}`}
                        onClick={(e) => e.stopPropagation()}
                        title="View public page"
                      >
                        {item.title}
                      </Link>
                    </td>
                    <td>
                      <Link
                        to={`/creators/${item.creator_slug}`}
                        onClick={(e) => e.stopPropagation()}
                      >
                        {item.creator_name}
                      </Link>
                    </td>
                    <td>{item.topic_category}</td>
                    <td>
                      <span
                        className={`pipeline-badge ${item.body_sections_format === "v2_sections" ? "pipeline-badge--success" : "pipeline-badge--pending"}`}
                      >
                        {formatBadge(item.body_sections_format)}
                      </span>
                    </td>
                    <td>{item.source_video_count}</td>
                    <td>{item.version_count}</td>
                    <td>{formatDate(item.updated_at)}</td>
                  </tr>
                  {expandedSlug === item.slug && (
                    <tr className="admin-page__detail-row">
                      <td colSpan={8}>
                        <div className="admin-page__detail-panel">
                          <div className="admin-page__detail-links">
                            <Link to={`/techniques/${item.slug}`}>
                              View public page →
                            </Link>
                          </div>
                          <h4>Source Videos</h4>
                          {expandLoading ? (
                            <p>Loading source videos…</p>
                          ) : expandedVideos.length === 0 ? (
                            <p className="admin-page__muted">
                              No source videos linked.
                            </p>
                          ) : (
                            <ul className="admin-page__source-list">
                              {expandedVideos.map((v) => (
                                <li key={v.id}>
                                  <Link
                                    to={`/admin/pipeline?video=${v.id}`}
                                    title="View in pipeline admin"
                                  >
                                    {v.filename}
                                  </Link>
                                  {v.added_at && (
                                    <span className="admin-page__muted">
                                      {" "}
                                      — added {formatDate(v.added_at)}
                                    </span>
                                  )}
                                </li>
                              ))}
                            </ul>
                          )}
                        </div>
                      </td>
                    </tr>
                  )}
                </React.Fragment>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
