"use client"

import Link from "next/link"
import { useRouter, useSearchParams } from "next/navigation"
import { useEffect, useMemo, useState } from "react"

import type { ReportMeta } from "@/lib/types"

type DirectoryClientProps = {
  reports: ReportMeta[]
  regions: string[]
  canAccessPro: boolean
}

type SortOrder = "newest" | "oldest"

function formatDate(date: string) {
  return new Date(date).toLocaleDateString("en-GB", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  })
}

function normalizeRegion(value: string) {
  return value.trim().toLowerCase().replace(/-/g, " ")
}

export default function DirectoryClient({
  reports,
  regions,
  canAccessPro,
}: DirectoryClientProps) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const [selectedRegion, setSelectedRegion] = useState("All")
  const [selectedTopic, setSelectedTopic] = useState("")
  const [searchQuery, setSearchQuery] = useState("")
  const [sortOrder, setSortOrder] = useState<SortOrder>("newest")

  function updateURL(region: string, topic: string) {
    const params = new URLSearchParams()

    if (region && region !== "All") {
      params.set("region", region)
    }

    if (topic) {
      params.set("topic", topic)
    }

    const query = params.toString()
    router.replace(query ? `/directory?${query}` : "/directory", {
      scroll: false,
    })
  }

  useEffect(() => {
    const regionParam = searchParams.get("region")
    const topicParam = searchParams.get("topic")

    setSelectedTopic(topicParam ?? "")

    if (!regionParam) {
      setSelectedRegion("All")
      return
    }

    const matchingRegion = regions.find(
      (region) => normalizeRegion(region) === normalizeRegion(regionParam),
    )

    setSelectedRegion(matchingRegion ?? "All")
  }, [regions, searchParams])

  const filteredReports = useMemo(() => {
    const query = searchQuery.trim().toLowerCase()
    const topic = selectedTopic.trim().toLowerCase()

    return reports
      .filter((report) =>
        selectedRegion === "All" ? true : report.region === selectedRegion,
      )
      .filter((report) => {
        if (!topic) {
          return true
        }

        return (
          report.topic.toLowerCase().includes(topic) ||
          report.title.toLowerCase().includes(topic)
        )
      })
      .filter((report) => {
        if (!query) {
          return true
        }

        const searchableText = [
          report.title,
          report.subtitle,
          report.topic,
        ]
          .join(" ")
          .toLowerCase()

        return searchableText.includes(query)
      })
      .sort((a, b) => {
        const dateA = new Date(a.publishedAt).getTime()
        const dateB = new Date(b.publishedAt).getTime()

        return sortOrder === "newest" ? dateB - dateA : dateA - dateB
      })
  }, [reports, searchQuery, selectedRegion, selectedTopic, sortOrder])

  function clearFilters() {
    setSelectedRegion("All")
    setSelectedTopic("")
    setSearchQuery("")
    router.replace("/directory", { scroll: false })
  }

  function selectRegion(region: string) {
    if (region === "All") {
      setSelectedRegion("All")
      setSelectedTopic("")
      router.replace("/directory", { scroll: false })
      return
    }

    setSelectedRegion(region)
    updateURL(region, selectedTopic)
  }

  function clearTopicFilter() {
    setSelectedTopic("")
    updateURL(selectedRegion, "")
  }

  function changeTopicFilter(topic: string) {
    setSelectedTopic(topic)
    updateURL(selectedRegion, topic)
  }

  return (
    <section className="bg-[var(--color-bg)] px-6 pb-20">
      <div className="mx-auto max-w-[1200px]">
        <div className="mb-8">
          <div className="-mx-6 flex gap-3 overflow-x-auto px-6 sm:mx-0 sm:flex-wrap sm:px-0">
            {["All", ...regions].map((region) => {
              const isActive = selectedRegion === region

              return (
                <button
                  key={region}
                  type="button"
                  onClick={() => selectRegion(region)}
                  className={[
                    "shrink-0 cursor-pointer rounded-full border px-4 py-1.5 text-[13px] transition",
                    isActive
                      ? "border-[var(--color-accent)] bg-[var(--color-accent)] text-white"
                      : "border-[var(--color-border)] bg-[var(--color-surface)] text-[var(--color-text-secondary)] hover:border-[var(--color-accent)]",
                  ].join(" ")}
                >
                  {region}
                </button>
              )
            })}
          </div>

          <div className="mt-3 flex flex-wrap items-center gap-3">
            <input
              type="text"
              value={selectedTopic}
              onChange={(event) => changeTopicFilter(event.target.value)}
              placeholder="Filter by topic or keyword..."
              data-lpignore="true"
              suppressHydrationWarning
              className="w-full rounded border border-[var(--color-border)] bg-[var(--color-surface)] px-3 py-1.5 text-[13px] text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-secondary)] sm:w-[220px]"
            />
            {selectedTopic ? (
              <span className="inline-flex items-center gap-1 rounded bg-[var(--color-tag-bg)] px-2 py-0.5 text-xs text-[var(--color-accent)]">
                {selectedTopic}
                <button
                  type="button"
                  onClick={clearTopicFilter}
                  className="ml-1 cursor-pointer bg-transparent text-[14px] leading-none text-[var(--color-accent)]"
                  aria-label="Clear topic filter"
                >
                  &times;
                </button>
              </span>
            ) : null}
            <input
              type="search"
              value={searchQuery}
              onChange={(event) => setSearchQuery(event.target.value)}
              placeholder="Search reports..."
              className="w-full rounded border border-[var(--color-border)] bg-[var(--color-surface)] px-3 py-1.5 text-[13px] text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-secondary)] sm:w-[220px]"
            />
            <select
              value={sortOrder}
              onChange={(event) => setSortOrder(event.target.value as SortOrder)}
              className="rounded border border-[var(--color-border)] bg-[var(--color-surface)] px-3 py-1.5 text-[13px] text-[var(--color-text-primary)] outline-none"
            >
              <option value="newest">Newest first</option>
              <option value="oldest">Oldest first</option>
            </select>
          </div>
        </div>

        <div className="mb-4 flex flex-wrap items-center gap-2 text-[13px] text-[var(--color-text-secondary)]">
          <span>
            {filteredReports.length} report
            {filteredReports.length !== 1 ? "s" : ""}
          </span>
          {selectedRegion !== "All" ? (
            <span className="rounded-full bg-[var(--color-tag-bg)] px-2 py-0.5 text-[11px] text-[var(--color-accent)]">
              {selectedRegion}
              <button
                type="button"
                onClick={() => {
                  setSelectedRegion("All")
                  updateURL("All", selectedTopic)
                }}
                className="ml-1 cursor-pointer border-0 bg-transparent text-[13px] leading-none text-[var(--color-accent)]"
                aria-label="Clear region filter"
              >
                &times;
              </button>
            </span>
          ) : null}
          {selectedTopic ? (
            <span className="rounded-full bg-[var(--color-tag-bg)] px-2 py-0.5 text-[11px] text-[var(--color-accent)]">
              {selectedTopic}
              <button
                type="button"
                onClick={clearTopicFilter}
                className="ml-1 cursor-pointer border-0 bg-transparent text-[13px] leading-none text-[var(--color-accent)]"
                aria-label="Clear topic filter"
              >
                &times;
              </button>
            </span>
          ) : null}
          {selectedRegion !== "All" || selectedTopic ? (
            <button
              type="button"
              onClick={clearFilters}
              className="cursor-pointer border-0 bg-transparent text-xs text-[var(--color-text-secondary)] underline"
            >
              Clear all
            </button>
          ) : null}
        </div>

        {filteredReports.length > 0 ? (
          <div className="grid gap-4">
            {filteredReports.map((report) => (
              <Link
                key={report.slug}
                href={`/${report.slug}`}
                className="flex overflow-hidden rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)] transition duration-200 hover:border-[var(--color-accent)]"
              >
                <div className="relative hidden min-h-[110px] w-[180px] shrink-0 sm:block">
                  {report.coverImage ? (
                    <img
                      src={report.coverImage}
                      alt={report.title}
                      className="h-full w-full object-cover"
                    />
                  ) : (
                    <div className="h-full w-full bg-[var(--color-border)]" />
                  )}
                  {report.isPro && !canAccessPro ? (
                    <span
                      aria-label="Pro report"
                      className="absolute right-2 top-2 rounded bg-black/60 px-1.5 py-0.5 text-xs text-white"
                    >
                      <svg
                        aria-hidden="true"
                        className="h-3.5 w-3.5"
                        fill="none"
                        stroke="currentColor"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth="2"
                        viewBox="0 0 24 24"
                      >
                        <rect height="11" rx="2" width="18" x="3" y="11" />
                        <path d="M7 11V7a5 5 0 0 1 10 0v4" />
                      </svg>
                    </span>
                  ) : null}
                </div>

                <div className="flex-1 p-4">
                  <div className="flex flex-wrap gap-2">
                    <span className="rounded bg-[var(--color-tag-bg)] px-2 py-0.5 text-[11px] uppercase tracking-widest text-[var(--color-accent)]">
                      {report.region}
                    </span>
                    {report.isPro ? (
                      <span className="rounded bg-[#7c3aed] px-2 py-0.5 text-[11px] uppercase tracking-widest text-white">
                        PRO
                      </span>
                    ) : null}
                  </div>

                  <h2 className="mt-1.5 line-clamp-1 font-serif text-lg text-[var(--color-text-primary)]">
                    {report.title}
                  </h2>
                  <p className="mt-1 line-clamp-2 text-[13px] text-[var(--color-text-secondary)]">
                    {report.subtitle}
                  </p>

                  <div className="mt-2.5 flex flex-wrap items-center justify-between gap-2 text-xs text-[var(--color-text-secondary)]">
                    <span>{report.topic}</span>
                    <span>
                      {formatDate(report.publishedAt)} · {report.readTime} min read
                    </span>
                  </div>
                </div>
              </Link>
            ))}
          </div>
        ) : (
          <div className="rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)] px-6 py-16 text-center">
            <div className="text-4xl">🔍</div>
            <h2 className="mt-4 font-serif text-xl text-[var(--color-text-primary)]">
              No reports found.
            </h2>
            <p className="mt-2 text-sm text-[var(--color-text-secondary)]">
              Try a different region or search term.
            </p>
            <button
              type="button"
              onClick={clearFilters}
              className="mt-5 rounded bg-[var(--color-accent)] px-4 py-2 text-sm font-medium text-white transition hover:bg-[var(--color-accent-hover)]"
            >
              Clear filters
            </button>
          </div>
        )}
      </div>
    </section>
  )
}
