"use client";

import { useMemo, useState } from "react";
import { motion } from "framer-motion";
import {
  AnimatedSection,
  AnimatedItem,
} from "@/components/ui/AnimatedSection";
import EyebrowBadge from "@/components/ui/EyebrowBadge";
import ParallaxImage from "@/components/ui/ParallaxImage";
import {
  EXPOSURES,
  calculateSavings,
  formatCurrency,
  formatNumber,
  type Exposure,
} from "@/lib/savings";

const MONTHS = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"];

function Slider({
  label,
  value,
  min,
  max,
  step,
  display,
  onChange,
}: {
  label: string;
  value: number;
  min: number;
  max: number;
  step: number;
  display: string;
  onChange: (v: number) => void;
}) {
  const fill = ((value - min) / (max - min)) * 100;
  return (
    <div>
      <div className="mb-3 flex items-baseline justify-between">
        <label className="text-[10px] font-medium tracking-wider text-zinc-500 uppercase">
          {label}
        </label>
        <span className="font-mono text-sm font-semibold text-zinc-900 tabular-nums">
          {display}
        </span>
      </div>
      <input
        type="range"
        className="solar-range"
        min={min}
        max={max}
        step={step}
        value={value}
        aria-label={label}
        style={{ ["--fill" as string]: `${fill}%` }}
        onChange={(e) => onChange(Number(e.target.value))}
      />
    </div>
  );
}

export default function SavingsBento() {
  const [monthlyBill, setMonthlyBill] = useState(3000);
  const [roofArea, setRoofArea] = useState(850);
  const [exposure, setExposure] = useState<Exposure>("good");

  const result = useMemo(
    () => calculateSavings({ monthlyBill, roofArea, exposure }),
    [monthlyBill, roofArea, exposure],
  );

  const peakYield = Math.max(...result.monthlyYield);

  return (
    <section
      id="savings"
      className="relative z-10 overflow-hidden px-6 py-24 md:px-8 md:py-32"
    >
      {/* Full-bleed photographic backdrop — no scrim so the image is 100% visible. */}
      <ParallaxImage
        src="/images/savings/bg.jpg"
        alt=""
        strength={0.1}
        className="z-0"
      />

      <AnimatedSection className="relative z-10 mx-auto max-w-[1400px]">
        <AnimatedItem className="mb-14 flex flex-col items-center text-center">
          <EyebrowBadge className="mb-6">Run the numbers</EyebrowBadge>
          <h2
            className="max-w-[20ch] text-3xl font-bold tracking-tighter text-zinc-950 md:text-5xl"
            style={{ textShadow: "0 0 30px rgba(255,255,255,0.9), 0 2px 4px rgba(0,0,0,0.5), 0 4px 16px rgba(0,0,0,0.4), 2px 2px 0px rgba(255,255,255,0.6)" }}
          >
            Move two sliders. See twenty-five years.
          </h2>
          <p
            className="mt-5 max-w-[55ch] text-base font-semibold leading-relaxed text-zinc-900 md:text-lg"
            style={{ textShadow: "0 0 20px rgba(255,255,255,0.95), 0 1px 3px rgba(0,0,0,0.5), 0 3px 10px rgba(0,0,0,0.3)" }}
          >
            Every figure below recalculates live against your bill, your roof
            and your shading — the same model our surveyors use on site.
          </p>
        </AnimatedItem>

        <div className="grid grid-cols-1 gap-5 md:grid-cols-[2fr_3fr]">
          {/* Controls */}
          <AnimatedItem
            className="card-surface flex flex-col justify-center gap-8 p-7 max-md:p-5 !bg-[#fffdf8]"
          >
            <Slider
              label="Monthly electricity bill"
              value={monthlyBill}
              min={500}
              max={20000}
              step={250}
              display={formatCurrency(monthlyBill)}
              onChange={setMonthlyBill}
            />
            <Slider
              label="Usable roof area"
              value={roofArea}
              min={200}
              max={2500}
              step={50}
              display={`${formatNumber(roofArea)} sq ft`}
              onChange={setRoofArea}
            />
            <div>
              <span className="mb-3 block text-[10px] font-medium tracking-wider text-zinc-500 uppercase">
                How much shade does your roof get?
              </span>
              <div className="inset-surface flex gap-1 rounded-2xl p-1">
                {EXPOSURES.map((e) => (
                  <button
                    key={e.id}
                    onClick={() => setExposure(e.id)}
                    aria-pressed={exposure === e.id}
                    className={`min-h-11 flex-1 rounded-xl px-2 text-xs font-medium transition-all duration-300 ${
                      exposure === e.id
                        ? "bg-white text-zinc-900 shadow-[var(--pill-shadow)]"
                        : "text-zinc-500 hover:text-zinc-800"
                    }`}
                  >
                    {e.label}
                  </button>
                ))}
              </div>
            </div>
            {result.roofLimited && (
              <p className="text-xs leading-relaxed text-amber-700">
                Your roof caps the array before it fully covers your usage —
                the figures below reflect what actually fits.
              </p>
            )}
          </AnimatedItem>

          {/* Headline savings */}
          <AnimatedItem
            className="card-surface relative flex flex-col justify-between overflow-hidden p-7 max-md:p-5 !bg-[#fffdf8]"
          >
            <div
              className="pointer-events-none absolute -top-24 -right-24 h-64 w-64 rounded-full opacity-60 blur-3xl"
              style={{
                background:
                  "radial-gradient(circle, rgba(245,158,11,0.28), transparent 70%)",
              }}
            />
            <div className="relative">
              <span className="text-[10px] font-medium tracking-wider text-zinc-500 uppercase">
                Estimated 25-year net savings
              </span>
              <div className="mt-3 flex items-baseline gap-3">
                <motion.span
                  key={Math.round(result.lifetimeSavings)}
                  initial={{ opacity: 0.4, y: 6 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ type: "spring", stiffness: 100, damping: 20 }}
                  className="text-5xl font-semibold tracking-tighter text-orange-600 tabular-nums md:text-7xl"
                >
                  {formatCurrency(result.lifetimeSavings)}
                </motion.span>
              </div>
              <p className="mt-4 max-w-[48ch] text-sm leading-relaxed text-zinc-600">
                After the {formatCurrency(result.netCost)} net install cost is
                paid back — {formatNumber(result.paybackYears, 1)} years in,
                on a system built for a 25-year design lifespan.
              </p>
            </div>

            <div className="relative mt-8 grid grid-cols-3 gap-3">
              {[
                {
                  label: "Monthly",
                  value: formatCurrency(result.monthlySavings),
                },
                {
                  label: "Payback",
                  value: `${formatNumber(result.paybackYears, 1)} yr`,
                },
                {
                  label: "Bill offset",
                  value: `${Math.round(result.billOffset)}%`,
                },
              ].map((s) => (
                <div
                  key={s.label}
                  className="card-surface-nested px-4 py-3.5 max-md:px-3"
                >
                  <div className="font-mono text-lg font-semibold text-zinc-900 tabular-nums">
                    {s.value}
                  </div>
                  <div className="mt-0.5 text-[10px] tracking-wider text-zinc-500 uppercase">
                    {s.label}
                  </div>
                </div>
              ))}
            </div>
          </AnimatedItem>
        </div>

        {/* Row 2 */}
        <div className="mt-5 grid grid-cols-1 gap-5 md:grid-cols-[3fr_2fr]">
          <AnimatedItem
            className="card-surface p-7 max-md:p-5 !bg-[#fffdf8]"
          >
            <div className="mb-6 flex items-baseline justify-between">
              <div>
                <span className="text-[10px] font-medium tracking-wider text-zinc-500 uppercase">
                  Projected monthly generation
                </span>
                <div className="mt-1 font-mono text-2xl font-semibold text-zinc-900 tabular-nums">
                  {formatNumber(result.annualYield)}{" "}
                  <span className="text-sm font-normal text-zinc-500">
                    kWh / year
                  </span>
                </div>
              </div>
              <span className="pill-surface px-3 py-1.5 font-mono text-xs font-semibold text-zinc-700">
                {formatNumber(result.systemKw, 2)} kW
              </span>
            </div>
            <div className="flex h-44 items-end gap-1.5 md:gap-2.5">
              {result.monthlyYield.map((y, i) => (
                <div
                  key={i}
                  className="group flex flex-1 flex-col items-center gap-2"
                >
                  <motion.div
                    className="w-full rounded-t-md bg-gradient-to-t from-amber-500 to-orange-400"
                    initial={false}
                    animate={{ height: `${(y / peakYield) * 100}%` }}
                    transition={{ type: "spring", stiffness: 100, damping: 20 }}
                    style={{ minHeight: 4 }}
                    title={`${MONTHS[i]}: ${formatNumber(y)} kWh`}
                  />
                  <span className="font-mono text-[10px] text-zinc-400">
                    {MONTHS[i]}
                  </span>
                </div>
              ))}
            </div>
          </AnimatedItem>

          <AnimatedItem
            className="card-surface flex flex-col justify-between p-7 max-md:p-5 !bg-[#fffdf8]"
          >
            <div>
              <span className="text-[10px] font-medium tracking-wider text-zinc-500 uppercase">
                Array footprint
              </span>
              <div className="mt-3 flex items-baseline gap-2">
                <span className="font-mono text-4xl font-semibold text-zinc-900 tabular-nums">
                  {result.panels}
                </span>
                <span className="text-sm text-zinc-500">panels</span>
              </div>
            </div>
            <div className="mt-6">
              <div className="mb-2 flex justify-between text-xs text-zinc-500">
                <span>Roof used</span>
                <span className="font-mono tabular-nums">
                  {Math.round(result.roofUsedPct)}%
                </span>
              </div>
              <div className="inset-surface h-2.5 w-full overflow-hidden rounded-full">
                <motion.div
                  className="h-full rounded-full bg-gradient-to-r from-amber-500 to-orange-600"
                  initial={false}
                  animate={{ width: `${result.roofUsedPct}%` }}
                  transition={{ type: "spring", stiffness: 100, damping: 20 }}
                />
              </div>
              <p className="mt-4 text-xs leading-relaxed text-zinc-500">
                Laid out at {formatNumber(result.systemKw, 2)} kW across{" "}
                {formatNumber(roofArea)} sq ft, leaving statutory access
                setbacks clear.
              </p>
            </div>
          </AnimatedItem>
        </div>

        {/* Row 3 */}
        <div className="mt-5 grid grid-cols-1 gap-5 md:grid-cols-3">
          {[
            {
              label: "CO₂ avoided over 25 years",
              value: `${formatNumber(result.co2Tonnes, 1)} t`,
              note: "Versus grid-average generation for your region.",
            },
            {
              label: "Equivalent mature trees",
              value: formatNumber(result.trees),
              note: "Absorbing the same carbon every year the array runs.",
            },
            {
              label: "Install cost after subsidy",
              value: formatCurrency(result.netCost),
              note: `${formatCurrency(result.grossCost)} before the ${formatCurrency(result.subsidy)} PM Surya Ghar subsidy — we file the paperwork.`,
            },
          ].map((c) => (
            <AnimatedItem
              key={c.label}
              className="card-surface p-7 max-md:p-5 !bg-[#fffdf8]"
            >
              <span className="text-[10px] font-medium tracking-wider text-zinc-500 uppercase">
                {c.label}
              </span>
              <div className="mt-3 font-mono text-3xl font-semibold text-zinc-900 tabular-nums">
                {c.value}
              </div>
              <p className="mt-3 text-sm leading-relaxed text-zinc-600">
                {c.note}
              </p>
            </AnimatedItem>
          ))}
        </div>

        <AnimatedItem>
          <p className="mt-8 text-center text-xs text-white/60">
            Estimates only. Final figures come from your roof survey, tariff and
            local incentive schedule.
          </p>
        </AnimatedItem>
      </AnimatedSection>
    </section>
  );
}
