"use client";

import { useState } from "react";
import { useTranslation } from "@turbostarter/i18n";
import { cn } from "@turbostarter/ui";
import {
  ScatterChart,
  Scatter,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  ZAxis,
  Cell,
  ReferenceLine,
  ReferenceArea,
  LabelList,
} from "recharts";

import { CtaButton } from "~/modules/marketing/layout/cta-button";
import {
  Section,
  SectionBadge,
  SectionDescription,
  SectionHeader,
  SectionTitle,
} from "~/modules/marketing/layout/section";
import {
  DEMO_THEMES,
  DEMO_ACTIONS,
  DOMAIN_COLORS as THEME_DOMAIN_COLORS,
} from "./demo-report-data";

// ---------------------------------------------------------------------------
// Demo data (hardcoded for "Bistro El Sol")
// ---------------------------------------------------------------------------

const SCORE = 83;
const SCORE_COLOR = "#22c55e";

const PILLARS = [
  { key: "ratingQuality", value: 88, color: "#4285F4" },
  { key: "sentimentDepth", value: 76, color: "#8b5cf6" },
  { key: "volume", value: 91, color: "#22c55e" },
  { key: "momentum", value: 72, color: "#f59e0b" },
  { key: "intensity", value: 85, color: "#3b82f6" },
] as const;

const DOMAINS = [
  { key: "operations", color: "#3b82f6", value: 78 },
  { key: "product", color: "#22c55e", value: 85 },
  { key: "journey", color: "#f59e0b", value: 62 },
  { key: "environment", color: "#8b5cf6", value: 71 },
  { key: "value", color: "#f43f5e", value: 68 },
  { key: "management", color: "#6b7280", value: 74 },
] as const;

const SEVERITY_COLORS: Record<string, string> = {
  Critical: "#ef4444",
  High: "#f97316",
  Medium: "#f59e0b",
};

const EFFORT_COLORS: Record<string, string> = {
  low: "#22c55e",
  medium: "#f59e0b",
  high: "#ef4444",
  Low: "#22c55e",
  Medium: "#f59e0b",
  High: "#ef4444",
  Bajo: "#22c55e",
  Medio: "#f59e0b",
  Alto: "#ef4444",
};

const IMPACT_COLORS: Record<string, string> = {
  low: "#6b7280",
  medium: "#f59e0b",
  high: "#22c55e",
  Low: "#6b7280",
  Medium: "#f59e0b",
  High: "#22c55e",
  Bajo: "#6b7280",
  Medio: "#f59e0b",
  Alto: "#22c55e",
};

const DOMAIN_COLORS: Record<string, string> = {
  Operations: "#3b82f6",
  Product: "#22c55e",
  Environment: "#8b5cf6",
};

const TABS = ["score", "domains", "issues", "actions", "themes"] as const;
type Tab = (typeof TABS)[number];

// ---------------------------------------------------------------------------
// Score Tab
// ---------------------------------------------------------------------------

function ScoreTab() {
  const { t } = useTranslation("marketing");
  const radius = 65;
  const stroke = 10;
  const cx = 100;
  const cy = 72;
  const circumference = Math.PI * radius;
  const offset = circumference - (SCORE / 100) * circumference;

  return (
    <div className="flex flex-col items-center gap-4 sm:flex-row sm:items-start sm:gap-10">
      {/* Left: Gauge + band */}
      <div className="flex shrink-0 flex-col items-center gap-4">
        <span className="text-muted-foreground text-xs tracking-wide uppercase">
          {t("reportPreview.demo.businessName")}
        </span>

        <div className="relative" style={{ width: 200, height: 82 }}>
          <svg
            width="200"
            height="82"
            viewBox="0 0 200 82"
            className="overflow-visible"
          >
            <circle
              cx={cx}
              cy={cy}
              r={radius}
              fill="none"
              stroke="currentColor"
              className="text-muted/20"
              strokeWidth={stroke}
              strokeDasharray={`${circumference} ${circumference}`}
              strokeDashoffset={0}
              strokeLinecap="round"
              transform={`rotate(180 ${cx} ${cy})`}
            />
            <circle
              cx={cx}
              cy={cy}
              r={radius}
              fill="none"
              stroke={SCORE_COLOR}
              strokeWidth={stroke}
              strokeDasharray={`${circumference} ${circumference}`}
              strokeDashoffset={offset}
              strokeLinecap="round"
              transform={`rotate(180 ${cx} ${cy})`}
              className="transition-all duration-1000 ease-out"
            />
          </svg>
          <div className="absolute inset-0 flex flex-col items-center justify-end pb-0">
            <span
              className="text-5xl font-bold tabular-nums"
              style={{ color: SCORE_COLOR }}
            >
              {SCORE}
            </span>
            <span className="text-muted-foreground text-[10px] tracking-wide">
              {t("reportPreview.demo.scoreLabel")}
            </span>
          </div>
        </div>

        <div className="w-48">
          <div className="flex h-2 overflow-hidden rounded-full">
            <div style={{ width: "10%", backgroundColor: "#ef4444" }} />
            <div style={{ width: "15%", backgroundColor: "#f97316" }} />
            <div style={{ width: "15%", backgroundColor: "#f59e0b" }} />
            <div style={{ width: "20%", backgroundColor: "#22c55e" }} />
            <div style={{ width: "40%", backgroundColor: "#059669" }} />
          </div>
          <div className="relative h-3">
            <div
              className="absolute top-0"
              style={{
                left: `${SCORE}%`,
                transform: "translateX(-50%)",
                width: 0,
                height: 0,
                borderLeft: "5px solid transparent",
                borderRight: "5px solid transparent",
                borderBottom: `6px solid ${SCORE_COLOR}`,
              }}
            />
          </div>
          <div className="relative -mt-0.5 flex text-[7px] text-muted-foreground">
            <span className="absolute left-0 -translate-x-1/2">0</span>
            <span className="absolute" style={{ left: "10%" }}>40</span>
            <span className="absolute" style={{ left: "25%" }}>60</span>
            <span className="absolute" style={{ left: "40%" }}>75</span>
            <span className="absolute" style={{ left: "60%" }}>90</span>
            <span className="absolute right-0 translate-x-1/2">100</span>
          </div>
        </div>
      </div>

      {/* Right: Pillar bars */}
      <div className="flex w-full flex-1 flex-col gap-3">
        {PILLARS.map((p) => (
          <div key={p.key} className="flex items-center gap-3">
            <span className="text-muted-foreground w-24 shrink-0 text-right text-xs sm:w-32 sm:text-sm">
              {t(`reportPreview.demo.pillars.${p.key}` as const)}
            </span>
            <div className="bg-muted/30 relative h-2.5 flex-1 overflow-hidden rounded-full">
              <div
                className="absolute inset-y-0 left-0 rounded-full transition-all duration-700 ease-out"
                style={{
                  width: `${p.value}%`,
                  backgroundColor: p.color,
                }}
              />
            </div>
            <span className="w-10 text-right text-sm font-semibold tabular-nums">
              {p.value}%
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Domains Tab
// ---------------------------------------------------------------------------

function DomainsTab() {
  const { t } = useTranslation("marketing");

  return (
    <div className="flex flex-col gap-3.5">
      {DOMAINS.map((d) => (
        <div key={d.key} className="flex items-center gap-3">
          <span
            className="size-2.5 shrink-0 rounded-full"
            style={{ backgroundColor: d.color }}
          />
          <span className="text-foreground w-32 shrink-0 text-sm">
            {t(`reportPreview.demo.domains.${d.key}` as const)}
          </span>
          <div className="bg-muted/30 relative h-2.5 flex-1 overflow-hidden rounded-full">
            <div
              className="absolute inset-y-0 left-0 rounded-full transition-all duration-700 ease-out"
              style={{ width: `${d.value}%`, backgroundColor: d.color }}
            />
          </div>
          <span
            className="w-9 text-right text-sm font-semibold tabular-nums"
            style={{ color: d.color }}
          >
            {d.value}%
          </span>
        </div>
      ))}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Issues Tab
// ---------------------------------------------------------------------------

function IssuesTab() {
  const { t } = useTranslation("marketing");

  const issues = [
    { key: "issue1" as const, idx: 0 },
    { key: "issue2" as const, idx: 1 },
    { key: "issue3" as const, idx: 2 },
  ];

  return (
    <div className="flex flex-col gap-4">
      {issues.map(({ key: issueKey, idx }) => {
        const severity = t(`reportPreview.demo.issues.${issueKey}.severity` as const);
        const severityColor = SEVERITY_COLORS[severity] ?? "#f59e0b";
        const domain = t(`reportPreview.demo.issues.${issueKey}.domain` as const);
        const domainColor = DOMAIN_COLORS[domain] ?? "#6b7280";

        return (
          <div
            key={issueKey}
            className="bg-muted/20 flex gap-3 rounded-lg border p-3"
          >
            <div
              className="flex size-7 shrink-0 items-center justify-center rounded-full text-xs font-bold text-white"
              style={{ backgroundColor: severityColor }}
            >
              {idx + 1}
            </div>

            <div className="min-w-0 flex-1">
              <p className="text-foreground text-sm font-semibold leading-tight">
                {t(`reportPreview.demo.issues.${issueKey}.title` as const)}
              </p>

              <div className="mt-1.5 flex flex-wrap items-center gap-2">
                <span className="inline-flex items-center gap-1 text-xs">
                  <span
                    className="inline-block size-2 rounded-full"
                    style={{ backgroundColor: domainColor }}
                  />
                  <span className="text-muted-foreground">{domain}</span>
                </span>
                <span className="text-muted-foreground text-xs">
                  {t(`reportPreview.demo.issues.${issueKey}.complaints` as const)}
                </span>
                <span
                  className="rounded px-1.5 py-0.5 text-[10px] font-semibold text-white"
                  style={{ backgroundColor: severityColor }}
                >
                  {severity}
                </span>
              </div>

              <div
                className="mt-2 border-l-2 pl-3"
                style={{ borderColor: severityColor }}
              >
                <p className="text-muted-foreground text-xs italic leading-relaxed">
                  {t(`reportPreview.demo.issues.${issueKey}.quote` as const)}
                </p>
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Actions Tab (enhanced with real report data)
// ---------------------------------------------------------------------------

function ActionsTab() {
  const { t } = useTranslation("marketing");

  // Build mention count map from demo themes
  const mentionMap = new Map<string, number>();
  for (const theme of DEMO_THEMES) {
    mentionMap.set(theme.primitive, theme.count);
  }

  return (
    <div className="flex flex-col gap-4">
      {DEMO_ACTIONS.map((action, idx) => {
        const effortColor = EFFORT_COLORS[action.effort] ?? "#f59e0b";
        const impactColor = IMPACT_COLORS[action.impact] ?? "#f59e0b";
        const mentions = mentionMap.get(action.source);

        return (
          <div
            key={idx}
            className="bg-muted/20 overflow-hidden rounded-lg border"
          >
            <div className="flex gap-3 p-3">
              <div className="bg-primary/10 text-primary flex size-7 shrink-0 items-center justify-center rounded-full text-xs font-bold">
                {idx + 1}
              </div>

              <div className="min-w-0 flex-1">
                <p className="text-foreground text-sm font-semibold leading-tight">
                  {action.action}
                </p>

                <div className="mt-1.5 flex flex-wrap items-center gap-2">
                  <span className="text-muted-foreground text-xs">
                    {action.owner}
                  </span>
                  {mentions != null && (
                    <span className="text-xs font-medium" style={{ color: "#4285F4" }}>
                      {mentions} {t("reportPreview.demo.themes.mentions" as const)}
                    </span>
                  )}
                  <span className="text-muted-foreground text-xs">
                    {action.timeline}
                  </span>
                </div>

                <div className="mt-2 flex flex-wrap gap-2">
                  <span
                    className="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-semibold"
                    style={{
                      backgroundColor: `${effortColor}18`,
                      color: effortColor,
                    }}
                  >
                    {action.effort} effort
                  </span>
                  <span
                    className="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-semibold"
                    style={{
                      backgroundColor: `${impactColor}18`,
                      color: impactColor,
                    }}
                  >
                    {action.impact} impact
                  </span>
                </div>
              </div>
            </div>

            {action.success_metric && (
              <div className="bg-muted/30 border-t px-4 py-2">
                <p className="text-muted-foreground text-xs leading-relaxed">
                  <span className="font-semibold">Target:</span> {action.success_metric}
                </p>
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Themes Tab (ThemeMatrix scatter chart)
// ---------------------------------------------------------------------------

interface ScatterPoint {
  x: number;
  y: number;
  z: number;
  name: string;
  domain: string;
  color: string;
}

function ThemesTab() {
  const { t } = useTranslation("marketing");

  const data: ScatterPoint[] = DEMO_THEMES
    .filter((theme) => theme.domain !== "meta")
    .map((theme) => {
      const total =
        theme.valence.positive +
        theme.valence.negative +
        theme.valence.neutral +
        theme.valence.mixed;
      const sentimentRatio =
        total > 0
          ? ((theme.valence.positive - theme.valence.negative) / total) * 100
          : 0;
      return {
        x: theme.count,
        y: Math.round(sentimentRatio),
        z: theme.weight * theme.count,
        name: theme.label,
        domain: theme.domain,
        color: THEME_DOMAIN_COLORS[theme.domain] ?? "#6b7280",
      };
    })
    .sort((a, b) => b.z - a.z);

  const yValues = data.map((d) => d.y);
  const yMin = Math.min(-20, ...yValues) - 10;
  const yMax = Math.max(20, ...yValues) + 10;

  return (
    <div>
      {/* Domain legend */}
      <div className="mb-4 flex flex-wrap justify-center gap-x-4 gap-y-1">
        {[
          { label: "People/Service", domain: "P" },
          { label: "Journey", domain: "J" },
          { label: "Value", domain: "V" },
          { label: "Product", domain: "O" },
          { label: "Environment", domain: "E" },
        ].map((d) => (
          <span key={d.domain} className="inline-flex items-center gap-1.5 text-xs">
            <span
              className="inline-block size-2 rounded-full"
              style={{ backgroundColor: THEME_DOMAIN_COLORS[d.domain] }}
            />
            <span className="text-muted-foreground">{d.label}</span>
          </span>
        ))}
      </div>

      <ResponsiveContainer width="100%" height={300}>
        <ScatterChart margin={{ top: 20, right: 30, left: 10, bottom: 10 }}>
          <defs>
            <linearGradient id="tmPositiveZone" x1="0" y1="1" x2="0" y2="0">
              <stop offset="0%" stopColor="#22c55e" stopOpacity={0.02} />
              <stop offset="100%" stopColor="#22c55e" stopOpacity={0.08} />
            </linearGradient>
            <linearGradient id="tmNegativeZone" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#ef4444" stopOpacity={0.02} />
              <stop offset="100%" stopColor="#ef4444" stopOpacity={0.08} />
            </linearGradient>
          </defs>
          <ReferenceArea y1={0} y2={yMax} fill="url(#tmPositiveZone)" strokeOpacity={0} />
          <ReferenceArea y1={yMin} y2={0} fill="url(#tmNegativeZone)" strokeOpacity={0} />
          <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
          <XAxis
            type="number"
            dataKey="x"
            tick={{ fill: "#6b7280", fontSize: 11 }}
            tickLine={false}
            axisLine={false}
            label={{
              value: t("reportPreview.demo.themes.frequency" as const),
              position: "insideBottom",
              offset: -5,
              fill: "#9ca3af",
              fontSize: 12,
            }}
          />
          <YAxis
            type="number"
            dataKey="y"
            domain={[yMin, yMax]}
            tick={{ fill: "#6b7280", fontSize: 11 }}
            tickLine={false}
            axisLine={false}
            label={{
              value: t("reportPreview.demo.themes.sentiment" as const),
              angle: -90,
              position: "insideLeft",
              fill: "#9ca3af",
              fontSize: 12,
            }}
          />
          <ReferenceLine y={0} stroke="#94a3b8" strokeWidth={1.5} />
          <ZAxis type="number" dataKey="z" range={[80, 500]} />
          <Tooltip
            content={({ active, payload }) => {
              if (!active || !payload?.length) return null;
              const point = (payload[0] as Record<string, unknown>)
                ?.payload as ScatterPoint | undefined;
              if (!point) return null;
              return (
                <div className="bg-background rounded-lg border p-2 shadow-md">
                  <div className="text-foreground text-[13px] font-bold">
                    {point.name}
                  </div>
                  <div className="text-muted-foreground text-xs">
                    {t("reportPreview.demo.themes.mentions" as const)}: <strong>{point.x}</strong>
                  </div>
                  <div className="text-muted-foreground text-xs">
                    {t("reportPreview.demo.themes.netSentiment" as const)}: <strong>{point.y}%</strong>
                  </div>
                </div>
              );
            }}
          />
          <Scatter data={data}>
            {data.map((entry, i) => (
              <Cell key={i} fill={entry.color} fillOpacity={0.7} />
            ))}
            <LabelList dataKey="name" position="top" fontSize={9} fill="#6b7280" offset={8} />
          </Scatter>
        </ScatterChart>
      </ResponsiveContainer>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Main component
// ---------------------------------------------------------------------------

export const ReportPreview = () => {
  const [activeTab, setActiveTab] = useState<Tab>("score");
  const { t } = useTranslation("marketing");

  return (
    <Section id="report-preview">
      <SectionHeader>
        <SectionBadge>{t("reportPreview.label")}</SectionBadge>
        <SectionTitle>{t("reportPreview.title")}</SectionTitle>
        <SectionDescription>
          {t("reportPreview.description")}
        </SectionDescription>
      </SectionHeader>

      <div className="relative w-full max-w-3xl">
        {/* Ambient glow */}
        <div className="pointer-events-none absolute inset-0 -bottom-10">
          <div className="absolute top-1/2 left-1/2 h-[400px] w-[500px] -translate-x-1/2 -translate-y-1/2 rounded-full bg-blue-500/8 blur-[100px]" />
          <div className="absolute top-1/3 left-1/3 h-[250px] w-[250px] -translate-x-1/2 -translate-y-1/2 rounded-full bg-amber-400/10 blur-[80px]" />
        </div>

        {/* Card */}
        <div className="bg-background relative overflow-clip rounded-2xl border shadow-sm">
          {/* Tab bar */}
          <div className="flex border-b">
            {TABS.map((tab) => (
              <button
                key={tab}
                type="button"
                onClick={() => setActiveTab(tab)}
                className={cn(
                  "text-muted-foreground hover:text-foreground relative flex-1 px-2 py-3 text-xs font-medium transition-colors sm:px-4 sm:text-sm",
                  activeTab === tab && "text-foreground",
                )}
              >
                {t(`reportPreview.tabs.${tab}` as const)}
                {activeTab === tab && (
                  <span
                    className="absolute inset-x-0 bottom-0 h-0.5"
                    style={{ backgroundColor: "#4285F4" }}
                  />
                )}
              </button>
            ))}
          </div>

          {/* Tab content */}
          <div className="p-6 sm:p-8">
            {activeTab === "score" && <ScoreTab />}
            {activeTab === "domains" && <DomainsTab />}
            {activeTab === "issues" && <IssuesTab />}
            {activeTab === "actions" && <ActionsTab />}
            {activeTab === "themes" && <ThemesTab />}
          </div>
        </div>
      </div>

      <CtaButton>{t("reportPreview.cta")}</CtaButton>
    </Section>
  );
};
