"use client";

import { useSearchParams } from "next/navigation";
import { PreviewLink } from "@/components/layout/preview-context";
import { DataTable, type Column } from "@/components/shared/data-table";
import { Field, SelectField } from "@/components/shared/field";
import { Metric, PageHeader, Panel } from "@/components/shared/page";
import { TableExport, type ExportRecord } from "@/components/shared/table-export";
import { Button } from "@/components/ui/button";
import { useQueryUpdate } from "@/components/shared/tabs";
import { tableExportData, type ExportFormat } from "@/lib/export";
import {
  financialReportDateRange,
  mapFinancialReportItem,
  scopeFinancialReportRows,
  type FinancialReportData,
  type FinancialReportRow,
} from "./financial-report-contract";

function formatNumber(value: number | null, maximumFractionDigits = 2): string {
  return value === null
    ? "—"
    : value.toLocaleString("en-US", { maximumFractionDigits });
}

function formatCurrency(value: number | null, currency: string): string {
  if (value === null) return "—";
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency,
    maximumFractionDigits: 2,
  }).format(value);
}

function downloadFilename(response: Response, format: ExportFormat): string {
  const contentDisposition = response.headers.get("content-disposition") ?? "";
  const encoded = /filename\*=UTF-8''([^;]+)/i.exec(contentDisposition)?.[1];
  const regular = /filename="?([^";]+)"?/i.exec(contentDisposition)?.[1];
  const candidate = encoded ?? regular;
  if (candidate) {
    try {
      const decoded = decodeURIComponent(candidate).replace(/[\\/\0]/g, "_");
      if (decoded.trim()) return decoded;
    } catch {
      // Use a safe generated filename when the upstream filename is malformed.
    }
  }
  return `financial-report.${format === "xlsx" ? "xlsx" : format}`;
}

async function downloadFinancialReport(
  rows: readonly ExportRecord[],
  format: ExportFormat,
  startDate: string,
  endDate: string,
): Promise<void> {
  if (rows.length > 100) {
    throw new Error("Select 100 or fewer locations for each download.");
  }

  const type = format === "xlsx" ? "excel" : format;
  const query = new URLSearchParams({
    ...financialReportDateRange(startDate, endDate),
    type,
  });
  const response = await fetch(`/api/financial-report/download?${query}`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ location_ids: rows.map((row) => row.id) }),
    cache: "no-store",
  });
  if (!response.ok) {
    const errorBody: unknown = await response.json().catch(() => null);
    const message =
      typeof errorBody === "object" &&
      errorBody !== null &&
      "error" in errorBody &&
      typeof errorBody.error === "string"
        ? errorBody.error
        : "Unable to download the financial report. Please retry.";
    throw new Error(message);
  }

  const objectUrl = URL.createObjectURL(await response.blob());
  const anchor = document.createElement("a");
  anchor.href = objectUrl;
  anchor.download = downloadFilename(response, format);
  anchor.click();
  setTimeout(() => URL.revokeObjectURL(objectUrl), 1_000);
}

export function FinancialReportLive({
  data,
  error,
  startDate,
  endDate,
  locationId,
  embedded = false,
  canExport,
}: {
  data: FinancialReportData | null;
  error: string | null;
  startDate: string;
  endDate: string;
  locationId?: string;
  embedded?: boolean;
  canExport: boolean;
}) {
  const params = useSearchParams();
  const update = useQueryUpdate();
  const selectedLocationId = locationId ?? params.get("location_id") ?? "";
  const requestedContractType = params.get("contract_type") ?? "";
  const isSingleLocation = selectedLocationId.length > 0;
  const allRows = (data?.items ?? [])
    .filter((item) => !locationId || item.location_id === locationId)
    .map(mapFinancialReportItem);
  const rowScope = scopeFinancialReportRows(
    allRows,
    selectedLocationId,
    requestedContractType,
  );
  const { rows, contractTypes, contractType: selectedContractType } = rowScope;
  const selectedRow = allRows.find(
    (row) => row.locationId === selectedLocationId,
  );
  const displayedMetrics = isSingleLocation ? selectedRow : data?.summary;
  const displayedLocationCount = isSingleLocation
    ? Number(!!selectedRow)
    : (data?.summary.total_locations ?? 0);
  const displayedContractLocationCount = isSingleLocation
    ? Number((selectedRow?.contractCount ?? 0) > 0)
    : (data?.summary.locations_with_contract ?? 0);
  const displayedCurrency =
    displayedMetrics?.currency ?? data?.summary.currency ?? "IDR";
  const filterGridColumns = isSingleLocation
    ? locationId
      ? "md:grid-cols-3 xl:grid-cols-3"
      : "md:grid-cols-3 xl:grid-cols-4"
    : "md:grid-cols-3 xl:grid-cols-6";

  const columns: Column<FinancialReportRow>[] = [
    {
      key: "name",
      label: "Location",
      render: (row) => (
        <PreviewLink
          className="text-foreground hover:underline"
          href={`/reports/financial-report?${new URLSearchParams({
            location_id: row.locationId,
            start_date: startDate,
            end_date: endDate,
          }).toString()}`}
        >
          {row.name}
        </PreviewLink>
      ),
    },
    {
      key: "chargepointCount",
      label: "Chargepoints",
      render: (row) => formatNumber(row.chargepointCount, 0),
    },
    {
      key: "total_kwh",
      label: "Total kWh",
      render: (row) => formatNumber(row.total_kwh),
    },
    {
      key: "total_time_hours",
      label: "Time (Hours)",
      render: (row) => formatNumber(row.total_time_hours),
    },
    {
      key: "total_gross_revenue",
      label: "Gross Revenue",
      render: (row) => formatCurrency(row.total_gross_revenue, row.currency),
    },
    {
      key: "total_deduction",
      label: "Deduction",
      render: (row) => formatCurrency(row.total_deduction, row.currency),
    },
    {
      key: "total_electrical_bill",
      label: "Electrical Bill",
      render: (row) => formatCurrency(row.total_electrical_bill, row.currency),
    },
    {
      key: "total_net_revenue",
      label: "Net Revenue",
      render: (row) => formatCurrency(row.total_net_revenue, row.currency),
    },
    {
      key: "total_cpo_share",
      label: "CPO Share",
      render: (row) => formatCurrency(row.total_cpo_share, row.currency),
    },
    {
      key: "total_bm_share",
      label: "Building Management Share",
      render: (row) => formatCurrency(row.total_bm_share, row.currency),
    },
    {
      key: "total_investor_share",
      label: "Investor Share",
      render: (row) => formatCurrency(row.total_investor_share, row.currency),
    },
  ];

  const onExport = (records: readonly ExportRecord[], format: ExportFormat) =>
    downloadFinancialReport(records, format, startDate, endDate);
  const singleLocationExportRecords: ExportRecord[] = selectedRow
    ? [
        {
          id: selectedRow.id,
          label: selectedRow.name,
          data: tableExportData(selectedRow, columns),
        },
      ]
    : [];

  return (
    <div className="space-y-5">
      {!embedded && (
        <PageHeader title="Financial Report for CPO & Partner" />
      )}
      <Panel
        title={
          embedded || isSingleLocation
            ? "Financial Report"
            : "Locations Financial"
        }
        description={
          isSingleLocation
            ? "Performance summary for this location and date range."
            : "Location-level financial aggregates returned by Monet for the selected date range."
        }
      >
        <form
          className={`grid items-end gap-4 p-5 ${filterGridColumns}`}
          onSubmit={(event) => {
            event.preventDefault();
            const form = new FormData(event.currentTarget);
            update({
              start_date: String(form.get("start_date") ?? ""),
              end_date: String(form.get("end_date") ?? ""),
              paginate_page: null,
            });
          }}
        >
          {!locationId && (
            <SelectField
              label="Location"
              value={selectedLocationId}
              options={[
                { value: "", label: "All Locations" },
                ...allRows.map((row) => ({ value: row.locationId, label: row.name })),
              ]}
              onChange={(event) =>
                update({
                  location_id: event.target.value,
                  contract_type: null,
                  paginate_page: null,
                })
              }
            />
          )}
          <Field
            label="Start Date"
            name="start_date"
            type="date"
            required
            defaultValue={startDate}
          />
          <Field
            label="End Date"
            name="end_date"
            type="date"
            required
            defaultValue={endDate}
          />
          {!isSingleLocation && contractTypes.length > 0 && (
            <SelectField
              label="Contract Type"
              value={selectedContractType}
              options={[
                { value: "", label: "All Contract Types" },
                ...contractTypes.map((type) => ({ value: type, label: type })),
              ]}
              onChange={(event) =>
                update({ contract_type: event.target.value, paginate_page: null })
              }
            />
          )}
          <Button>Apply Filters</Button>
        </form>
      </Panel>

      {error ? (
        <Panel title="Financial report unavailable">
          <p role="alert" className="p-5 text-destructive">
            {error}
          </p>
        </Panel>
      ) : data ? (
        <>
          {!isSingleLocation && selectedContractType && (
            <p
              role="status"
              className="rounded-lg border bg-muted/40 px-4 py-3 text-sm text-muted-foreground"
            >
              Summary metrics include all contract types; the location table is
              filtered to {selectedContractType}.
            </p>
          )}
          {isSingleLocation && !selectedRow ? (
            <p
              role="status"
              className="rounded-lg border bg-muted/40 px-4 py-3 text-sm text-muted-foreground"
            >
              No financial records were found for this location and date range.
            </p>
          ) : (
            <>
              {isSingleLocation && selectedRow && (
                <div className="flex items-center justify-between gap-4">
                  <h2 className="font-semibold">Performance Summary</h2>
                  {canExport && <TableExport
                    title="Financial Report"
                    filename="financial-report"
                    records={singleLocationExportRecords}
                    pageIds={singleLocationExportRecords.map((row) => row.id)}
                    onExport={onExport}
                  />}
                </div>
              )}
              <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
                {isSingleLocation ? (
                  <Metric
                    label="Chargepoints"
                    value={formatNumber(selectedRow?.chargepointCount ?? null, 0)}
                  />
                ) : (
                  <>
                    <Metric
                      label="Locations"
                      value={formatNumber(displayedLocationCount, 0)}
                    />
                    <Metric
                      label="Locations with Contracts"
                      value={formatNumber(displayedContractLocationCount, 0)}
                    />
                  </>
                )}
                <Metric
                  label="Total kWh"
                  value={formatNumber(displayedMetrics?.total_kwh ?? null)}
                />
                <Metric
                  label="Total Time (Hours)"
                  value={formatNumber(displayedMetrics?.total_time_hours ?? null)}
                />
                <Metric
                  label="Total Gross Revenue"
                  value={formatCurrency(
                    displayedMetrics?.total_gross_revenue ?? null,
                    displayedCurrency,
                  )}
                />
                <Metric
                  label="Total Net Revenue"
                  value={formatCurrency(
                    displayedMetrics?.total_net_revenue ?? null,
                    displayedCurrency,
                  )}
                />
                <Metric
                  label="Total Deduction"
                  value={formatCurrency(
                    displayedMetrics?.total_deduction ?? null,
                    displayedCurrency,
                  )}
                />
                <Metric
                  label="Electrical Bill"
                  value={formatCurrency(
                    displayedMetrics?.total_electrical_bill ?? null,
                    displayedCurrency,
                  )}
                />
                <Metric
                  label="CPO Share"
                  value={formatCurrency(
                    displayedMetrics?.total_cpo_share ?? null,
                    displayedCurrency,
                  )}
                  note={displayedMetrics?.cpo_share_percentage ?? "—"}
                />
                <Metric
                  label="Building Management Share"
                  value={formatCurrency(
                    displayedMetrics?.total_bm_share ?? null,
                    displayedCurrency,
                  )}
                  note={displayedMetrics?.bm_share_percentage ?? "—"}
                />
                <Metric
                  label="Investor Share"
                  value={formatCurrency(
                    displayedMetrics?.total_investor_share ?? null,
                    displayedCurrency,
                  )}
                />
              </div>
              {!isSingleLocation && (
                <DataTable
                  title="Location Performance"
                  rows={rows}
                  columns={columns}
                  searchDebounceMs={300}
                  hideRefresh
                  exportName="financial-report"
                  emptyMessage="No financial records match this date range and filter."
                  onExport={onExport}
                  hideExport={!canExport}
                />
              )}
            </>
          )}
        </>
      ) : (
        <Panel title="Financial report unavailable">
          <p role="alert" className="p-5 text-destructive">
            The financial report could not be loaded. Please retry.
          </p>
        </Panel>
      )}
    </div>
  );
}
