"use client";

import Link from "next/link";
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { useAsyncEffect } from "@/hooks/use-async-effect";
import { toast } from "sonner";

import {
  getAdminDrawFinanceSummary,
  postAdminCancelDraw,
  postAdminManualCloseDraw,
  postAdminReopenDraw,
  postAdminRunDrawRng,
} from "@/api/admin-draws";
import { postAdminRunDrawSettlement } from "@/api/admin-settlement";
import { Button } from "@/components/ui/button";
import { AdminNoResourceState } from "@/components/admin/admin-no-resource-state";
import { AdminLoadingState } from "@/components/admin/admin-loading-state";
import { useAdminDateTimeFormatter } from "@/hooks/use-admin-datetime-formatter";
import { useConfirmAction } from "@/hooks/use-confirm-action";
import { LotteryApiBizError } from "@/types/api/errors";
import type { AdminDrawFinanceSummaryData } from "@/types/api/admin-draw-finance";
import { canManageDrawResults } from "@/lib/draw-access";
import { adminHasAnyPermission } from "@/lib/admin-permissions";
import { useAdminProfile } from "@/stores/admin-session";
import { signedMoneyClass } from "@/lib/admin-signed-money";
import { cn } from "@/lib/utils";
import { formatAdminMinorUnits } from "@/lib/money";
import { useDrawDetail } from "@/modules/draws/draw-detail-context";

import {
  PRD_DRAW_REOPEN_MANAGE,
  PRD_PAYOUT_MANAGE,
  PRD_PAYOUT_REVIEW,
} from "./draw-prd";

type ScheduleStep = {
  key: string;
  label: string;
  at: string | null | undefined;
};

function ScheduleTimeline({ steps }: { steps: ScheduleStep[] }) {
  const formatDt = useAdminDateTimeFormatter();

  return (
    <ol className="grid gap-2 sm:grid-cols-3">
      {steps.map((step) => (
        <li key={step.key} className="rounded-lg border border-border/60 bg-muted/20 px-3 py-2">
          <p className="text-xs text-muted-foreground">{step.label}</p>
          <p className="mt-0.5 font-mono text-sm tabular-nums">{formatDt(step.at)}</p>
        </li>
      ))}
    </ol>
  );
}

export function DrawDetailConsole({ drawId }: { drawId: string }): React.ReactElement {
  const { t } = useTranslation(["draws", "common"]);
  const { draw: data, loading, error, refresh, drawId: idNum } = useDrawDetail();
  const profile = useAdminProfile();
  const canManageDraw = canManageDrawResults(profile?.permissions);
  const canReopenDraw = adminHasAnyPermission(profile?.permissions, [PRD_DRAW_REOPEN_MANAGE]);
  const canRunSettlement = adminHasAnyPermission(profile?.permissions, [
    PRD_PAYOUT_MANAGE,
    PRD_PAYOUT_REVIEW,
  ]);
  const [acting, setActing] = useState<string | null>(null);
  const [financeSummary, setFinanceSummary] = useState<AdminDrawFinanceSummaryData | null>(null);
  const { request: requestConfirm, ConfirmDialog } = useConfirmAction();

  const loadFinance = useCallback(async () => {
    if (!Number.isFinite(idNum) || !data) {
      setFinanceSummary(null);
      return;
    }
    if (data.capabilities?.can_view_draw_finance === false) {
      setFinanceSummary(null);
      return;
    }
    try {
      setFinanceSummary(await getAdminDrawFinanceSummary(idNum));
    } catch {
      setFinanceSummary(null);
    }
  }, [data, idNum]);

  useAsyncEffect(() => {
    void loadFinance();
  }, [loadFinance]);

  async function runAction(name: string, action: () => Promise<unknown>): Promise<void> {
    if (!Number.isFinite(idNum)) return;
    setActing(name);
    try {
      await action();
      toast.success(t("actionSuccess", { name }));
      await refresh();
    } catch (e) {
      toast.error(e instanceof LotteryApiBizError ? e.message : t("actionFailed", { name }));
    } finally {
      setActing(null);
    }
  }

  const scheduleSteps = useMemo((): ScheduleStep[] => {
    if (!data) return [];
    const steps: ScheduleStep[] = [
      { key: "start", label: t("startTime"), at: data.start_time },
      { key: "close", label: t("closeTime"), at: data.close_time },
      { key: "draw", label: t("plannedDraw"), at: data.draw_time },
    ];
    if (data.cooling_end_time) {
      steps.push({
        key: "cooling",
        label: t("coolingEndTime"),
        at: data.cooling_end_time,
      });
    }
    return steps;
  }, [data, t]);

  const availableActions = useMemo(() => {
    if (!data) return [];

    type ActionDef = {
      key: string;
      label: string;
      variant: "outline" | "destructive";
      enabled: boolean;
      onConfirm: () => Promise<void>;
      confirmTitle: string;
      confirmDescription: string;
      confirmVariant?: "default" | "destructive";
    };

    const defs: ActionDef[] = [];

    if (canManageDraw) {
      defs.push(
        {
          key: "manualClose",
          label: t("manualClose"),
          variant: "outline",
          enabled: ["pending", "open"].includes(data.status),
          onConfirm: async () => { await postAdminManualCloseDraw(idNum); },
          confirmTitle: t("confirm.manualCloseTitle"),
          confirmDescription: t("confirm.manualCloseDescription"),
        },
        {
          key: "cancel",
          label: t("cancelBeforeDraw"),
          variant: "outline",
          enabled: ["pending", "open", "closing", "closed"].includes(data.status),
          onConfirm: async () => { await postAdminCancelDraw(idNum); },
          confirmTitle: t("confirm.cancelDrawTitle"),
          confirmDescription: t("confirm.cancelDrawDescription"),
        },
        {
          key: "rng",
          label: t("rngAutoGenerate"),
          variant: "outline",
          enabled: data.status === "closed",
          onConfirm: async () => { await postAdminRunDrawRng(idNum); },
          confirmTitle: t("confirm.rngDrawTitle"),
          confirmDescription: t("confirm.rngDrawDescription"),
        },
      );
    }

    if (canReopenDraw) {
      defs.push({
        key: "reopen",
        label: t("cooldownReopen"),
        variant: "destructive",
        enabled: data.status === "cooldown",
        onConfirm: async () => { await postAdminReopenDraw(idNum); },
        confirmTitle: t("confirm.reopenTitle"),
        confirmDescription: t("confirm.reopenDescription"),
        confirmVariant: "destructive",
      });
    }

    if (canRunSettlement) {
      defs.push({
        key: "settlement",
        label: t("runSettlement"),
        variant: "outline",
        enabled: data.status === "settling",
        onConfirm: async () => { await postAdminRunDrawSettlement(idNum); },
        confirmTitle: t("confirm.runSettlementTitle"),
        confirmDescription: t("confirm.runSettlementDescription"),
      });
    }

    return defs.filter((d) => d.enabled);
  }, [canManageDraw, canReopenDraw, canRunSettlement, data, idNum, t]);

  if (loading && !data) {
    return <AdminLoadingState minHeight="6rem" className="py-6" />;
  }

  if (error) {
    return <p className="text-sm text-destructive">{error}</p>;
  }
  if (!data) {
    return <AdminNoResourceState />;
  }

  const batch = data.result_batch_counts;
  const pendingReview = batch.pending_review ?? 0;
  const totalBatches = batch.total ?? batch.published;
  const financeCurrency = financeSummary?.currency_code ?? "NPR";
  const hasResultActivity = totalBatches > 0 || pendingReview > 0 || batch.published > 0;

  return (
    <div className="space-y-4">
      <div className="grid gap-3 sm:grid-cols-3">
        <div className="rounded-lg border border-border/60 px-3 py-2.5">
          <p className="text-xs text-muted-foreground">{t("overviewBetTotal")}</p>
          <p className="mt-1 font-mono text-sm tabular-nums">
            {formatAdminMinorUnits(
              financeSummary?.total_bet_minor ?? data.total_bet_minor ?? 0,
              financeCurrency,
            )}
          </p>
        </div>
        <div className="rounded-lg border border-border/60 px-3 py-2.5">
          <p className="text-xs text-muted-foreground">{t("overviewPayoutTotal")}</p>
          <p className="mt-1 font-mono text-sm tabular-nums">
            {formatAdminMinorUnits(
              financeSummary?.total_payout_minor ?? data.total_payout_minor ?? 0,
              financeCurrency,
            )}
          </p>
        </div>
        <div className="rounded-lg border border-border/60 px-3 py-2.5">
          <p className="text-xs text-muted-foreground">{t("overviewProfitLoss")}</p>
          <p
            className={cn(
              "mt-1 font-mono text-sm tabular-nums",
              signedMoneyClass(
                financeSummary?.approx_house_gross_minor ?? data.profit_loss_minor ?? 0,
                true,
              ),
            )}
          >
            {formatAdminMinorUnits(
              financeSummary?.approx_house_gross_minor ?? data.profit_loss_minor ?? 0,
              financeCurrency,
            )}
          </p>
        </div>
      </div>

      <ScheduleTimeline steps={scheduleSteps} />

      {hasResultActivity ? (
        <div className="flex flex-wrap items-center gap-2 text-sm">
          {canManageDraw && totalBatches > 0 ? (
            <span className="rounded-md bg-muted px-2 py-1 tabular-nums">
              {t("batchSummaryTotal", { count: totalBatches })}
            </span>
          ) : null}
          {canManageDraw && pendingReview > 0 ? (
            <Link
              href={`/admin/draws/${drawId}/review`}
              className="rounded-md bg-amber-500/15 px-2 py-1 font-medium text-amber-800 dark:text-amber-200"
            >
              {t("batchSummaryPending", { count: pendingReview })}
            </Link>
          ) : null}
          {batch.published > 0 ? (
            <Link
              href={`/admin/draws/${drawId}/results`}
              className="rounded-md bg-emerald-500/15 px-2 py-1 font-medium text-emerald-800 dark:text-emerald-200"
            >
              {t("batchSummaryPublished", { count: batch.published })}
            </Link>
          ) : null}
          {data.capabilities?.can_view_draw_finance !== false ? (
            <Link
              href={`/admin/draws/${drawId}/finance`}
              className="text-sm font-medium text-primary hover:underline"
            >
              {t("viewFinance")}
            </Link>
          ) : null}
        </div>
      ) : canManageDraw ? (
        <Link
          href={`/admin/draws/${drawId}/review`}
          className="text-sm font-medium text-primary hover:underline"
        >
          {t("goToReviewTab")}
        </Link>
      ) : null}

      {availableActions.length > 0 ? (
        <div className="flex flex-wrap gap-2 border-t border-border/60 pt-4">
          {availableActions.map((action) => (
            <Button
              key={action.key}
              type="button"
              size="sm"
              variant={action.variant}
              disabled={acting !== null}
              onClick={() =>
                requestConfirm({
                  title: action.confirmTitle,
                  description: action.confirmDescription,
                  confirmVariant: action.confirmVariant,
                  onConfirm: () => runAction(action.label, action.onConfirm),
                })
              }
            >
              {acting === action.label ? t("processing") : action.label}
            </Button>
          ))}
        </div>
      ) : null}

      <ConfirmDialog />
    </div>
  );
}