"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { VideoCard, type VideoCardData } from "@/components/video-card";
import { Button, EmptyState, FeedSkeleton, useToast } from "@/components/ui";
import { useSession } from "@/components/session-provider";
import { api } from "@/lib/api-client";

export default function HistoryPage() {
  const { user } = useSession();
  const { toast, toastNode } = useToast();
  const [items, setItems] = useState<VideoCardData[] | null>(null);

  useEffect(() => {
    if (!user) return setItems([]);
    void api<{ items: VideoCardData[] }>("/api/history").then((data) => setItems(data.items)).catch(() => setItems([]));
  }, [user]);

  return (
    <div className="flex flex-col gap-6 px-4 py-6 lg:flex-row">
      <aside className="w-full shrink-0 lg:w-64">
        <h1 className="text-2xl font-bold">Watch history</h1>
        <Button
          variant="secondary"
          className="mt-4 w-full"
          onClick={async () => {
            await api("/api/history?all=1", { method: "DELETE" }).catch((e) => toast(e.message));
            setItems([]);
            toast("History cleared");
          }}
        >
          Clear all history
        </Button>
        <Link href="/playlist/watch_later" className="mt-2 block rounded-full bg-surface px-4 py-2 text-center text-sm font-semibold">
          Watch later
        </Link>
        <Link href="/playlist/liked" className="mt-2 block rounded-full bg-surface px-4 py-2 text-center text-sm font-semibold">
          Liked videos
        </Link>
      </aside>
      <div className="min-w-0 flex-1 space-y-4">
        {items === null ? <FeedSkeleton count={4} /> : null}
        {items !== null && items.length === 0 ? (
          user ? (
            <EmptyState icon="🕘" title="Nothing watched yet" hint="Videos you watch will show up here so you can continue where you left off." />
          ) : (
            <EmptyState icon="🔒" title="Sign in to see your history" hint="Your watch history is private to your account." action={<Link href="/login" className="text-sm font-semibold text-brand">Sign in</Link>} />
          )
        ) : null}
        {items?.map((video) => (
          <div key={video.id} className="flex items-start gap-2">
            <div className="min-w-0 flex-1">
              <VideoCard video={video} layout="row" />
            </div>
            <button
              onClick={async () => {
                const data = await api<{ items: VideoCardData[] }>("/api/history", { method: "DELETE", json: { videoId: video.id } }).catch(() => null);
                if (data) setItems(data.items);
                toast("Removed from history");
              }}
              className="rounded px-2 py-1 text-xs hover:bg-surface"
            >
              ✕
            </button>
          </div>
        ))}
      </div>
      {toastNode}
    </div>
  );
}
