"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { PaginatedResponse, Topic } from "@/lib/types";
import TopicCard from "./topic-card";

type TopicsViewProps = {
  pagination: PaginatedResponse<Topic>;
};

export default function TopicsView({ pagination }: TopicsViewProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [search, setSearch] = useState("");
  const [clientPagination, setClientPagination] = useState(pagination);

  const currentFilter = searchParams.get("published");
  const showPublishedOnly = currentFilter === "true" ? "published" : currentFilter === "false" ? "draft" : "all";

  const filteredTopics = useMemo(() => {
    return clientPagination.data.filter((topic) => {
      const matchSearch =
        !search ||
        topic.generated_data.some(
          (item) => item.title?.toLowerCase().includes(search.toLowerCase()) ?? false
        ) ||
        (topic.prompt?.toLowerCase().includes(search.toLowerCase()) ?? false);

      return matchSearch;
    });
  }, [clientPagination.data, search]);

  useEffect(() => {
    setClientPagination(pagination);
  }, [pagination]);

  useEffect(() => {
    const handler = async () => {
      try {
        const params = new URLSearchParams(searchParams.toString());
        params.set("page", String(clientPagination.current_page));
        const response = await fetch(`/api/topics?${params.toString()}`, { cache: "no-store" });
        if (!response.ok) return;
        const next = await response.json();
        setClientPagination(next);
      } catch {
        // ignore
      }
    };

    window.addEventListener("topics:refresh", handler);
    return () => window.removeEventListener("topics:refresh", handler);
  }, [clientPagination.current_page, searchParams]);

  const handleFilterChange = (value: "all" | "published" | "draft") => {
    const params = new URLSearchParams(searchParams.toString());
    if (value === "all") {
      params.delete("published");
    } else {
      params.set("published", value === "published" ? "true" : "false");
    }
    params.set("page", "1"); // Reset to page 1 on filter change
    router.push(`/posts?${params.toString()}`);
  };

  return (
    <section className="space-y-6">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
        <div className="flex flex-1 flex-col gap-4 sm:flex-row">
          <label className="flex-1">
            <span className="sr-only">Search</span>
            <input
              type="search"
              placeholder="Search by title, platform, or prompt"
              value={search}
              onChange={(event) => setSearch(event.target.value)}
              className="w-full rounded-2xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-900 outline-none ring-2 ring-transparent transition focus:ring-orange-500/40 dark:border-white/10 dark:bg-white/5 dark:text-white"
            />
          </label>
          <div className="flex gap-2 rounded-2xl border border-slate-200 p-1 text-xs font-semibold text-slate-900 dark:border-white/10 dark:text-white">
            {[
              { label: "All", value: "all" },
              { label: "Published", value: "published" },
              { label: "Drafts", value: "draft" },
            ].map((option) => (
              <button
                key={option.value}
                type="button"
                onClick={() => handleFilterChange(option.value as "all" | "published" | "draft")}
                className={`flex-1 rounded-2xl px-3 py-2 transition ${showPublishedOnly === option.value
                  ? "bg-slate-200 dark:bg-white/20"
                  : "text-slate-600 dark:text-slate-400"
                  }`}
              >
                {option.label}
              </button>
            ))}
          </div>
        </div>
        <div className="flex justify-between text-sm text-slate-600 dark:text-slate-400 lg:w-auto">
          <span>
            Page {clientPagination.current_page} / {clientPagination.last_page}
          </span>
          <span>Total {clientPagination.total} items</span>
        </div>
      </div>

      <div className="grid gap-4 lg:grid-cols-2">
        {filteredTopics.map((topic) => (
          <TopicCard key={topic.id} topic={topic} />
        ))}
      </div>

      <div className="flex items-center justify-between rounded-2xl border border-slate-200 px-4 py-3 text-sm text-slate-900 dark:border-white/10 dark:text-white">
        <Link
          href={`/posts?${new URLSearchParams({ ...Object.fromEntries(searchParams.entries()), page: String(Math.max(1, clientPagination.current_page - 1)) }).toString()}`}
          className="rounded-2xl px-3 py-1 text-slate-600 transition hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-white/10"
        >
          Previous
        </Link>
        <span>
          {clientPagination.current_page} / {clientPagination.last_page}
        </span>
        <Link
          href={`/posts?${new URLSearchParams({ ...Object.fromEntries(searchParams.entries()), page: String(Math.min(clientPagination.last_page, clientPagination.current_page + 1)) }).toString()}`}
          className="rounded-2xl px-3 py-1 text-slate-600 transition hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-white/10"
        >
          Next
        </Link>
      </div>
    </section>
  );
}
