"use client";

import * as React from "react";
import { useParams } from "next/navigation";
import { RefreshCw } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";

import { fetchDashboardStatisticsClient } from "@/app/customer/[tenant]/dashboard/_lib/dashboard-api";
import type { DashboardStatisticsData } from "@/app/customer/[tenant]/dashboard/_lib/dashboard-server-api";
import { IndividualDashboardOverview } from "@/app/customer/_components/individual-dashboard-overview";
import { useImpersonationScopeRefresh } from "@/app/customer/_lib/admin/use-impersonation-scope-refresh";
import { AUM_MODE_CHANGED_EVENT } from "@/app/customer/_lib/aum-mode-events";
import { resolveClientCustomerTenant } from "@/lib/tenant/client-tenant";
import { CorporateDashboardCards } from "./dashboard-widget-host";
import { DashboardPageHeader, DashboardSkeleton } from "./dashboard-overview-layout";

export function DashboardOverview({ formattedDate }: { formattedDate: string }) {
  const params = useParams<{ tenant: string }>();
  const tenant = params?.tenant?.trim() || resolveClientCustomerTenant();

  const [data, setData] = React.useState<DashboardStatisticsData | null>(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);

  const load = React.useCallback(async () => {
    setLoading(true);
    setError(null);
    const result = await fetchDashboardStatisticsClient(tenant);
    if (result.errorMessage) {
      setError(result.errorMessage);
      setData(null);
    } else {
      setData(result.data);
    }
    setLoading(false);
  }, [tenant]);

  useImpersonationScopeRefresh(() => {
    void load();
  });

  React.useEffect(() => {
    void load();
  }, [load]);

  React.useEffect(() => {
    const onAumModeChanged = () => {
      void (async () => {
        const result = await fetchDashboardStatisticsClient(tenant);
        if (!result.errorMessage && result.data) {
          setData(result.data);
        }
      })();
    };

    window.addEventListener(AUM_MODE_CHANGED_EVENT, onAumModeChanged);
    return () => window.removeEventListener(AUM_MODE_CHANGED_EVENT, onAumModeChanged);
  }, [tenant]);

  if (loading && !data) {
    return (
      <div className="flex flex-col gap-2">
        <DashboardPageHeader formattedDate={formattedDate} />
        <DashboardSkeleton />
      </div>
    );
  }

  if (error && !data) {
    return (
      <div className="flex flex-col gap-2">
        <DashboardPageHeader
          formattedDate={formattedDate}
          actions={
            <Button size="sm" variant="outline" onClick={() => void load()}>
              <RefreshCw className="size-3.5" />
              Retry
            </Button>
          }
        />
        <Card className="border-destructive/30">
          <CardContent className="flex flex-col items-start gap-3 p-6">
            <p className="text-sm text-destructive">{error}</p>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (!data) {
    return null;
  }

  if (data.portal === "individual") {
    return (
      <IndividualDashboardOverview
        cards={data.macroCards ?? []}
        cardPrefs={data.cardPrefs ?? null}
        cardCatalog={data.cardCatalog}
        tenant={tenant}
        loading={loading}
        onRefresh={() => void load()}
        formattedDate={formattedDate}
      />
    );
  }

  return (
    <CorporateDashboardCards
      data={data}
      tenant={tenant}
      loading={loading}
      onRefresh={() => void load()}
      formattedDate={formattedDate}
    />
  );
}
