"use client";

import * as React from "react";

import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";
import { customerUrl } from "@/lib/tenant";

import { DashboardWidgetBody } from "@/app/customer/_components/dashboard-charts/dashboard-widget-body";
import { ResponsiveDonutChart } from "@/app/customer/_components/dashboard-charts/responsive-donut-chart";
import { WidgetChartLegend } from "@/app/customer/_components/dashboard-charts/widget-chart-legend";
import { DashboardWidgetShell } from "@/app/customer/_components/dashboard-widget-shell";
import { useWidgetSettingsAction } from "@/app/customer/_components/dashboard-widget-configure-provider";
import { LAYOUT_IDS } from "@/app/customer/_lib/dashboard-layout";
import { useDashboardWidgetData } from "@/app/customer/_lib/use-dashboard-widget-data";
import { getStaticWidgetDefinition } from "@/app/customer/_lib/dashboard-widget-registry-definitions";
import { configureParamForWidget } from "@/app/customer/[tenant]/settings/_components/widget-config";
import { buildDepositCurrencySlices } from "@/app/customer/[tenant]/reports/deposit-report/_lib/deposit-chart-data";
import { fetchDepositWidgetClient } from "@/app/customer/[tenant]/reports/deposit-report/_lib/deposit-widget-api";
import type { DepositWidgetData } from "@/app/customer/[tenant]/reports/deposit-report/_lib/deposit-widget-server-api";

const widgetMeta = getStaticWidgetDefinition("deposit");

function amountClass(raw: number) {
  if (!Number.isFinite(raw) || Math.abs(raw) < 1e-9) return "text-foreground";
  return raw < 0 ? "text-red-600 dark:text-red-400" : "text-emerald-700 dark:text-emerald-400";
}

function CompactDepositList({ data }: { data: DepositWidgetData }) {
  return (
    <div className="divide-y rounded-md border">
      {data.rows.slice(0, 5).map((row, index) => (
        <div
          key={`${row.bank_id}-${row.currency}-${row.maturity_date}-${index}`}
          className="flex items-center justify-between gap-2 px-3 py-2.5"
        >
          <div className="min-w-0">
            <p className="truncate font-medium">{row.bank_name || "—"}</p>
            <p className="text-[10px] text-muted-foreground tabular-nums">{row.maturity_date_fmt || "—"}</p>
          </div>
          <span className={cn("shrink-0 text-sm font-semibold tabular-nums", amountClass(row.amount))}>
            {row.currency} {row.amount_fmt}
          </span>
        </div>
      ))}
    </div>
  );
}

function DepositMaturityTable({ data }: { data: DepositWidgetData }) {
  return (
    <div className="min-h-0 flex-1 overflow-y-auto text-xs">
      <div className="overflow-hidden rounded-md border">
        <table className="w-full text-left">
          <thead className="bg-muted/50 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
            <tr>
              <th className="px-3 py-2">Bank</th>
              <th className="px-3 py-2 text-right">FD Amount</th>
              <th className="px-3 py-2 text-center">Maturity Date</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {data.rows.map((row, index) => (
              <tr key={`${row.bank_id}-${row.currency}-${row.maturity_date}-${index}`}>
                <td className="px-3 py-2">{row.bank_name || "—"}</td>
                <td className={cn("px-3 py-2 text-right tabular-nums", amountClass(row.amount))}>
                  {row.currency} {row.amount_fmt}
                </td>
                <td className="px-3 py-2 text-center tabular-nums text-muted-foreground">
                  {row.maturity_date_fmt || "—"}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function DepositWidgetBody({ data }: { data: DepositWidgetData }) {
  const slices = React.useMemo(
    () => buildDepositCurrencySlices(data.currency_totals),
    [data.currency_totals],
  );

  return (
    <DashboardWidgetBody>
      {({ tier }) => {
        if (tier === "compact") {
          return (
            <div className="overflow-y-auto p-4 text-xs">
              <CompactDepositList data={data} />
            </div>
          );
        }

        if (tier === "balanced") {
          return (
            <div className="flex min-h-0 flex-1 flex-col gap-3 overflow-hidden p-4">
              {slices.length > 0 ? (
                <div className="grid shrink-0 grid-cols-[minmax(120px,0.8fr)_minmax(0,1.2fr)] items-center gap-3">
                  <ResponsiveDonutChart slices={slices} minSize={110} maxSize={160} />
                  <WidgetChartLegend items={slices} />
                </div>
              ) : null}
              <DepositMaturityTable data={data} />
            </div>
          );
        }

        return (
          <div className="grid min-h-0 flex-1 grid-cols-[minmax(180px,0.85fr)_minmax(0,1.15fr)] gap-3 overflow-hidden p-4">
            <div className="flex min-h-0 flex-col items-center justify-center gap-3">
              <ResponsiveDonutChart slices={slices} minSize={140} maxSize={200} />
              <WidgetChartLegend items={slices} className="w-full" />
            </div>
            <DepositMaturityTable data={data} />
          </div>
        );
      }}
    </DashboardWidgetBody>
  );
}

export function DepositWidget({
  widgetId,
  title,
  layoutId,
}: {
  widgetId?: number;
  title?: string;
  layoutId?: string;
} = {}) {
  const resolvedLayoutId =
    layoutId ?? (widgetId && widgetId > 0 ? `depw-${widgetId}` : LAYOUT_IDS.deposit);

  const fetchIndividual = React.useCallback(
    async (resolvedTenant: string) => {
      const result = await fetchDepositWidgetClient(resolvedTenant, {
        widgetId: widgetId && widgetId > 0 ? widgetId : null,
      });
      return { data: result.data, errorMessage: result.errorMessage };
    },
    [widgetId],
  );

  const { tenant, data, loading, refreshing, error, refresh } = useDashboardWidgetData<DepositWidgetData>({
    layoutId: resolvedLayoutId,
    fetchIndividual,
    refreshOnScopeChange: false,
    skipBatch: Boolean(widgetId && widgetId > 0),
    widgetId: widgetId && widgetId > 0 ? widgetId : undefined,
  });

  const reportHref = customerUrl(tenant, widgetMeta.reportPath ?? "/reports/deposit-report");
  const settingsHrefFallback =
    widgetId && widgetId > 0
      ? customerUrl(tenant, `/settings?section=dashboard&configure=${configureParamForWidget("dep", widgetId)}`)
      : customerUrl(tenant, "/settings?section=dashboard");
  const { settingsHref, onSettingsClick } = useWidgetSettingsAction(widgetId ?? 0, settingsHrefFallback);
  const displayTitle = title?.trim() || widgetMeta.label;
  const hasRows = (data?.rows.length ?? 0) > 0;

  return (
    <DashboardWidgetShell
      title={displayTitle}
      subtitle={data ? `Next ${data.days} days` : undefined}
      reportHref={reportHref}
      settingsHref={settingsHref}
      onSettingsClick={onSettingsClick}
      loading={loading && !data}
      refreshing={refreshing}
      error={error}
      onRefresh={refresh}
      loadingContent={
        <div className="flex flex-1 flex-col gap-3 p-4">
          <Skeleton className="h-16 w-full" />
          <div className="space-y-2">
            {Array.from({ length: 4 }).map((_, i) => (
              <Skeleton key={i} className="h-8 w-full" />
            ))}
          </div>
        </div>
      }
      emptyContent={
        <div className="flex flex-1 items-center justify-center p-6 text-center text-muted-foreground text-sm">
          {data?.empty_message ?? "No Deposit Next 30 days maturity date"}
        </div>
      }
    >
      {data && hasRows ? <DepositWidgetBody data={data} /> : null}
    </DashboardWidgetShell>
  );
}
