import { SectionDivider } from "../SectionDivider";
import { ScenarioFinancialDrawer } from "../ScenarioFinancialDrawer";
import { DashboardSummaryCards } from "../DashboardSummaryCards";
import { EpcQualityCards } from "../EpcQualityCards";

import { loadBaselineMetrics } from "@/app/portfolio/[slug]/(portfolio)/reporting/databaseFunctions";

import type { BaselineMetrics } from "../types";
import Image from "next/image";
import { AutoPrint } from "./AutoPrint";

/* ---------------------------------------------
   Base URL helper (Vercel + local)
--------------------------------------------- */

function getBaseUrl() {
  if (process.env.VERCEL_BRANCH_URL) {
    return `https://${process.env.VERCEL_BRANCH_URL}`;
  }

  if (process.env.VERCEL_URL) {
    return `https://${process.env.VERCEL_URL}`;
  }

  return "http://localhost:3000";
}

/* ---------------------------------------------
   Server-side fetch for scenario metrics
--------------------------------------------- */

async function fetchScenarioReport({
  portfolioId,
  scenarioId,
}: {
  portfolioId: number;
  scenarioId: number;
}) {
  const res = await fetch(
    `${getBaseUrl()}/api/portfolio/${portfolioId}/scenario/${scenarioId}/metrics`,
    { cache: "no-store" }
  );

  if (!res.ok) {
    throw new Error("Failed to load scenario report");
  }

  return res.json();
}

/* ---------------------------------------------
   Page
--------------------------------------------- */

export default async function ReportingPdfPage(props: {
  params: Promise<{ slug: string }>;
  searchParams: Promise<{ scenarioId?: string }>;
}) {
  const params = await props.params;
  const searchParams = await props.searchParams;
  const scenarioId = Number(searchParams.scenarioId);

  if (!scenarioId) {
    return <div>No scenario selected</div>;
  }

  const portfolioId = Number(params.slug);

  /* ---------------------------------------------
     Fetch baseline + scenario (parallel)
  --------------------------------------------- */

  const [baseline, scenarioData]: [BaselineMetrics, any] = await Promise.all([
    loadBaselineMetrics(portfolioId),
    fetchScenarioReport({ portfolioId, scenarioId }),
  ]);

  /* ---------------------------------------------
     Scenario-only metrics for drawer
  --------------------------------------------- */

  const scenarioOverlay = scenarioData
    ? {
        avgSap: {
          baseline: baseline.averages.avg_sap ?? 0,
          scenario: Number(scenarioData.avg_sap),
        },
        avgCarbon: {
          baseline: Number(baseline.averages.avg_carbon ?? 0),
          scenario: Number(scenarioData.avg_carbon),

          baselineTotal: Number(baseline.totals.total_carbon ?? 0),
          scenarioTotal: Number(scenarioData.total_carbon ?? 0),
        },
        avgBills: {
          baseline: baseline.averages.avg_bills ?? 0,
          scenario: scenarioData.avg_bills,
          baselineTotal: baseline.totals.total_bills ?? 0,
          scenarioTotal: scenarioData.total_bills,
        },
        valuation: { baseline: null, scenario: null },
        scenarioEpcBands: scenarioData.scenario_epc_counts,
      }
    : null;

  const scenarioSpecific = {
    constructionCost: scenarioData.construction_cost,
    pcCost: scenarioData.pc_cost,
    contingency: scenarioData.contingency,
    funding: scenarioData.total_funding,
    costPerSap:
      scenarioData.construction_cost > 0
        ? scenarioData.gross_per_unit /
          (scenarioData.avg_sap - (baseline.averages.avg_sap ?? 0))
        : 0,
    costPerCo2:
      scenarioData.construction_cost > 0
        ? (scenarioData.construction_cost + scenarioData.pc_cost) /
          scenarioData.total_carbon
        : 0,
    netCost: scenarioData.net_cost,
    grossPerUnit: scenarioData.gross_per_unit,
    nUnits: scenarioData.n_units_upgraded,
    totalCarbonSaved:
      (baseline.totals.total_carbon ?? 0) - scenarioData.total_carbon,
    totalBillsSaved:
      (baseline.totals.total_bills ?? 0) - scenarioData.total_bills,
    averageCaribonSaved:
      ((baseline.totals.total_carbon ?? 0) - scenarioData.total_carbon) /
      scenarioData.n_units_upgraded,
    averageBillsSaved:
      ((baseline.totals.total_bills ?? 0) - scenarioData.total_bills) /
      scenarioData.n_units_upgraded,
  };

  return (
    <div className="print-page">
      <div className="print-root space-y-4">
        <AutoPrint />
        {/* ------------------------------------------------
          Branded header
      ------------------------------------------------ */}
        <header className="flex items-center gap-3 border-b pb-2">
          <Image
            src="/domna_logo_blue_transparent_background.png"
            alt="Domna Logo"
            width={140}
            height={40}
          />
          <div>
            <h1 className="text-xl font-semibold">Retrofit Scenario Report</h1>
          </div>
        </header>

        {/* ------------------------------------------------
          Scenario Impact Summary
      ------------------------------------------------ */}
        <SectionDivider
          title="Scenario Impact Summary"
          subtitle="Financial, carbon and energy outcomes"
        />

        <ScenarioFinancialDrawer open={true} metrics={scenarioSpecific} />

        {/* ------------------------------------------------
          Portfolio Summary (baseline)
      ------------------------------------------------ */}
        <div className="page-break" />
        <SectionDivider
          title="Portfolio Summary"
          subtitle="Headline performance indicators"
        />

        <DashboardSummaryCards
          total={baseline.total}
          totals={baseline.totals}
          averages={baseline.averages}
          estimatedCounts={baseline.estimatedCounts}
          scenarioOverlay={scenarioOverlay}
        />

        {/* ------------------------------------------------
          EPC Quality (baseline)
      ------------------------------------------------ */}
        <SectionDivider
          title="EPC Quality"
          subtitle="Condition, compliance and performance"
        />

        <EpcQualityCards
          estimatedCounts={baseline.estimatedCounts}
          total={baseline.total}
          expiredEpcs={baseline.expiredEpcs}
          likelyDowngrades={baseline.likelyDowngrades}
        />
      </div>
    </div>
  );
}
