import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { api } from "../lib/api";
import { RouteIcon } from "../components/PixelIcons";

const TYPE_LABELS: Record<string, string> = { youtube: "YouTube", hyread: "HyRead 書籍", manual: "手動" };
const STATUS_LABELS: Record<string, string> = { captured: "已擷取", processing: "處理中", ready: "已完成", error: "錯誤" };

function SourceRow({ source, onRefresh }: { source: any; onRefresh: () => void }) {
  const [processing, setProcessing] = useState(false);
  const qc = useQueryClient();

  const processMutation = useMutation({
    mutationFn: async () => {
      const transcript = source.metadata?.transcript || "";
      return api.youtubeProcess(source.id, transcript);
    },
    onSuccess: () => { qc.invalidateQueries({ queryKey: ["content"] }); onRefresh(); },
  });

  return (
    <div className={`cs-row cs-${source.kind}`}>
      <div className="cs-info">
        <div className="cs-title">{source.title || source.id}</div>
        <div className="cs-meta">
          <span className={`tag tag-${source.kind}`}>{TYPE_LABELS[source.kind] || source.kind}</span>
          <span className={`tag tag-${source.status}`}>{STATUS_LABELS[source.status] || source.status}</span>
          {source.channel && <span>{source.channel}</span>}
          {source.published_at && <span>{source.published_at}</span>}
          {source.processed_count > 0 && <span>{source.processed_count} 項知識</span>}
        </div>
      </div>
      <div className="cs-actions">
        {source.status === "captured" && source.kind === "youtube" && (
          <button className="btn btn-sm" onClick={() => processMutation.mutate()} disabled={processing}>
            {processing ? "處理中..." : "AI 處理"}
          </button>
        )}
        <button
          className="btn btn-sm btn-ghost"
          onClick={() => api.rebuildKnowledge().then(onRefresh)}
        >
          重建知識庫
        </button>
      </div>
    </div>
  );
}

export default function ContentManager() {
  const [tab, setTab] = useState<"sources" | "youtube" | "hyread" | "schedule">("sources");
  const [url, setUrl] = useState("");
  const [scheduleUrl, setScheduleUrl] = useState("");
  const [scheduleName, setScheduleName] = useState("");
  const [scheduleInterval, setScheduleInterval] = useState(10080);
  const [fetchStatus, setFetchStatus] = useState<string | null>(null);
  const [importStatus, setImportStatus] = useState<string | null>(null);
  const qc = useQueryClient();

  const sourcesQ = useQuery({
    queryKey: ["content"],
    queryFn: () => api.contentSources(),
  });

  const hyreadQ = useQuery({
    queryKey: ["hyread-scan"],
    queryFn: () => api.hyreadScan(),
    enabled: tab === "hyread",
  });

  const schedulesQ = useQuery({
    queryKey: ["content-schedules"],
    queryFn: () => api.contentSchedules(),
    enabled: tab === "schedule",
  });

  const ytDlpQ = useQuery({
    queryKey: ["yt-dlp"],
    queryFn: () => api.ytDlpStatus(),
  });

  const fetchMutation = useMutation({
    mutationFn: (u: string) => api.youtubeFetch(u),
    onSuccess: (data) => {
      setFetchStatus(`成功: 已加入 ${data.items?.length || 1} 個影片`);
      setUrl("");
      qc.invalidateQueries({ queryKey: ["content"] });
    },
    onError: (err: any) => setFetchStatus(`錯誤: ${err.message}`),
  });

  const scheduleMutation = useMutation({
    mutationFn: () => api.createContentSchedule({
      kind: "youtube_channel",
      name: scheduleName,
      url: scheduleUrl,
      intervalMin: scheduleInterval,
    }),
    onSuccess: () => {
      setScheduleUrl("");
      setScheduleName("");
      qc.invalidateQueries({ queryKey: ["content-schedules"] });
    },
  });

  const refresh = () => {
    qc.invalidateQueries({ queryKey: ["content"] });
    qc.invalidateQueries({ queryKey: ["knowledge"] });
  };

  return (
    <div className="page content-manager-page">
      <div className="page-head">
        <h1>內容管理</h1>
        <p className="page-subtitle">管理 YouTube 與 HyRead 內容擷取</p>
      </div>

      <div className="cm-tabs">
        {(["sources", "youtube", "hyread", "schedule"] as const).map(t => (
          <button key={t} className={`btn ${tab === t ? "btn-active" : ""}`} onClick={() => setTab(t)}>
            {t === "sources" ? "所有來源" : t === "youtube" ? "YouTube" : t === "hyread" ? "HyRead" : "排程"}
          </button>
        ))}
      </div>

      {tab === "sources" && (
        <section>
          <div className="cm-toolbar">
            <span className="text-dim">{sourcesQ.data?.stats?.total || 0} 個內容來源</span>
            <button className="btn btn-sm" onClick={() => api.rebuildKnowledge().then(refresh)}>重建知識庫</button>
          </div>
          <div className="cs-list">
            {(sourcesQ.data?.sources || []).map((s: any) => (
              <SourceRow key={s.id} source={s} onRefresh={refresh} />
            ))}
            {(!sourcesQ.data?.sources || sourcesQ.data.sources.length === 0) && (
              <div className="lc-empty"><p>尚無內容來源，請從 YouTube 或 HyRead 匯入</p></div>
            )}
          </div>
          {sourcesQ.data?.stats?.byKind && (
            <div className="cm-stats">
              {Object.entries(sourcesQ.data.stats.byKind).map(([k, counts]: [string, any]) => (
                <div key={k} className="cm-stat-chip">
                  {TYPE_LABELS[k] || k}: {Object.values(counts).reduce((a: number, b: any) => a + (b as number), 0)}
                </div>
              ))}
            </div>
          )}
        </section>
      )}

      {tab === "youtube" && (
        <section>
          <div className="cm-card">
            <h3>抓取 YouTube 影片</h3>
            <div className="cm-input-row">
              <input
                type="text"
                className="cm-input"
                placeholder="YouTube URL (單一影片或播放清單)"
                value={url}
                onChange={e => setUrl(e.target.value)}
              />
              <button
                className="btn"
                onClick={() => url.trim() && fetchMutation.mutate(url.trim())}
                disabled={fetchMutation.isPending || !url.trim()}
              >
                {fetchMutation.isPending ? "抓取中..." : "抓取"}
              </button>
            </div>
            {fetchStatus && <div className={`cm-status ${fetchStatus.startsWith("錯誤") ? "error" : "ok"}`}>{fetchStatus}</div>}
            <div className="cm-hint">
              {ytDlpQ.data?.available ? "✓ yt-dlp 已安裝" : "⚠ yt-dlp 未安裝（僅能用公開 API）"}
              ｜支援單一影片與播放清單
              ｜會員影片請用 Chrome 擴充功能
            </div>
          </div>

          <div className="cm-card">
            <h3>Chrome 擴充功能</h3>
            <p className="text-dim">安裝擴充功能後，在 YouTube 或 HyRead 頁面點擊「擷取」即可將內容送回伺服器。</p>
            <a href="/extension.crx" className="btn btn-sm" download>下載擴充功能</a>
          </div>
        </section>
      )}

      {tab === "hyread" && (
        <section>
          <div className="cm-card">
            <h3>掃描 hyread-tools/output/</h3>
            <button className="btn" onClick={() => qc.invalidateQueries({ queryKey: ["hyread-scan"] })}>
              重新掃描
            </button>
          </div>

          <div className="cm-card">
            <h3>上傳 book.html</h3>
            <p className="text-dim">從 hyread-tools/output/ 取得 book.html 後在此上傳</p>
            <input
              type="file"
              accept=".html"
              onChange={async (e) => {
                const file = e.target.files?.[0];
                if (!file) return;
                const text = await file.text();
                const title = file.name.replace(/\.html$/, "");
                setImportStatus("上傳中...");
                try {
                  const res = await api.hyreadUpload(title, text);
                  setImportStatus(`成功: ${res.title} (${res.principleCount} 原則, ${res.termCount} 名詞)`);
                  qc.invalidateQueries({ queryKey: ["content"] });
                } catch (err: any) {
                  setImportStatus(`錯誤: ${err.message}`);
                }
              }}
            />
            {importStatus && <div className={`cm-status ${importStatus.startsWith("錯誤") ? "error" : "ok"}`}>{importStatus}</div>}
          </div>

          <div className="cm-card">
            <h3>已掃描書籍</h3>
            {(hyreadQ.data?.books || []).length === 0 && <div className="text-dim">尚未掃描到書籍</div>}
            {(hyreadQ.data?.books || []).map((book: any) => (
              <div key={book.dir} className="cs-row">
                <div className="cs-info">
                  <div className="cs-title">{book.title}</div>
                  <div className="cs-meta">
                    <span>{book.pageCount} 頁</span>
                    <span>{book.metadata?.author || ""}</span>
                  </div>
                </div>
                <div className="cs-actions">
                  <button
                    className="btn btn-sm"
                    onClick={async () => {
                      try {
                        await api.hyreadImport(book.dir);
                        qc.invalidateQueries({ queryKey: ["content"] });
                        qc.invalidateQueries({ queryKey: ["hyread-scan"] });
                      } catch (err: any) {
                        alert(err.message);
                      }
                    }}
                  >
                    匯入
                  </button>
                </div>
              </div>
            ))}
          </div>
        </section>
      )}

      {tab === "schedule" && (
        <section>
          <div className="cm-card">
            <h3>新增排程</h3>
            <div className="cm-input-row">
              <input
                type="text"
                className="cm-input"
                placeholder="顯示名稱"
                value={scheduleName}
                onChange={e => setScheduleName(e.target.value)}
              />
              <input
                type="text"
                className="cm-input"
                placeholder="YouTube 頻道/播放清單 URL"
                value={scheduleUrl}
                onChange={e => setScheduleUrl(e.target.value)}
              />
              <select value={scheduleInterval} onChange={e => setScheduleInterval(Number(e.target.value))}>
                <option value={1440}>每天</option>
                <option value={10080}>每週</option>
                <option value={43200}>每月</option>
              </select>
              <button
                className="btn btn-sm"
                onClick={() => scheduleMutation.mutate()}
                disabled={!scheduleName.trim() || !scheduleUrl.trim()}
              >
                新增
              </button>
            </div>
          </div>

          <div className="cm-card">
            <h3>現有排程</h3>
            {(schedulesQ.data?.schedules || []).length === 0 && <div className="text-dim">尚無排程</div>}
            {(schedulesQ.data?.schedules || []).map((s: any) => (
              <div key={s.id} className="cs-row">
                <div className="cs-info">
                  <div className="cs-title">{s.name}</div>
                  <div className="cs-meta">
                    <span>{s.interval_min >= 43200 ? "每月" : s.interval_min >= 10080 ? "每週" : "每天"}</span>
                    <span>{s.enabled ? "啟用" : "停用"}</span>
                    {s.last_checked_at && <span>上次檢查: {new Date(s.last_checked_at).toLocaleDateString()}</span>}
                  </div>
                </div>
                <div className="cs-actions">
                  <button className="btn btn-sm btn-ghost" onClick={() => api.deleteContentSchedule(s.id).then(() => qc.invalidateQueries({ queryKey: ["content-schedules"] }))}>刪除</button>
                </div>
              </div>
            ))}
          </div>
        </section>
      )}
    </div>
  );
}
