import { useEffect, useState } from "react";
import { apiGet, apiPost } from "../../api";
import { PageHead, Empty, Loading } from "../../components/ui";
import { IconHeart, IconRefresh, IconTrash, IconUser } from "../../components/icons";
import { useToast } from "../../lib/toast";

interface User {
  id: string;
  name: string;
}
interface Collection {
  collection_id: string;
  collection_name: string;
  owner_name: string | null;
  is_favorites: boolean;
  item_count: number | null;
  owner_user_id: string | null;
}
interface ViewItem {
  id: string;
  title: string;
  type: string;
  year?: number;
  watched: boolean;
}
interface View {
  collection_name: string;
  user_name: string;
  items: ViewItem[];
  summary: { current_count: number; watched_count: number; unwatched_count: number };
}

export default function Favorites() {
  const toast = useToast();
  const [collections, setCollections] = useState<Collection[]>([]);
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [collectionId, setCollectionId] = useState("");
  const [userId, setUserId] = useState("");
  const [view, setView] = useState<View | null>(null);
  const [viewLoading, setViewLoading] = useState(false);
  const [busy, setBusy] = useState(false);
  const [targetSize, setTargetSize] = useState(20);

  useEffect(() => {
    apiGet<{ collections: Collection[]; users: User[] }>("/api/favorites/collections")
      .then((d) => {
        setCollections(d.collections);
        setUsers(d.users);
      })
      .catch((e) => toast(e.message, "err"))
      .finally(() => setLoading(false));
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  // When a favorites collection is picked, default the user to its owner.
  useEffect(() => {
    const c = collections.find((x) => x.collection_id === collectionId);
    if (c?.owner_user_id) setUserId(c.owner_user_id);
  }, [collectionId, collections]);

  function loadView() {
    if (!collectionId || !userId) return;
    setViewLoading(true);
    setView(null);
    apiGet<View>(`/api/favorites/collection/${collectionId}?user_id=${userId}`)
      .then(setView)
      .catch((e) => toast(e.message, "err"))
      .finally(() => setViewLoading(false));
  }

  useEffect(() => {
    if (collectionId && userId) loadView();
  }, [collectionId, userId]); // eslint-disable-line react-hooks/exhaustive-deps

  async function cleanup(dryRun: boolean) {
    if (!dryRun && !window.confirm("Remove all watched items from this collection?")) return;
    setBusy(true);
    try {
      const res = await apiPost(`/api/favorites/collection/${collectionId}/cleanup`, { userId, dryRun });
      toast(
        dryRun
          ? `${res.summary.watched_count} watched items would be removed`
          : `Removed ${res.summary.removed_count} watched items`,
        dryRun ? "info" : "ok"
      );
      if (!dryRun) loadView();
    } catch (e: any) {
      toast(e.message, "err");
    } finally {
      setBusy(false);
    }
  }

  async function regenerate(dryRun: boolean) {
    setBusy(true);
    try {
      const res = await apiPost(`/api/favorites/collection/${collectionId}/regenerate`, { userId, dryRun, targetSize });
      toast(
        dryRun
          ? `${res.summary.recommended_count} recommendations available`
          : `Added ${res.summary.added_count} recommendations`,
        dryRun ? "info" : "ok"
      );
      if (!dryRun) loadView();
    } catch (e: any) {
      toast(e.message, "err");
    } finally {
      setBusy(false);
    }
  }

  if (loading) return <Loading />;

  return (
    <>
      <PageHead title="User Favorites" icon={<IconHeart />} />

      <div className="panel" style={{ marginBottom: 18 }}>
        <div className="panel-body row wrap" style={{ gap: 14 }}>
          <div className="field grow" style={{ minWidth: 220 }}>
            <label className="field-label">Collection</label>
            <select className="select" value={collectionId} onChange={(e) => setCollectionId(e.target.value)}>
              <option value="">Select a collection…</option>
              {collections.map((c) => (
                <option key={c.collection_id} value={c.collection_id}>
                  {c.collection_name} {c.is_favorites ? "★" : ""} ({c.item_count ?? "?"})
                </option>
              ))}
            </select>
          </div>
          <div className="field grow" style={{ minWidth: 200 }}>
            <label className="field-label">User (for watched status)</label>
            <select className="select" value={userId} onChange={(e) => setUserId(e.target.value)}>
              <option value="">Select a user…</option>
              {users.map((u) => (
                <option key={u.id} value={u.id}>
                  {u.name}
                </option>
              ))}
            </select>
          </div>
        </div>
      </div>

      {viewLoading ? (
        <Loading />
      ) : !view ? (
        <div className="panel">
          <Empty icon={<IconHeart />}>Pick a collection and user to inspect favorites.</Empty>
        </div>
      ) : (
        <>
          <div className="row between wrap" style={{ marginBottom: 16, gap: 12 }}>
            <div className="row gap-sm wrap">
              <span className="badge">{view.summary.current_count} items</span>
              <span className="badge badge-ok">{view.summary.watched_count} watched</span>
              <span className="badge badge-accent">{view.summary.unwatched_count} unwatched</span>
            </div>
            <div className="row gap-sm wrap">
              <button className="btn btn-sm" onClick={() => cleanup(true)} disabled={busy}>
                Preview cleanup
              </button>
              <button className="btn btn-sm btn-danger" onClick={() => cleanup(false)} disabled={busy}>
                <IconTrash /> Remove watched
              </button>
              <div className="row gap-sm" style={{ marginLeft: 8 }}>
                <span className="hint">Target</span>
                <input
                  className="input"
                  style={{ width: 64 }}
                  type="number"
                  min={0}
                  value={targetSize}
                  onChange={(e) => setTargetSize(+e.target.value)}
                />
                <button className="btn btn-sm" onClick={() => regenerate(true)} disabled={busy}>
                  Preview recs
                </button>
                <button className="btn btn-sm btn-green" onClick={() => regenerate(false)} disabled={busy}>
                  <IconRefresh /> Add recs
                </button>
              </div>
            </div>
          </div>

          <div className="panel">
            <table className="data-table">
              <thead>
                <tr>
                  <th>Title</th>
                  <th>Type</th>
                  <th>Year</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                {view.items.map((i) => (
                  <tr key={i.id}>
                    <td className="cell-strong">{i.title}</td>
                    <td>{i.type}</td>
                    <td className="mono">{i.year || "—"}</td>
                    <td>
                      {i.watched ? <span className="badge badge-ok">watched</span> : <span className="badge">unwatched</span>}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </>
      )}
    </>
  );
}
