"use client";
import { useState } from "react";
import { useSearchParams } from "next/navigation";
import {
  usePreviewRole,
  PreviewLink,
} from "@/components/layout/preview-context";
import {
  PageHeader,
  Metric,
  Panel,
  PreviewNotice,
} from "@/components/shared/page";
import { DataTable, type Column } from "@/components/shared/data-table";
import { Field, SelectField } from "@/components/shared/field";
import { Tabs, useQueryUpdate } from "@/components/shared/tabs";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { currency } from "@/lib/format";
import { isManager } from "@/lib/preview";
import { financials, locations } from "./fixtures";
import {
  financialScope,
  financialTotals,
  scopedLocations,
  type LocationFinancial,
} from "./model";
const moneyColumn = (
  key: "gross" | "deduction" | "electrical" | "investorShare" | "bmShare",
  label: string,
): Column<LocationFinancial> => ({
  key,
  label,
  render: (row) => currency(row[key]),
});
export function FinancialReport({
  locationId,
  embedded = false,
}: {
  locationId?: string;
  embedded?: boolean;
}) {
  const role = usePreviewRole(),
    params = useSearchParams(),
    update = useQueryUpdate();
  const [agreement, setAgreement] = useState<LocationFinancial | null>(null);
  const allowed = scopedLocations(locations, role),
    requested = locationId ?? params.get("location_id") ?? "";
  const restricted = role === "investor" || isManager(role);
  const selected = restricted
    ? allowed.some((row) => row.id === requested)
      ? requested
      : (allowed[0]?.id ?? "")
    : requested;
  const start = params.get("start_date") ?? "2026-10-01",
    end = params.get("end_date") ?? "2026-10-15";
  const rows = financialScope(
    financials,
    locations,
    role,
    selected,
    params.get("chargepoint") ?? "",
    start,
    end,
  ).filter(
    (row) =>
      !params.get("contract_type") ||
      row.contractType === params.get("contract_type"),
  );
  const total = financialTotals(rows),
    isInvestor = role === "investor",
    manager = isManager(role);
  const columns: Column<LocationFinancial>[] = [
    {
      key: "name",
      label: "Location",
      render: (row) => (
        <PreviewLink
          className="text-primary hover:underline"
          href={`/locations/${row.locationId}`}
        >
          {row.name}
        </PreviewLink>
      ),
    },
    { key: "chargepoint", label: "Chargepoint" },
    { key: "kwh", label: "kWh", render: (row) => row.kwh.toLocaleString() },
    { key: "hours", label: "Time (Hours)" },
    moneyColumn("gross", "Gross Revenue"),
    moneyColumn("deduction", "Deduction"),
    moneyColumn("electrical", "Electrical Bill"),
    { key: "net", label: "Net Revenue", render: (row) => currency(row.net) },
    ...(!manager ? [moneyColumn("investorShare", "Investor Share")] : []),
    ...(!isInvestor
      ? [moneyColumn("bmShare", "Building Management Share")]
      : []),
  ];
  return (
    <div className="space-y-5">
      {!embedded && (
        <PageHeader
          title={
            isInvestor
              ? "Financial Report"
              : "Financial Report for CPO & Partner"
          }
        />
      )}
      <Panel
        title={
          embedded ? "Financial Report" : "Locations Financial (List Style)"
        }
        description={
          restricted
            ? "Showing financial records for your assigned or contracted location."
            : "Location and chargepoint performance with contract allocations."
        }
      >
        <form
          className="grid items-end gap-4 p-5 md:grid-cols-3 xl:grid-cols-6"
          onSubmit={(event) => {
            event.preventDefault();
            const data = new FormData(event.currentTarget);
            update({
              start_date: String(data.get("start_date")),
              end_date: String(data.get("end_date")),
              paginate_page: null,
            });
          }}
        >
          <SelectField
            label="Location"
            value={selected}
            disabled={!!locationId || manager}
            options={[
              ...(!restricted ? [{ value: "", label: "All Locations" }] : []),
              ...allowed.map((row) => ({ value: row.id, label: row.name })),
            ]}
            onChange={(event) =>
              update({ location_id: event.target.value, chargepoint: null })
            }
          />
          <Field
            label="Start Date"
            name="start_date"
            type="date"
            required
            defaultValue={start}
            max={end}
          />
          <Field
            label="End Date"
            name="end_date"
            type="date"
            required
            defaultValue={end}
            min={start}
          />
          <SelectField
            label="Chargepoint"
            value={params.get("chargepoint") ?? ""}
            options={[
              { value: "", label: "All Chargepoints" },
              ...financials
                .filter(
                  (row) =>
                    (!selected || row.locationId === selected) &&
                    allowed.some((location) => location.id === row.locationId),
                )
                .map((row) => row.chargepoint),
            ]}
            onChange={(event) => update({ chargepoint: event.target.value })}
          />
          <SelectField
            label="Contract Type"
            value={params.get("contract_type") ?? ""}
            options={[
              "",
              "NET_REV_SHARES",
              "GROSS_REV_SHARES",
              "FIXED_COST",
            ].map((value) => ({ value, label: value || "All Contract Types" }))}
            onChange={(event) => update({ contract_type: event.target.value })}
          />
          <Button>Apply Filters</Button>
        </form>
      </Panel>
      {start > end ? (
        <PreviewNotice>Start date must be before the end date.</PreviewNotice>
      ) : (
        <>
          <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
            <Metric label="Total kWh" value={total.kwh.toLocaleString()} />
            <Metric
              label="Total Time (Hours)"
              value={total.hours.toLocaleString()}
            />
            <Metric label="Total Gross Revenue" value={currency(total.gross)} />
            <Metric label="Total Net Revenue" value={currency(total.net)} />
            <Metric label="Total Deduction" value={currency(total.deduction)} />
            <Metric
              label="Electrical Bill"
              value={currency(total.electrical)}
            />
            {!manager && (
              <Metric
                label="Investor Share"
                value={currency(total.investorShare)}
                note="50% of net revenue for net share contracts"
              />
            )}
            {!isInvestor && (
              <Metric
                label="Building Management Share"
                value={currency(total.bmShare)}
                note="Contract share before VAT"
              />
            )}
          </div>
          <DataTable
            title="Location Performance"
            rows={rows}
            columns={columns}
            emptyMessage="No financial records match this scope and date range."
            actions={(row) => (
              <Button
                variant="outline"
                size="sm"
                onClick={() => setAgreement(row)}
              >
                Business Agreement
              </Button>
            )}
          />
        </>
      )}
      <Dialog
        open={!!agreement}
        onOpenChange={(open) => {
          if (!open) setAgreement(null);
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Business Agreement</DialogTitle>
            <DialogDescription>
              {agreement?.name} · {agreement?.contractType.replaceAll("_", " ")}
            </DialogDescription>
          </DialogHeader>
          <dl className="grid grid-cols-2 gap-4 text-sm">
            <div>
              <dt className="text-muted-foreground">Investor Share</dt>
              <dd>50% of net revenue</dd>
            </div>
            <div>
              <dt className="text-muted-foreground">Building Management</dt>
              <dd>20% of net revenue</dd>
            </div>
            <div>
              <dt className="text-muted-foreground">Settlement</dt>
              <dd>Monthly + 7 days</dd>
            </div>
            <div>
              <dt className="text-muted-foreground">Deductions</dt>
              <dd>Service fee, electrical bill</dd>
            </div>
          </dl>
          <PreviewNotice>Agreement values are fixture previews.</PreviewNotice>
        </DialogContent>
      </Dialog>
    </div>
  );
}
export function InvestorLocationReport() {
  const params = useSearchParams();
  return (
    <>
      <Tabs
        queryKey="view"
        items={[
          { value: "financial", label: "Financial Report" },
          { value: "locations", label: "Contracted Locations" },
        ]}
      />
      {params.get("view") === "locations" ? (
        <DataTable
          title="Contracted Locations"
          rows={scopedLocations(locations, "investor")}
          columns={[
            {
              key: "name",
              label: "Location",
              render: (row) => (
                <PreviewLink
                  className="text-primary"
                  href={`/locations/${row.id}`}
                >
                  {row.name}
                </PreviewLink>
              ),
            },
            { key: "city", label: "City" },
            { key: "chargepoints", label: "Chargepoints" },
            { key: "status", label: "Status" },
          ]}
        />
      ) : (
        <FinancialReport embedded />
      )}
    </>
  );
}
