"use client";

import { motion, AnimatePresence } from "framer-motion";
import { formatNumber } from "@/app/utils";
import clsx from "clsx";

/* Heroicons (outline) */
import {
  ArrowTrendingUpIcon,
  ClipboardDocumentCheckIcon,
  ScaleIcon,
  HomeIcon,
  BoltIcon,
  FireIcon,
  ChartBarIcon,
  WrenchIcon,
} from "@heroicons/react/24/outline";

/* Lucide */
import { Gauge } from "lucide-react";

/* ───────────────────────────────────────────── */
/* Types                                        */
/* ───────────────────────────────────────────── */

interface ScenarioFinancialDrawerProps {
  open: boolean;
  metrics: any | null;
  loading?: boolean;
}

/* ───────────────────────────────────────────── */
/* Gradient Tokens                              */
/* ───────────────────────────────────────────── */

const gradients = {
  green: "bg-gradient-to-r from-green-700 via-green-400 to-green-700",
  blue: "bg-gradient-to-r from-brandblue via-sky-400 to-brandblue",
  purple: "bg-gradient-to-r from-purple-700 via-purple-400 to-purple-700",
};

/* ───────────────────────────────────────────── */
/* Gradient Card Shell                          */
/* ───────────────────────────────────────────── */

function GradientCard({
  gradient,
  variant,
  children,
}: {
  gradient: string;
  variant: "green" | "blue" | "purple";
  children: React.ReactNode;
}) {
  return (
    <div
      className={clsx(
        "relative rounded-lg p-[2px] gradient-card",
        gradient,
        `gradient-${variant}`,
      )}
    >
      <div className="rounded-[7px] bg-white h-full">{children}</div>
    </div>
  );
}

/* ───────────────────────────────────────────── */
/* Single Metric Card                           */
/* ───────────────────────────────────────────── */

function Metric({
  label,
  value,
  icon: Icon,
  color,
  gradient,
  variant = "green",
  loading = false,
}: {
  label: string;
  value: string | number;
  icon: React.ComponentType<React.SVGProps<SVGSVGElement>>;
  color: string;
  gradient: string;
  variant?: "green" | "blue" | "purple";
  loading?: boolean;
}) {
  if (loading || !value) {
    return (
      <GradientCard gradient={gradient} variant={variant}>
        <div className="p-4 h-full animate-pulse">
          <div className="h-4 w-1/2 bg-gray-200 rounded mb-3" />
          <div className="h-6 w-3/4 bg-gray-200 rounded" />
        </div>
      </GradientCard>
    );
  }
  return (
    <GradientCard gradient={gradient} variant={variant}>
      <div className="flex flex-col items-center justify-center p-4 h-full text-center">
        {loading ? (
          <div className="w-full animate-pulse space-y-3">
            <div className="h-6 w-6 mx-auto rounded bg-gray-200" />
            <div className="h-8 w-2/3 mx-auto rounded bg-gray-200" />
            <div className="h-3 w-1/2 mx-auto rounded bg-gray-200" />
          </div>
        ) : (
          <>
            <Icon className={clsx("h-6 w-6 mb-2", color)} />
            <span className="text-3xl font-semibold text-gray-900">
              {value}
            </span>
            <span className="mt-1 text-xs uppercase tracking-wide font-semibold text-gray-500">
              {label}
            </span>
          </>
        )}
      </div>
    </GradientCard>
  );
}

/* ───────────────────────────────────────────── */
/* Paired Metric Card (Reusable Everywhere)     */
/* ───────────────────────────────────────────── */

function PairedMetric({
  title,
  icon: Icon,
  primary,
  secondary,
  gradient,
  iconClassName = "text-gray-700",
  variant = "green",
  loading = false,
}: {
  title: string;
  icon: React.ComponentType<React.SVGProps<SVGSVGElement>>;
  primary: { label: string; value: string };
  secondary: { label: string; value: string };
  gradient: string;
  iconClassName?: string;
  variant?: "green" | "blue" | "purple";
  loading?: boolean;
}) {
  if (loading || !primary.value || !secondary.value) {
    return (
      <GradientCard gradient={gradient} variant={variant}>
        <div className="p-4 h-full animate-pulse">
          <div className="h-4 w-1/2 bg-gray-200 rounded mb-3" />
          <div className="h-6 w-3/4 bg-gray-200 rounded" />
        </div>
      </GradientCard>
    );
  }

  return (
    <GradientCard gradient={gradient} variant={variant}>
      <div className="p-4 h-full">
        {loading ? (
          <div className="animate-pulse space-y-4">
            <div className="h-4 w-1/3 rounded bg-gray-200" />
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <div className="h-3 w-2/3 rounded bg-gray-200" />
                <div className="h-6 w-full rounded bg-gray-200" />
              </div>
              <div className="space-y-2">
                <div className="h-3 w-2/3 rounded bg-gray-200" />
                <div className="h-6 w-full rounded bg-gray-200" />
              </div>
            </div>
          </div>
        ) : (
          <>
            <div className="flex items-center gap-2 mb-3">
              <Icon className={clsx("h-5 w-5", iconClassName)} />
              <span className="text-sm font-semibold text-gray-900">
                {title}
              </span>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <p className="text-xs text-gray-500">{primary.label}</p>
                <p className="text-xl font-semibold text-gray-900">
                  {primary.value}
                </p>
              </div>

              <div>
                <p className="text-xs text-gray-500">{secondary.label}</p>
                <p className="text-xl font-semibold text-gray-900">
                  {secondary.value}
                </p>
              </div>
            </div>
          </>
        )}
      </div>
    </GradientCard>
  );
}

/* ───────────────────────────────────────────── */
/* Section Header                               */
/* ───────────────────────────────────────────── */

function Section({
  title,
  subtitle,
  icon: Icon,
  gradient,
  accentColor,
  children,
}: {
  title: string;
  subtitle: string;
  icon: React.ComponentType<React.SVGProps<SVGSVGElement>>;
  gradient: string;
  accentColor: string;
  children: React.ReactNode;
}) {
  return (
    <div className="space-y-4">
      <div className="flex items-start gap-3">
        <div className={clsx("w-1 rounded-full self-stretch", gradient)} />

        <div
          className={clsx(
            "rounded-lg p-2 bg-white shadow-sm border",
            accentColor,
          )}
        >
          <Icon className="h-5 w-5" />
        </div>

        <div className="pt-0.5">
          <h4 className="text-base font-semibold text-gray-900">{title}</h4>
          <p className="text-xs text-gray-500">{subtitle}</p>
        </div>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3 print-grid-3">
        {children}
      </div>
    </div>
  );
}

/* ───────────────────────────────────────────── */
/* Loading Skeleton for dashboard cards          */
/* ───────────────────────────────────────────── */

function LoadingOverlay() {
  return (
    <div className="absolute inset-0 z-20 rounded-lg bg-white/70 backdrop-blur-sm">
      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4 p-6 animate-pulse">
        {Array.from({ length: 9 }).map((_, i) => (
          <div key={i} className="h-28 rounded-lg bg-gray-200" />
        ))}
      </div>
    </div>
  );
}

/* ───────────────────────────────────────────── */
/* Main Drawer                                 */
/* ───────────────────────────────────────────── */

export function ScenarioFinancialDrawer({
  open,
  metrics,
  loading = false,
}: ScenarioFinancialDrawerProps) {
  return (
    <AnimatePresence initial={false}>
      {open && (
        <motion.div
          initial={{ height: 0, opacity: 0 }}
          animate={{ height: "auto", opacity: 1 }}
          exit={{ height: 0, opacity: 0 }}
          transition={{ duration: 0.35, ease: "easeInOut" }}
          className="overflow-hidden"
        >
          <div className="rounded-lg border border-gray-200 bg-white shadow-sm mt-4 p-6 space-y-6">
            <h3 className="text-lg font-semibold text-brandblue">
              Scenario Impact Summary
            </h3>

            {/* BENEFITS */}
            <Section
              title="Benefits"
              subtitle="Impact for occupants and the environment"
              icon={ArrowTrendingUpIcon}
              gradient={gradients.green}
              accentColor="border-green-200 text-green-700"
            >
              <PairedMetric
                title="Carbon impact"
                icon={BoltIcon}
                iconClassName="text-green-700"
                primary={{
                  label: "Total carbon saved (t/yr)",
                  value: metrics ? formatNumber(metrics.totalCarbonSaved) : "",
                }}
                secondary={{
                  label: "Average per unit (t/yr)",
                  value: metrics
                    ? formatNumber(metrics.averageCaribonSaved)
                    : "",
                }}
                gradient={gradients.green}
                variant="green"
                loading={loading}
              />

              <PairedMetric
                title="Bill savings"
                icon={FireIcon}
                iconClassName="text-green-700"
                primary={{
                  label: "Total bill savings (£/yr)",
                  value: metrics
                    ? `£${formatNumber(metrics.totalBillsSaved)}`
                    : "",
                }}
                secondary={{
                  label: "Average per unit (£/yr)",
                  value: metrics
                    ? `£${formatNumber(metrics.averageBillsSaved)}`
                    : "",
                }}
                gradient={gradients.green}
                variant="green"
                loading={loading}
              />

              <Metric
                label="Homes upgraded"
                value={metrics ? metrics.nUnits : ""}
                icon={HomeIcon}
                color="text-green-700"
                gradient={gradients.green}
                variant="green"
                loading={loading}
              />
            </Section>

            {/* COSTS */}
            <Section
              title="Costs"
              subtitle="Investment required to deliver the works"
              icon={ClipboardDocumentCheckIcon}
              gradient={gradients.blue}
              accentColor="border-brandblue text-brandblue"
            >
              <PairedMetric
                title="Delivery costs"
                icon={WrenchIcon}
                iconClassName="text-blue-600"
                primary={{
                  label: "Construction works",
                  value: metrics
                    ? `£${formatNumber(metrics.constructionCost)}`
                    : "",
                }}
                secondary={{
                  label: "Project delivery",
                  value: metrics ? `£${formatNumber(metrics.pcCost)}` : "",
                }}
                gradient={gradients.blue}
                variant="blue"
                loading={loading}
              />

              <Metric
                label="Gross cost per unit"
                value={metrics ? `£${formatNumber(metrics.grossPerUnit)}` : ""}
                icon={HomeIcon}
                color="text-blue-600"
                gradient={gradients.blue}
                variant="blue"
                loading={loading}
              />

              <Metric
                label="Contingency"
                value={metrics ? `£${formatNumber(metrics.contingency)}` : ""}
                icon={Gauge}
                color="text-blue-600"
                gradient={gradients.blue}
                variant="blue"
                loading={loading}
              />
            </Section>

            {/* COST EFFECTIVENESS */}
            <Section
              title="Cost effectiveness"
              subtitle="Value for money of the investment"
              icon={ScaleIcon}
              gradient={gradients.purple}
              accentColor="border-purple-200 text-purple-700"
            >
              <PairedMetric
                title="Efficiency metrics"
                icon={ChartBarIcon}
                iconClassName="text-purple-700"
                primary={{
                  label: "£ per SAP point",
                  value: metrics ? `£${formatNumber(metrics.costPerSap)}` : "",
                }}
                secondary={{
                  label: "£ per tonne CO₂",
                  value: metrics ? `£${formatNumber(metrics.costPerCo2)}` : "",
                }}
                gradient={gradients.purple}
                variant="purple"
                loading={loading}
              />
            </Section>
          </div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
