"use client";

import { Banknote, CheckCircle2, Globe2, MapPinned, PackageSearch, ShieldX } from "lucide-react";
import type { CSSProperties } from "react";
import { useMemo, useState } from "react";
import type { MapRegion, MapReport } from "@/components/dashboard/data-types";
import { usePreferences } from "@/components/providers/app-providers";

type Metric = "orders" | "confirmationRate" | "cancelRate" | "cod";

export function MapPage({ report }: { report: MapReport }) {
  const { dictionary: t, locale } = usePreferences();
  const [metric, setMetric] = useState<Metric>("orders");
  const nameFor = (region: MapRegion) => locale === "ar" ? region.nameAr : region.nameEn;
  const valueFor = (region: MapRegion) => region[metric];
  const maxValue = Math.max(1, ...report.egypt.map(valueFor));
  const sortedEgypt = useMemo(
    () => [...report.egypt].sort((left, right) => valueFor(right) - valueFor(left)),
    [metric, report.egypt],
  );
  const number = new Intl.NumberFormat(locale === "ar" ? "ar-EG" : "en-US");
  const money = new Intl.NumberFormat(locale === "ar" ? "ar-EG" : "en-US", {
    style: "currency",
    currency: "EGP",
    maximumFractionDigits: 0,
  });
  const displayMetric = (region: MapRegion) => {
    if (metric === "cod") return money.format(region.cod);
    if (metric === "confirmationRate" || metric === "cancelRate") return `${number.format(valueFor(region))}%`;
    return number.format(region.orders);
  };

  const cards = [
    { label: t.dashboard.map.totalOrders, value: number.format(report.totals.orders), icon: PackageSearch, tone: "cyan" },
    { label: t.dashboard.map.confirmed, value: number.format(report.totals.confirmed), icon: CheckCircle2, tone: "green" },
    { label: t.dashboard.map.cancelled, value: number.format(report.totals.cancelled), icon: ShieldX, tone: "red" },
    { label: t.dashboard.map.cod, value: money.format(report.totals.cod), icon: Banknote, tone: "blue" },
  ];

  return (
    <div className="data-page map-page">
      <header className="data-page-header">
        <div>
          <p className="eyebrow">{t.dashboard.map.eyebrow}</p>
          <h1>{t.dashboard.map.title}</h1>
          <p>{t.dashboard.map.description}</p>
        </div>
        <div className="metric-switcher" aria-label={t.dashboard.map.metric}>
          {(["orders", "confirmationRate", "cancelRate", "cod"] as Metric[]).map((value) => (
            <button className={metric === value ? "active" : ""} type="button" key={value} onClick={() => setMetric(value)}>
              {t.dashboard.map.metrics[value]}
            </button>
          ))}
        </div>
      </header>

      <section className="summary-grid">
        {cards.map(({ label, value, icon: Icon, tone }) => (
          <article className={`summary-card tone-${tone}`} key={label}>
            <span><Icon size={19} /></span>
            <div><small>{label}</small><strong>{value}</strong></div>
          </article>
        ))}
      </section>

      <section className="map-layout">
        <article className="data-panel egypt-map-panel">
          <header className="panel-heading">
            <div><MapPinned size={18} /><div><h2>{t.dashboard.map.egyptTitle}</h2><p>{t.dashboard.map.egyptSubtitle}</p></div></div>
            <span>{report.egypt.length} {t.dashboard.map.governorates}</span>
          </header>
          <div className="governorate-heatmap" aria-label={t.dashboard.map.egyptTitle}>
            {report.egypt.map((region) => {
              const intensity = valueFor(region) / maxValue;
              return (
                <div
                  className={`governorate-tile ${region.orders === 0 ? "is-empty" : ""}`}
                  key={region.code}
                  style={{
                    "--heat-bg": `${4 + Math.max(.08, intensity) * 18}%`,
                    "--heat-border": `${14 + Math.max(.08, intensity) * 34}%`,
                    "--heat-line": `${20 + Math.max(.08, intensity) * 80}%`,
                  } as CSSProperties}
                  title={`${nameFor(region)}: ${displayMetric(region)}`}
                >
                  <span>{region.code}</span>
                  <strong>{nameFor(region)}</strong>
                  <small>{displayMetric(region)}</small>
                </div>
              );
            })}
          </div>
          <div className="heat-legend"><span>{t.dashboard.map.lower}</span><i /><span>{t.dashboard.map.higher}</span></div>
        </article>

        <aside className="region-summary-stack">
          <RegionSummary title={t.dashboard.map.gulf} regions={report.gulf} locale={locale} empty={t.dashboard.map.noData} />
          <RegionSummary title={t.dashboard.map.international} regions={report.international} locale={locale} empty={t.dashboard.map.noData} />
        </aside>
      </section>

      <section className="data-panel table-panel">
        <header className="panel-heading">
          <div><Globe2 size={18} /><div><h2>{t.dashboard.map.tableTitle}</h2><p>{t.dashboard.map.tableSubtitle}</p></div></div>
        </header>
        <div className="data-table-wrap">
          <table className="data-table">
            <thead><tr>
              <th>{t.dashboard.map.governorate}</th>
              <th>{t.dashboard.map.orders}</th>
              <th>{t.dashboard.map.confirmation}</th>
              <th>{t.dashboard.map.cancelRate}</th>
              <th>{t.dashboard.map.cod}</th>
            </tr></thead>
            <tbody>
              {sortedEgypt.map((region) => (
                <tr key={region.code}>
                  <td><strong>{nameFor(region)}</strong><small className="mono">{region.code}</small></td>
                  <td>{number.format(region.orders)}</td>
                  <td><span className="rate-positive">{number.format(region.confirmationRate)}%</span></td>
                  <td><span className={region.cancelRate > 25 ? "rate-negative" : ""}>{number.format(region.cancelRate)}%</span></td>
                  <td>{money.format(region.cod)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>
    </div>
  );
}

function RegionSummary({
  title,
  regions,
  locale,
  empty,
}: {
  title: string;
  regions: MapRegion[];
  locale: "ar" | "en";
  empty: string;
}) {
  const number = new Intl.NumberFormat(locale === "ar" ? "ar-EG" : "en-US");
  const money = new Intl.NumberFormat(locale === "ar" ? "ar-EG" : "en-US", {
    style: "currency",
    currency: "EGP",
    maximumFractionDigits: 0,
  });
  const totals = regions.reduce(
    (value, region) => ({ orders: value.orders + region.orders, cod: value.cod + region.cod }),
    { orders: 0, cod: 0 },
  );

  return (
    <article className="data-panel region-summary">
      <div className="region-summary-icon"><Globe2 size={21} /></div>
      <h2>{title}</h2>
      {regions.length ? (
        <>
          <strong>{number.format(totals.orders)}</strong>
          <span>{money.format(totals.cod)}</span>
          <div>{regions.map((region) => <small key={`${region.country}-${region.code}`}>{region.nameEn} · {region.orders}</small>)}</div>
        </>
      ) : <p>{empty}</p>}
    </article>
  );
}
