"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { ChartNoAxesCombined, Plus } from "lucide-react";
import { SelectField } from "@/components/shared/field";
import { Metric, Panel } from "@/components/shared/page";
import { useQueryUpdate } from "@/components/shared/tabs";
import { Button } from "@/components/ui/button";
import type { FinancialOptions } from "./contract";
import { money } from "./display";
import { InvestmentForm, type InvestmentLocation } from "./investment-form";
import { RevenueChart } from "./revenue-chart";
import type { InvestmentPortfolioData } from "./server";

const percentNumber = new Intl.NumberFormat("en", { maximumFractionDigits: 2 });

export function RoiPortfolio({
  locations,
  locationError,
  locationId,
  portfolio,
  groups,
  canEdit,
}: {
  locations: InvestmentLocation[];
  locationError: string | null;
  locationId: string;
  portfolio: InvestmentPortfolioData;
  groups: FinancialOptions;
  canEdit: boolean;
}) {
  const router = useRouter();
  const updateQuery = useQueryUpdate();
  const [pending, startTransition] = useTransition();
  const [formOpen, setFormOpen] = useState(false);
  const [savedLocation, setSavedLocation] = useState("");
  const selected = locations.find((location) => location.value === locationId);
  const data = pending ? undefined : portfolio.data;
  const error = portfolio.error;
  const retry = () => startTransition(() => router.refresh());

  return (
    <div className="min-w-0 space-y-4" aria-busy={pending}>
      <div className="panel flex flex-wrap items-end justify-between gap-4 p-4 sm:p-5">
        <div className="w-full sm:w-80">
          <SelectField
            label="Location"
            name="location_id"
            value={locationId}
            disabled={pending || locations.length === 0}
            options={[{ value: "", label: "All locations" }, ...locations]}
            onChange={(event) => {
              const value = event.target.value;
              setSavedLocation("");
              startTransition(() => updateQuery({ location_id: value || null }));
            }}
          />
        </div>
        {canEdit && (
          <div className="flex flex-wrap items-center gap-3">
            {!selected && locations.length > 0 && (
              <p className="text-xs text-muted-foreground">Select a location to create an investment.</p>
            )}
            <Button onClick={() => setFormOpen(true)} disabled={pending || !selected}>
              <Plus aria-hidden="true" />
              Create investment
            </Button>
          </div>
        )}
      </div>
      {locationError && (
        <div className="panel flex flex-wrap items-center justify-between gap-3 p-4">
          <p role="alert" className="text-sm text-destructive">{locationError}</p>
          <Button variant="outline" onClick={retry} disabled={pending}>Retry locations</Button>
        </div>
      )}
      {savedLocation === locationId && savedLocation && (
        <p role="status" className="rounded-lg border border-success/30 bg-success/10 px-4 py-3 text-sm">
          Investment created for {selected?.label}.
        </p>
      )}
      <div className="grid min-w-0 gap-4 sm:grid-cols-3">
        <Metric label="Total investment" value={data ? money(data.total_investment, data.currency) : "—"} />
        <Metric label="Total revenue" value={data ? money(data.total_revenue, data.currency) : "—"} />
        <Metric label="Percentage revenue" value={data ? `${percentNumber.format(data.percentage_revenue)}%` : "—"} />
      </div>
      <Panel className="min-w-0">
        <div className="flex flex-wrap items-center justify-between gap-3 border-b p-4 sm:p-5">
          <div>
            <h2 className="font-semibold">Revenue shares</h2>
            <p className="mt-1 text-sm text-muted-foreground">
              Monthly revenue and energy costs{data ? ` · ${data.currency}` : ""}
            </p>
          </div>
          {data && data.monthly_revenue.length > 0 && (
            <div className="flex items-center gap-2 rounded-lg border px-3 py-2 text-xs sm:text-sm">
              <span aria-hidden="true" className="w-5 shrink-0 border-t-2 border-dashed border-foreground" />
              <span>Break-even point</span>
              <span className="font-semibold tabular-nums">{money(data.total_investment, data.currency)}</span>
            </div>
          )}
        </div>
        {pending ? (
          <p role="status" className="grid min-h-40 place-items-center p-5 text-sm text-muted-foreground">Loading investment portfolio…</p>
        ) : error ? (
          <div className="flex flex-wrap items-center justify-between gap-3 p-5">
            <p role="alert" className="text-sm text-destructive">{error}</p>
            <Button variant="outline" onClick={retry}>Retry</Button>
          </div>
        ) : data && data.monthly_revenue.length > 0 ? (
          <RevenueChart key={locationId} portfolio={data} />
        ) : (
          <div className="flex min-h-48 flex-col items-center justify-center gap-2 p-5 text-center">
            <ChartNoAxesCombined aria-hidden="true" className="size-6 text-muted-foreground" />
            <p className="text-sm font-medium">No monthly revenue yet</p>
            <p className="text-sm text-muted-foreground">
              Revenue will appear here when monthly figures are available.
            </p>
          </div>
        )}
      </Panel>
      {canEdit && formOpen && selected && (
        <InvestmentForm
          key={locationId}
          location={{ ...selected, currency: portfolio.data?.currency ?? selected.currency }}
          groups={groups}
          onClose={() => setFormOpen(false)}
          onSaved={() => {
            setFormOpen(false);
            setSavedLocation(locationId);
            retry();
          }}
        />
      )}
    </div>
  );
}
