"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 { useImpersonationScopeRefresh } from "@/app/customer/_lib/admin/use-impersonation-scope-refresh";
import { AUM_MODE_CHANGED_EVENT } from "@/app/customer/_lib/aum-mode-events";
import { DEFAULT_LAYOUT_CHANGED_EVENT } from "@/app/customer/_lib/default-layout";
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);

  // A different tenant starts from the skeleton again (adjusted during render, not in an effect).
  const [loadedTenant, setLoadedTenant] = React.useState(tenant);
  if (loadedTenant !== tenant) {
    setLoadedTenant(tenant);
    setData(null);
    setError(null);
    setLoading(true);
  }

  const applyResult = React.useCallback(
    (result: Awaited<ReturnType<typeof fetchDashboardStatisticsClient>>) => {
      if (result.errorMessage) {
        setError(result.errorMessage);
        setData(null);
      } else {
        setData(result.data);
      }
      setLoading(false);
    },
    [],
  );

  const load = React.useCallback(async () => {
    setLoading(true);
    setError(null);
    applyResult(await fetchDashboardStatisticsClient(tenant));
  }, [tenant, applyResult]);

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

  React.useEffect(() => {
    let cancelled = false;
    void fetchDashboardStatisticsClient(tenant).then((result) => {
      if (!cancelled) applyResult(result);
    });
    return () => {
      cancelled = true;
    };
  }, [tenant, applyResult]);

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

    window.addEventListener(AUM_MODE_CHANGED_EVENT, refresh);
    window.addEventListener(DEFAULT_LAYOUT_CHANGED_EVENT, refresh);
    return () => {
      window.removeEventListener(AUM_MODE_CHANGED_EVENT, refresh);
      window.removeEventListener(DEFAULT_LAYOUT_CHANGED_EVENT, refresh);
    };
  }, [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;
  }

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