"use client"

import dynamic from "next/dynamic"
import Link from "next/link"
import { useCallback, useMemo, useState } from "react"

import type { ShippingChokepoint } from "@/lib/databoards/shipping"

const ShippingMap = dynamic(() => import("./ShippingMap"), {
  ssr: false,
  loading: () => (
    <div
      style={{
        height: "520px",
        background: "var(--color-surface)",
        borderRadius: "12px",
        border: "1px solid var(--color-border)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        color: "var(--color-text-secondary)",
        fontSize: "14px",
      }}
    >
      Loading map...
    </div>
  ),
})

type RiskFilter = "All" | "Critical" | "High" | "Medium" | "Low"

const filters: RiskFilter[] = ["All", "Critical", "High", "Medium", "Low"]

function riskColor(risk: string) {
  if (risk === "Critical") return "#ef4444"
  if (risk === "High") return "#f59e0b"
  if (risk === "Medium") return "#3b7dd8"
  if (risk === "Low") return "#4ade80"
  return "var(--color-accent)"
}

function activeRiskText(risk: RiskFilter) {
  return risk === "Low" ? "text-black" : "text-white"
}

export default function ShippingBoard({
  data,
}: {
  data: ShippingChokepoint[]
}) {
  const [selected, setSelected] = useState<ShippingChokepoint | null>(null)
  const [filter, setFilter] = useState<RiskFilter>("All")

  const handleSelect = useCallback((point: ShippingChokepoint) => {
    setSelected(point)
  }, [])

  const filteredData = useMemo(() => {
    return data.filter((row) => filter === "All" || row.riskLevel === filter)
  }, [data, filter])

  return (
    <section className="mx-auto max-w-[1400px] px-6 pb-20">
      <Link
        href="/pro/data-boards"
        className="mb-6 inline-block text-[13px] text-[var(--color-accent)] hover:underline"
      >
        &larr; Data Boards
      </Link>
      <h1 className="font-serif text-3xl font-normal text-[var(--color-text-primary)]">
        Global Shipping Chokepoints
      </h1>
      <p className="mt-1 text-sm text-[var(--color-text-secondary)]">
        Critical maritime passages controlling global oil and trade flows.
      </p>

      <div className="my-8 flex flex-wrap gap-2">
        {filters.map((risk) => {
          const isActive = filter === risk
          const color = riskColor(risk)

          return (
            <button
              key={risk}
              type="button"
              onClick={() => setFilter(risk)}
              className={[
                "cursor-pointer rounded-full border px-4 py-1.5 text-[13px] transition",
                isActive
                  ? `border-transparent ${activeRiskText(risk)}`
                  : "border-[var(--color-border)] bg-[var(--color-surface)] text-[var(--color-text-secondary)] hover:border-[var(--color-accent)]",
              ].join(" ")}
              style={isActive ? { backgroundColor: color } : undefined}
            >
              {risk}
            </button>
          )
        })}
      </div>

      <div className="mb-8 overflow-hidden rounded-xl border border-[var(--color-border)]">
        <ShippingMap data={filteredData} onSelect={handleSelect} />
      </div>

      <div className="mb-10 flex justify-center lg:justify-start">
        {selected ? (
          <DetailPanel
            chokepoint={selected}
            onClose={() => setSelected(null)}
          />
        ) : (
          <div className="w-full max-w-[600px] rounded-xl border border-[var(--color-border)] bg-[var(--color-surface)] p-6 text-center text-[13px] text-[var(--color-text-secondary)]">
            Click a marker on the map to see details.
          </div>
        )}
      </div>

      <div>
        <p className="mb-3 text-[11px] font-semibold uppercase tracking-widest text-[var(--color-accent)]">
          CHOKEPOINTS
        </p>
        <div className="overflow-x-auto">
          <table className="w-full min-w-[820px] border-collapse text-sm">
            <thead>
              <tr className="bg-[var(--color-surface)] text-[11px] uppercase tracking-widest text-[var(--color-accent)]">
                <th className="px-3 py-3 text-left">Name</th>
                <th className="px-3 py-3 text-left">Country</th>
                <th className="px-3 py-3 text-right">Oil Flow</th>
                <th className="px-3 py-3 text-right">% World</th>
                <th className="px-3 py-3 text-left">Risk</th>
              </tr>
            </thead>
            <tbody>
              {filteredData.map((row, index) => (
                <tr
                  key={row.name}
                  onClick={() => setSelected(row)}
                  className={[
                    "cursor-pointer border-b border-l-[3px] border-b-[var(--color-border)] border-l-transparent text-[13px] text-[var(--color-text-secondary)] transition hover:border-l-[var(--color-accent)]",
                    index % 2 === 1 ? "bg-[var(--color-surface)]" : "",
                  ].join(" ")}
                >
                  <td className="px-3 py-3 text-left text-[var(--color-text-primary)]">
                    {row.name}
                  </td>
                  <td className="px-3 py-3 text-left">{row.country}</td>
                  <td className="px-3 py-3 text-right">
                    {row.dailyOilMn}m barrels/day
                  </td>
                  <td className="px-3 py-3 text-right">
                    {row.percentWorldOil}%
                  </td>
                  <td
                    className="px-3 py-3 text-left font-semibold"
                    style={{ color: riskColor(row.riskLevel) }}
                  >
                    {row.riskLevel}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </section>
  )
}

function DetailPanel({
  chokepoint,
  onClose,
}: {
  chokepoint: ShippingChokepoint
  onClose: () => void
}) {
  return (
    <article className="relative w-full max-w-[600px] rounded-xl border border-[var(--color-border)] bg-[var(--color-surface)] p-6">
      <button
        type="button"
        onClick={onClose}
        className="absolute right-4 top-3 text-xl text-[var(--color-text-secondary)] transition hover:text-[var(--color-text-primary)]"
        aria-label="Close details"
      >
        x
      </button>
      <span
        className="inline-block rounded-full px-3 py-1 text-[11px] font-bold uppercase tracking-widest text-white"
        style={{ backgroundColor: riskColor(chokepoint.riskLevel) }}
      >
        {chokepoint.riskLevel}
      </span>
      <h2 className="mt-2 font-serif text-[1.4rem] text-[var(--color-text-primary)]">
        {chokepoint.name}
      </h2>
      <p className="text-[13px] text-[var(--color-text-secondary)]">
        {chokepoint.country}
      </p>

      <div className="mt-4 flex flex-wrap gap-6">
        <div>
          <p className="text-[11px] font-semibold uppercase tracking-widest text-[var(--color-accent)]">
            Daily Oil Flow
          </p>
          <p className="font-serif text-[18px] text-[var(--color-text-primary)]">
            {chokepoint.dailyOilMn}m barrels/day
          </p>
        </div>
        <div>
          <p className="text-[11px] font-semibold uppercase tracking-widest text-[var(--color-accent)]">
            % of World Oil
          </p>
          <p className="font-serif text-[18px] text-[var(--color-text-primary)]">
            {chokepoint.percentWorldOil}%
          </p>
        </div>
      </div>

      <p className="mt-4 text-[14px] leading-[1.7] text-[var(--color-text-secondary)]">
        {chokepoint.description}
      </p>
    </article>
  )
}
