"use client";

import * as React from "react";
import { resolveCustomerTenant } from "@/app/customer/_lib/resolve-customer-tenant";
import Link from "next/link";
import { useParams } from "next/navigation";
import { RefreshCw, X } from "lucide-react";

import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

import { PORTFOLIO_ANALYTICS_PRESETS } from "../../_lib/portfolio-analytics-query";
import { PortfolioAnalyticsFiltersDialog } from "./portfolio-analytics-filters-dialog";
import { PortfolioAnalyticsChartPanel } from "./portfolio-analytics-charts";
import { PortfolioAnalyticsDayChangesSheet } from "./portfolio-analytics-day-changes-sheet";
import { usePortfolioAnalyticsViewState } from "./use-portfolio-analytics-view-state";

export function PortfolioAnalyticsView() {
  const params = useParams<{ tenant?: string }>();
  const tenant =
    typeof params?.tenant === "string" && params.tenant.trim() ? params.tenant.trim() : resolveCustomerTenant();
  const s = usePortfolioAnalyticsViewState(tenant);
  const [dayOpen, setDayOpen] = React.useState(false);
  const [dayDate, setDayDate] = React.useState<string | null>(null);
  const [dayPrev, setDayPrev] = React.useState<string | null>(null);
  const [changesMode, setChangesMode] = React.useState<"day" | "period">("day");

  // Bank ids already on the chart query (ids=…) — reuse for day-changes.
  const bankQuery = React.useMemo(() => {
    const ids = new URLSearchParams(s.queryString).get("ids");
    return ids ? new URLSearchParams({ ids }).toString() : "";
  }, [s.queryString]);

  return (
    <div className="flex min-w-0 flex-col gap-3">
      <div className="flex w-full min-w-0 flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div className="min-w-0">
          <h1 className="font-semibold text-xl tracking-tight sm:text-2xl">Portfolio Analytics</h1>
          <p className="text-muted-foreground text-sm">
            {s.rangeLabel}
            {s.isLoading ? " · Loading…" : ""}
          </p>
          {s.loadErrorMessage ? <p className="text-destructive text-sm">{s.loadErrorMessage}</p> : null}
        </div>

        <div className="flex flex-wrap items-center gap-2">
          <div className="inline-flex items-center rounded-lg border border-border/60 bg-muted/25 p-0.5">
            {PORTFOLIO_ANALYTICS_PRESETS.map((item) => (
              <Button
                key={item.id}
                variant="ghost"
                size="sm"
                className={cn(
                  "h-7 rounded-md px-2.5 text-xs shadow-none",
                  s.preset === item.id
                    ? "bg-background text-foreground shadow-sm"
                    : "text-muted-foreground hover:bg-transparent hover:text-foreground",
                )}
                onClick={() => s.handlePresetChange(item.id)}
              >
                {item.label}
              </Button>
            ))}
          </div>
          <PortfolioAnalyticsFiltersDialog
            filters={s.filters}
            defaultFilters={s.defaultFilters}
            options={s.filterOptionLists}
            onApply={s.applyFilters}
          />
          <Button
            variant="outline"
            size="icon"
            className="h-8 w-8 shrink-0"
            aria-label="Refresh"
            onClick={s.handleRefresh}
          >
            <RefreshCw className={cn("size-3.5", s.isLoading && "animate-spin")} />
          </Button>
          <Button variant="outline" size="icon" className="h-8 w-8 shrink-0" asChild>
            <Link href={`/customer/${tenant}/dashboard`} aria-label="Close">
              <X className="size-3.5" />
            </Link>
          </Button>
        </div>
      </div>

      <PortfolioAnalyticsChartPanel
        isLoading={s.isLoading}
        chartData={s.chartData}
        chartSeriesConfig={s.chartSeriesConfig}
        visibleChartSeries={s.visibleChartSeries}
        legendSeries={s.legendSeries}
        focusedSeries={s.focusedSeries}
        onLegendClick={s.handleLegendClick}
        onClearFocus={() => s.setFocusedSeries("ALL")}
        onDayClick={(date, previousDate) => {
          setChangesMode("day");
          setDayDate(date);
          setDayPrev(previousDate);
          setDayOpen(true);
        }}
        onPeriodChangesClick={(endDate, startDate) => {
          setChangesMode("period");
          setDayDate(endDate);
          setDayPrev(startDate);
          setDayOpen(true);
        }}
        emptyLabel="No OS as-of snapshots in this range"
      />

      <PortfolioAnalyticsDayChangesSheet
        tenant={tenant}
        date={dayDate}
        previousDate={dayPrev}
        bankQuery={bankQuery}
        mode={changesMode}
        open={dayOpen}
        onOpenChange={setDayOpen}
      />
    </div>
  );
}
