import React from "react";
import NotebookTemplate from "@/components/NotebookTemplate";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  type ChartConfig,
  ChartContainer,
  ChartLegend,
  ChartLegendContent,
  ChartTooltip,
  ChartTooltipContent,
} from "@/components/ui/chart";
import {
  Area,
  AreaChart,
  Bar,
  BarChart,
  CartesianGrid,
  Line,
  LineChart,
  XAxis,
  YAxis,
} from "recharts";

import story from "@/data/<topic>/story.json";  // Replace <topic> with your data folder name

// ============================================================================
// TYPE DEFINITIONS
// ============================================================================

// Define types matching your JSON structure
type AnnualRow = {
  year: number;
  value1: number;
  value2: number;
  // Add more fields as needed
};

type CategoryRow = {
  year: number;
  category1: number;
  category2: number;
  category3: number;
  total: number;
  // Add more fields as needed
};

// ============================================================================
// DATA LOADING
// ============================================================================

// Load data from JSON
const annual = story.annual as AnnualRow[];
const byCategory = story.by_category as CategoryRow[];

// ============================================================================
// FORMATTING HELPERS
// ============================================================================

const fmtInt = (v: number) =>
  new Intl.NumberFormat("en-US", { maximumFractionDigits: 0 }).format(v);

const fmtPct1 = (v: number) =>
  new Intl.NumberFormat("en-US", { maximumFractionDigits: 1 }).format(v);

const fmtSigned1 = (v: number) =>
  `${v >= 0 ? "+" : ""}${new Intl.NumberFormat("en-US", {
    maximumFractionDigits: 1,
  }).format(v)}`;

// ============================================================================
// CHART CONFIGS
// ============================================================================

// Define chart configs for consistent styling
const chartConfig = {
  value1: { label: "Label 1", color: "var(--chart-1)" },
  value2: { label: "Label 2", color: "var(--chart-2)" },
  value3: { label: "Label 3", color: "var(--chart-3)" },
  value4: { label: "Label 4", color: "var(--chart-4)" },
} satisfies ChartConfig;

// ============================================================================
// MAIN COMPONENT
// ============================================================================

export default function MyTopic() {
  // Extract headline statistics
  const h = story.headline as {
    first_year: number;
    last_year: number;
    key_metric_1: number;
    key_metric_2: number;
    key_metric_3: number;
    // Add more fields as needed
  };

  return (
    <NotebookTemplate
      title="Your page title"
      subtitle="Descriptive subtitle explaining what this notebook covers"
      sources="Data source attribution (e.g., U.S. Energy Information Administration, World Bank, etc.)"
    >
      {/* ========================================================================
         INTRODUCTION SECTION
         ======================================================================== */}
      <section className="space-y-3">
        <p className="text-foreground leading-relaxed">
          This notebook looks at <strong>what you're analyzing</strong> and
          explains the key questions you're answering. Provide context about
          the data, time period, and geographic coverage.
        </p>
      </section>

      {/* ========================================================================
         HEADLINE CARDS
         ======================================================================== */}
      <section className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Key metric 1</CardDescription>
            <CardTitle>{fmtPct1(h.key_metric_1)}%</CardTitle>
          </CardHeader>
          <CardContent className="text-sm text-muted-foreground">
            Description, {h.first_year} → {h.last_year}
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Key metric 2</CardDescription>
            <CardTitle>{fmtSigned1(h.key_metric_2)} pp</CardTitle>
          </CardHeader>
          <CardContent className="text-sm text-muted-foreground">
            Description, {h.first_year} → {h.last_year}
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Key metric 3</CardDescription>
            <CardTitle>{fmtInt(h.key_metric_3)}</CardTitle>
          </CardHeader>
          <CardContent className="text-sm text-muted-foreground">
            Description, {h.last_year}
          </CardContent>
        </Card>
      </section>

      {/* ========================================================================
         CHART SECTION 1: Line chart for trends
         ======================================================================== */}
      <section className="space-y-4">
        <Card>
          <CardHeader>
            <CardTitle>Chart title</CardTitle>
            <CardDescription>
              Chart description explaining what this shows and the units.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <ChartContainer config={chartConfig} className="h-[360px] w-full">
              <LineChart data={annual} margin={{ left: 12, right: 12, top: 8 }}>
                <CartesianGrid vertical={false} />
                <XAxis dataKey="year" tickLine={false} axisLine={false} />
                <YAxis
                  tickLine={false}
                  axisLine={false}
                  tickFormatter={(v) => fmtInt(v)}
                />
                <ChartTooltip content={<ChartTooltipContent />} />
                <ChartLegend content={<ChartLegendContent />} />
                <Line
                  dataKey="value1"
                  stroke="var(--color-value1)"
                  strokeWidth={2}
                  dot={false}
                />
                <Line
                  dataKey="value2"
                  stroke="var(--color-value2)"
                  strokeWidth={2}
                  dot={false}
                />
              </LineChart>
            </ChartContainer>
          </CardContent>
        </Card>
      </section>

      {/* ========================================================================
         NARRATIVE SECTION 1
         ======================================================================== */}
      <section className="space-y-4">
        <p className="text-foreground leading-relaxed">
          Explain what the chart shows and why it matters. Use specific
          numbers from the data to tell the story. Connect to broader themes
          or implications.
        </p>
      </section>

      {/* ========================================================================
         CHART SECTION 2: Stacked area chart for composition
         ======================================================================== */}
      <section className="space-y-4">
        <Card>
          <CardHeader>
            <CardTitle>Chart title</CardTitle>
            <CardDescription>
              Chart description (stacked, TWh or other units).
            </CardDescription>
          </CardHeader>
          <CardContent>
            <ChartContainer config={chartConfig} className="h-[360px] w-full">
              <AreaChart data={byCategory} margin={{ left: 12, right: 12, top: 8 }}>
                <CartesianGrid vertical={false} />
                <XAxis dataKey="year" tickLine={false} axisLine={false} />
                <YAxis tickLine={false} axisLine={false} tickFormatter={(v) => fmtInt(v)} />
                <ChartTooltip content={<ChartTooltipContent />} />
                <ChartLegend content={<ChartLegendContent />} />
                <Area
                  type="monotone"
                  dataKey="category1"
                  stackId="a"
                  stroke="var(--color-category1)"
                  fill="var(--color-category1)"
                  fillOpacity={0.35}
                />
                <Area
                  type="monotone"
                  dataKey="category2"
                  stackId="a"
                  stroke="var(--color-category2)"
                  fill="var(--color-category2)"
                  fillOpacity={0.35}
                />
                <Area
                  type="monotone"
                  dataKey="category3"
                  stackId="a"
                  stroke="var(--color-category3)"
                  fill="var(--color-category3)"
                  fillOpacity={0.35}
                />
              </AreaChart>
            </ChartContainer>
          </CardContent>
        </Card>
      </section>

      {/* ========================================================================
         NARRATIVE SECTION 2
         ======================================================================== */}
      <section className="space-y-4">
        <p className="text-foreground leading-relaxed">
          Continue the story with more analysis. Explain patterns, trends,
          and what drives them. Use specific examples from the data.
        </p>
      </section>

      {/* ========================================================================
         ADD MORE CHART AND NARRATIVE SECTIONS AS NEEDED
         ======================================================================== */}

      {/* ========================================================================
         KEY TAKEAWAYS
         ======================================================================== */}
      <section className="space-y-4">
        <h2 className="text-2xl font-semibold">Key takeaways</h2>
        <ul className="list-disc pl-6 space-y-2 text-foreground">
          <li>
            Key takeaway 1 with specific numbers and context.
          </li>
          <li>
            Key takeaway 2 explaining an important pattern or insight.
          </li>
          <li>
            Key takeaway 3 with implications or broader significance.
          </li>
          <li>
            Key takeaway 4 connecting to other topics or future directions.
          </li>
        </ul>
      </section>

      {/* ========================================================================
         OTHER QUESTIONS TO EXPLORE
         ======================================================================== */}
      <section className="space-y-4">
        <h2 className="text-2xl font-semibold">Other questions to explore</h2>
        <ul className="list-disc pl-6 space-y-2 text-foreground">
          <li>Question 1 about follow-up analysis or deeper investigation.</li>
          <li>Question 2 about related topics or additional data sources.</li>
          <li>Question 3 about implications or future trends.</li>
          <li>Question 4 about methodological improvements or alternatives.</li>
        </ul>
      </section>
    </NotebookTemplate>
  );
}