import { useCallback, useEffect, useState } from "react";
import { SidebarNav } from "./CreatorDashboard";
import { ApiError } from "../api/client";
import {
  fetchCreatorHighlights,
  fetchHighlightDetail,
  updateHighlightStatus,
  trimHighlight,
  type HighlightCandidate,
  type ScoreBreakdown,
} from "../api/highlights";
import { useDocumentTitle } from "../hooks/useDocumentTitle";
import styles from "./HighlightQueue.module.css";

/* ── Helpers ────────────────────────────────────────────────────────────────── */

function formatDuration(secs: number): string {
  const m = Math.floor(secs / 60);
  const s = Math.floor(secs % 60);
  return `${m}:${s.toString().padStart(2, "0")}`;
}

function statusBadgeClass(status: string): string {
  switch (status) {
    case "approved":
      return styles.badgeApproved ?? "";
    case "rejected":
      return styles.badgeRejected ?? "";
    default:
      return styles.badgeCandidate ?? "";
  }
}

const BREAKDOWN_LABELS: { key: keyof ScoreBreakdown; label: string }[] = [
  { key: "duration_score", label: "Duration" },
  { key: "content_density_score", label: "Content Density" },
  { key: "technique_relevance_score", label: "Technique" },
  { key: "position_score", label: "Position" },
  { key: "uniqueness_score", label: "Uniqueness" },
  { key: "engagement_proxy_score", label: "Engagement" },
  { key: "plugin_diversity_score", label: "Plugin Diversity" },
];

type FilterTab = "all" | "shorts" | "approved" | "rejected";

/* ── Component ──────────────────────────────────────────────────────────────── */

export default function HighlightQueue() {
  useDocumentTitle("Highlight Queue");

  const [highlights, setHighlights] = useState<HighlightCandidate[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<FilterTab>("all");
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [trimStart, setTrimStart] = useState<string>("");
  const [trimEnd, setTrimEnd] = useState<string>("");
  const [actionLoading, setActionLoading] = useState<string | null>(null);

  const loadHighlights = useCallback(async (tab: FilterTab) => {
    setLoading(true);
    setError(null);
    try {
      const params: { status?: string; shorts_only?: boolean } = {};
      if (tab === "shorts") params.shorts_only = true;
      else if (tab === "approved") params.status = "approved";
      else if (tab === "rejected") params.status = "rejected";

      const res = await fetchCreatorHighlights(params);
      setHighlights(res.highlights);
    } catch (err) {
      setError(err instanceof ApiError ? err.detail : "Failed to load highlights");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadHighlights(activeTab);
  }, [activeTab, loadHighlights]);

  const handleTabChange = (tab: FilterTab) => {
    setActiveTab(tab);
    setExpandedId(null);
  };

  const handleApprove = async (id: string) => {
    setActionLoading(id);
    try {
      await updateHighlightStatus(id, "approved");
      await loadHighlights(activeTab);
    } catch (err) {
      setError(err instanceof ApiError ? err.detail : "Failed to update status");
    } finally {
      setActionLoading(null);
    }
  };

  const handleReject = async (id: string) => {
    setActionLoading(id);
    try {
      await updateHighlightStatus(id, "rejected");
      await loadHighlights(activeTab);
    } catch (err) {
      setError(err instanceof ApiError ? err.detail : "Failed to update status");
    } finally {
      setActionLoading(null);
    }
  };

  const handleToggleTrim = async (h: HighlightCandidate) => {
    if (expandedId === h.id) {
      setExpandedId(null);
      return;
    }
    // Fetch full detail to get score_breakdown
    try {
      const detail = await fetchHighlightDetail(h.id);
      setHighlights((prev) =>
        prev.map((x) => (x.id === h.id ? detail : x)),
      );
    } catch {
      // non-critical — proceed with what we have
    }
    setExpandedId(h.id);
    setTrimStart(
      h.trim_start != null
        ? String(h.trim_start)
        : h.key_moment
          ? String(h.key_moment.start_time)
          : "0",
    );
    setTrimEnd(
      h.trim_end != null
        ? String(h.trim_end)
        : h.key_moment
          ? String(h.key_moment.end_time)
          : "0",
    );
  };

  const handleSaveTrim = async (id: string) => {
    const start = parseFloat(trimStart);
    const end = parseFloat(trimEnd);
    if (isNaN(start) || isNaN(end) || start >= end || start < 0) {
      setError("Invalid trim values — start must be less than end, both ≥ 0");
      return;
    }
    setActionLoading(id);
    try {
      await trimHighlight(id, start, end);
      setExpandedId(null);
      await loadHighlights(activeTab);
    } catch (err) {
      setError(err instanceof ApiError ? err.detail : "Failed to save trim");
    } finally {
      setActionLoading(null);
    }
  };

  const tabs: { key: FilterTab; label: string }[] = [
    { key: "all", label: "All" },
    { key: "shorts", label: "Shorts" },
    { key: "approved", label: "Approved" },
    { key: "rejected", label: "Rejected" },
  ];

  return (
    <div className={styles.layout}>
      <SidebarNav />
      <div className={styles.content}>
        <h1 className={styles.pageTitle}>Highlight Queue</h1>
        <p className={styles.subtitle}>Review, trim, and approve auto-detected highlights</p>

        {/* Filter tabs */}
        <div className={styles.filterTabs}>
          {tabs.map((t) => (
            <button
              key={t.key}
              className={`${styles.filterTab}${activeTab === t.key ? ` ${styles.filterTabActive}` : ""}`}
              onClick={() => handleTabChange(t.key)}
            >
              {t.label}
            </button>
          ))}
        </div>

        {/* Error */}
        {error && <div className={styles.errorState}>{error}</div>}

        {/* Loading */}
        {loading && <div className={styles.loadingState}>Loading highlights…</div>}

        {/* Empty */}
        {!loading && !error && highlights.length === 0 && (
          <div className={styles.emptyState}>
            <h2>No highlights found</h2>
            <p>
              {activeTab === "all"
                ? "No highlight candidates have been detected yet."
                : `No ${activeTab === "shorts" ? "short (≤ 60 s)" : activeTab} highlights.`}
            </p>
          </div>
        )}

        {/* Candidate list */}
        {!loading && highlights.length > 0 && (
          <div className={styles.candidateList}>
            {highlights.map((h) => (
              <div key={h.id} className={styles.candidateCard}>
                {/* Header */}
                <div className={styles.candidateHeader}>
                  <span className={styles.candidateTitle}>
                    {h.key_moment?.title ?? "Untitled highlight"}
                  </span>
                  <span className={styles.candidateDuration}>
                    {formatDuration(h.duration_secs)}
                  </span>
                  {h.duration_secs <= 60 && (
                    <span className={styles.shortsBadge}>Short</span>
                  )}
                  <span className={`${styles.badge} ${statusBadgeClass(h.status)}`}>
                    {h.status}
                  </span>
                </div>

                {/* Composite score */}
                <div className={styles.compositeScore}>
                  <span className={styles.compositeLabel}>
                    {Math.round(h.score * 100)}%
                  </span>
                  <div className={styles.scoreBarTrack}>
                    <div
                      className={styles.scoreBarFill}
                      style={{ width: `${Math.round(h.score * 100)}%` }}
                    />
                  </div>
                </div>

                {/* Score breakdown (shown when expanded) */}
                {expandedId === h.id && h.score_breakdown && (
                  <div className={styles.breakdownSection}>
                    {BREAKDOWN_LABELS.map(({ key, label }) => {
                      const val = h.score_breakdown![key];
                      return (
                        <div key={key} className={styles.breakdownRow}>
                          <span className={styles.breakdownLabel}>{label}</span>
                          <div className={styles.breakdownBar}>
                            <div
                              className={styles.breakdownBarFill}
                              style={{ width: `${Math.round(val * 100)}%` }}
                            />
                          </div>
                          <span className={styles.breakdownValue}>
                            {Math.round(val * 100)}%
                          </span>
                        </div>
                      );
                    })}
                  </div>
                )}

                {/* Action buttons */}
                <div className={styles.actions}>
                  <button
                    className={`${styles.actionBtn} ${styles.approveBtn}`}
                    disabled={actionLoading === h.id || h.status === "approved"}
                    onClick={() => handleApprove(h.id)}
                  >
                    Approve
                  </button>
                  <button
                    className={`${styles.actionBtn} ${styles.rejectBtn}`}
                    disabled={actionLoading === h.id || h.status === "rejected"}
                    onClick={() => handleReject(h.id)}
                  >
                    Discard
                  </button>
                  <button
                    className={styles.actionBtn}
                    disabled={actionLoading === h.id}
                    onClick={() => handleToggleTrim(h)}
                  >
                    {expandedId === h.id ? "Close" : "Trim"}
                  </button>
                </div>

                {/* Trim panel */}
                {expandedId === h.id && (
                  <div className={styles.trimPanel}>
                    <div className={styles.trimField}>
                      <span className={styles.trimLabel}>Start (s)</span>
                      <input
                        type="number"
                        className={styles.trimInput}
                        value={trimStart}
                        onChange={(e) => setTrimStart(e.target.value)}
                        min={0}
                        step={0.1}
                      />
                    </div>
                    <div className={styles.trimField}>
                      <span className={styles.trimLabel}>End (s)</span>
                      <input
                        type="number"
                        className={styles.trimInput}
                        value={trimEnd}
                        onChange={(e) => setTrimEnd(e.target.value)}
                        min={0}
                        step={0.1}
                      />
                    </div>
                    <div className={styles.trimActions}>
                      <button
                        className={`${styles.actionBtn} ${styles.approveBtn}`}
                        disabled={actionLoading === h.id}
                        onClick={() => handleSaveTrim(h.id)}
                      >
                        Save
                      </button>
                      <button
                        className={styles.actionBtn}
                        onClick={() => setExpandedId(null)}
                      >
                        Cancel
                      </button>
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
