"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 { EconomyCountry } from "@/lib/databoards/economies"

type Metric =
  | "gdpTn"
  | "gdpGrowth"
  | "gdpPerCapita"
  | "population"
  | "inflation"

const metrics: Array<{ label: string; value: Metric }> = [
  { label: "GDP ($tn)", value: "gdpTn" },
  { label: "GDP Growth %", value: "gdpGrowth" },
  { label: "GDP Per Capita", value: "gdpPerCapita" },
  { label: "Population (m)", value: "population" },
  { label: "Inflation %", value: "inflation" },
]

const regions = ["All", "Americas", "Europe", "Asia", "Middle East", "Africa"]

function formatMetric(value: number, metric: Metric) {
  if (metric === "gdpTn") return `$${value}tn`
  if (metric === "gdpGrowth") return `${value}%`
  if (metric === "gdpPerCapita") return `$${value.toLocaleString("en-US")}`
  if (metric === "population") return `${value}m`
  return `${value}%`
}

function getBarFill(value: number, metric: Metric) {
  if ((metric === "gdpGrowth" || metric === "inflation") && value < 0) {
    return "#ef4444"
  }

  if ((metric === "gdpGrowth" || metric === "inflation") && value > 10) {
    return "#f59e0b"
  }

  return "var(--color-accent)"
}

function getHighest(data: EconomyCountry[], metric: Metric) {
  return [...data].sort((a, b) => b[metric] - a[metric])[0]
}

export default function EconomiesBoard({ data }: { data: EconomyCountry[] }) {
  const [metric, setMetric] = useState<Metric>("gdpTn")
  const [regionFilter, setRegionFilter] = useState("All")

  const filteredData = useMemo(() => {
    return [...data]
      .filter((row) => regionFilter === "All" || row.region === regionFilter)
      .sort((a, b) => b[metric] - a[metric])
  }, [data, metric, regionFilter])

  const largestEconomy = getHighest(data, "gdpTn")
  const fastestGrowing = getHighest(data, "gdpGrowth")
  const highestInflation = getHighest(data, "inflation")
  const mostPopulous = getHighest(data, "population")

  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)]">
        Global Economies
      </h1>
      <p className="mt-1 text-sm text-[var(--color-text-secondary)]">
        GDP, growth, inflation, and population. Data: World Bank / IMF 2024.
      </p>

      <div className="my-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard
          label="Largest Economy"
          value={
            largestEconomy
              ? `${largestEconomy.flag} ${largestEconomy.country}`
              : "No data"
          }
          sub={largestEconomy ? `$${largestEconomy.gdpTn}tn` : ""}
        />
        <StatCard
          label="Fastest Growing"
          value={
            fastestGrowing
              ? `${fastestGrowing.flag} ${fastestGrowing.country}`
              : "No data"
          }
          sub={fastestGrowing ? `+${fastestGrowing.gdpGrowth}%` : ""}
        />
        <StatCard
          label="Highest Inflation"
          value={
            highestInflation
              ? `${highestInflation.flag} ${highestInflation.country}`
              : "No data"
          }
          sub={highestInflation ? `${highestInflation.inflation}%` : ""}
        />
        <StatCard
          label="Most Populous"
          value={
            mostPopulous ? `${mostPopulous.flag} ${mostPopulous.country}` : "No data"
          }
          sub={mostPopulous ? `${mostPopulous.population}m people` : ""}
        />
      </div>

      <div className="mb-8 flex flex-wrap gap-3">
        <div className="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>

        <select
          value={regionFilter}
          onChange={(event) => setRegionFilter(event.target.value)}
          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"
        >
          {regions.map((region) => (
            <option key={region} value={region}>
              {region === "All" ? "All Regions" : region}
            </option>
          ))}
        </select>
      </div>

      <div className="rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)] p-4">
        <ResponsiveContainer width="100%" height={460}>
          <BarChart
            data={filteredData}
            layout="vertical"
            margin={{ top: 0, right: 40, left: 130, 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={125}
              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]}>
              {filteredData.map((row) => (
                <Cell
                  key={row.country}
                  fill={getBarFill(Number(row[metric]), metric)}
                />
              ))}
            </Bar>
          </BarChart>
        </ResponsiveContainer>
      </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-[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">Country</th>
                <th className="px-3 py-3 text-right">GDP ($tn)</th>
                <th className="px-3 py-3 text-right">Growth %</th>
                <th className="px-3 py-3 text-right">GDP/Capita</th>
                <th className="px-3 py-3 text-right">Population</th>
                <th className="px-3 py-3 text-right">Inflation %</th>
              </tr>
            </thead>
            <tbody>
              {filteredData.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.gdpTn}tn</td>
                  <td
                    className={[
                      "px-3 py-3 text-right",
                      row.gdpGrowth < 0
                        ? "text-[#ef4444]"
                        : row.gdpGrowth > 5
                          ? "text-[#4ade80]"
                          : "",
                    ].join(" ")}
                  >
                    {row.gdpGrowth}%
                  </td>
                  <td className="px-3 py-3 text-right">
                    ${row.gdpPerCapita.toLocaleString("en-US")}
                  </td>
                  <td className="px-3 py-3 text-right">
                    {row.population.toLocaleString("en-US")}m
                  </td>
                  <td
                    className={[
                      "px-3 py-3 text-right",
                      row.inflation > 20 ? "text-[#f59e0b]" : "",
                    ].join(" ")}
                  >
                    {row.inflation}%
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </section>
  )
}

function StatCard({
  label,
  value,
  sub,
}: {
  label: string
  value: string
  sub: string
}) {
  return (
    <div className="flex-1 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)] p-4">
      <p className="text-[11px] font-semibold uppercase tracking-widest text-[var(--color-accent)]">
        {label}
      </p>
      <p className="mt-1 font-serif text-[17px] text-[var(--color-text-primary)]">
        {value}
      </p>
      <p className="mt-0.5 text-[13px] text-[var(--color-text-secondary)]">
        {sub}
      </p>
    </div>
  )
}
