"use client"

import Link from "next/link"
import { useMemo, useState } from "react"
import {
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts"

import type { AiTechCountry } from "@/lib/databoards/ai-tech"

type Metric =
  | "aiInvestmentBn"
  | "semiconductorShare"
  | "techCompanies"
  | "aiResearchPapers"

const metrics: Array<{ label: string; value: Metric }> = [
  { label: "AI Investment ($bn)", value: "aiInvestmentBn" },
  { label: "Semiconductor Share %", value: "semiconductorShare" },
  { label: "Tech Companies", value: "techCompanies" },
  { label: "Research Papers", value: "aiResearchPapers" },
]

const insightCards = [
  {
    title: "US-China Tech War",
    body: "The US has imposed sweeping semiconductor export controls targeting China's AI development, restricting access to advanced chips and chip-making equipment since 2022.",
    source: "Source: BIS Export Controls 2024",
  },
  {
    title: "Semiconductor Concentration",
    body: "Taiwan and South Korea produce over 60% of the world's advanced semiconductors. TSMC alone accounts for 90%+ of cutting-edge chip fabrication below 5nm.",
    source: "Source: SIA 2024",
  },
  {
    title: "AI Research Race",
    body: "China now produces more AI research papers than any other nation, though US papers are more cited. The EU lags significantly in both investment and output.",
    source: "Source: Stanford HAI 2024",
  },
]

function formatMetric(value: number, metric: Metric) {
  if (metric === "aiInvestmentBn") return `$${value}bn`
  if (metric === "semiconductorShare") return `${value}%`
  if (metric === "techCompanies") return value.toString()
  return value.toLocaleString("en-US")
}

function policyColor(policy: string) {
  if (policy === "Aggressive") return "#3b7dd8"
  if (policy === "Sanctioned") return "#ef4444"
  if (policy === "Targeted") return "#f59e0b"
  if (policy === "Aligned with US") return "#4ade80"
  if (policy === "Moderate") return "#8b5cf6"
  return "var(--color-accent)"
}

export default function AiTechBoard({ data }: { data: AiTechCountry[] }) {
  const [metric, setMetric] = useState<Metric>("aiInvestmentBn")

  const sortedData = useMemo(() => {
    return [...data].sort((a, b) => b[metric] - a[metric])
  }, [data, metric])

  const policies = Array.from(new Set(data.map((row) => row.exportControls)))

  return (
    <section className="mx-auto max-w-[1200px] 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)]">
        AI & Tech Geopolitics
      </h1>
      <p className="mt-1 text-sm text-[var(--color-text-secondary)]">
        AI investment, semiconductor dominance, and research output by country.
        Data: 2024.
      </p>

      <div className="my-8 flex flex-wrap gap-2">
        {metrics.map((item) => {
          const isActive = metric === item.value

          return (
            <button
              key={item.value}
              type="button"
              onClick={() => setMetric(item.value)}
              className={[
                "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(" ")}
            >
              {item.label}
            </button>
          )
        })}
      </div>

      <div className="rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)] p-4">
        <ResponsiveContainer width="100%" height={380}>
          <BarChart
            data={sortedData}
            layout="vertical"
            margin={{ top: 0, right: 40, left: 140, bottom: 0 }}
          >
            <CartesianGrid
              horizontal
              vertical={false}
              stroke="var(--color-border)"
              strokeDasharray="3 3"
            />
            <XAxis
              type="number"
              tick={{ fill: "var(--color-text-secondary)", fontSize: 11 }}
              tickFormatter={(value) => formatMetric(Number(value), metric)}
            />
            <YAxis
              type="category"
              dataKey="country"
              width={135}
              tick={{ fill: "var(--color-text-primary)", fontSize: 12 }}
              tickFormatter={(country) => {
                const row = data.find((item) => item.country === country)
                return row ? `${row.flag} ${country}` : String(country)
              }}
            />
            <Tooltip
              contentStyle={{
                background: "var(--color-surface)",
                border: "1px solid var(--color-border)",
                borderRadius: "6px",
              }}
              labelStyle={{
                color: "var(--color-text-primary)",
                fontWeight: "bold",
              }}
              formatter={(value) => formatMetric(Number(value), metric)}
            />
            <Bar dataKey={metric} radius={[0, 4, 4, 0]}>
              {sortedData.map((row) => (
                <Cell key={row.country} fill={policyColor(row.exportControls)} />
              ))}
            </Bar>
          </BarChart>
        </ResponsiveContainer>
      </div>

      <div className="mt-4 flex flex-wrap gap-x-5 gap-y-2">
        {policies.map((policy) => (
          <div
            key={policy}
            className="flex items-center gap-2 text-[12px] text-[var(--color-text-secondary)]"
          >
            <span
              className="h-2 w-2 rounded-full"
              style={{ backgroundColor: policyColor(policy) }}
            />
            {policy}
          </div>
        ))}
      </div>

      <div className="mt-10 grid gap-4 md:grid-cols-3">
        {insightCards.map((card) => (
          <article
            key={card.title}
            className="rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)] p-5"
          >
            <h2 className="font-serif text-[15px] text-[var(--color-text-primary)]">
              {card.title}
            </h2>
            <p className="mt-2 text-[13px] leading-[1.7] text-[var(--color-text-secondary)]">
              {card.body}
            </p>
            <p className="mt-3 text-[11px] italic text-[var(--color-text-secondary)]">
              {card.source}
            </p>
          </article>
        ))}
      </div>

      <div className="mt-10">
        <p className="mb-3 text-[11px] font-semibold uppercase tracking-widest text-[var(--color-accent)]">
          FULL DATA TABLE
        </p>
        <div className="overflow-x-auto">
          <table className="w-full min-w-[860px] 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">Country</th>
                <th className="px-3 py-3 text-right">AI Investment</th>
                <th className="px-3 py-3 text-right">Semicon. Share</th>
                <th className="px-3 py-3 text-right">Tech Cos.</th>
                <th className="px-3 py-3 text-right">Research Papers</th>
                <th className="px-3 py-3 text-left">Export Policy</th>
              </tr>
            </thead>
            <tbody>
              {sortedData.map((row, index) => (
                <tr
                  key={row.country}
                  className={[
                    "border-b border-[var(--color-border)] text-[13px] text-[var(--color-text-secondary)]",
                    index % 2 === 1 ? "bg-[var(--color-surface)]" : "",
                  ].join(" ")}
                >
                  <td className="px-3 py-3 text-left text-[var(--color-text-primary)]">
                    {row.flag} {row.country}
                  </td>
                  <td className="px-3 py-3 text-right">
                    ${row.aiInvestmentBn}bn
                  </td>
                  <td className="px-3 py-3 text-right">
                    {row.semiconductorShare}%
                  </td>
                  <td className="px-3 py-3 text-right">
                    {row.techCompanies.toLocaleString("en-US")}
                  </td>
                  <td className="px-3 py-3 text-right">
                    {row.aiResearchPapers.toLocaleString("en-US")}
                  </td>
                  <td
                    className="px-3 py-3 text-left font-medium"
                    style={{ color: policyColor(row.exportControls) }}
                  >
                    {row.exportControls}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </section>
  )
}
