"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

import {
  deleteOddsVersion,
  getAdminPlayTypes,
  getAllConfigVersions,
  getOddsVersion,
  getOddsVersions,
  postOddsVersion,
  publishOddsVersion,
  putOddsItems,
} from "@/api/admin-config";
import { ConfigContextBanner, ConfigContextEmphasis } from "@/modules/config/config-context-banner";
import { ConfigDocPage, ConfigDocToolbar } from "@/modules/config/config-doc-page";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { ConfigReadonlyValue } from "@/modules/config/config-readonly-value";
import { ConfigVersionActions } from "@/modules/config/config-version-actions";
import { ConfigVersionSwitcher } from "@/modules/config/config-version-switcher";
import { useAdminDateTimeFormatter } from "@/hooks/use-admin-datetime-formatter";
import { useConfirmAction } from "@/hooks/use-confirm-action";
import { adminHasAnyPermission } from "@/lib/admin-permissions";
import { PRD_REBATE_MANAGE } from "@/lib/admin-prd";
import { useAdminProfile } from "@/stores/admin-session";
import { LotteryApiBizError } from "@/types/api/errors";
import type {
  AdminPlayTypeRow,
  ConfigVersionSummary,
  OddsItemRow,
  OddsVersionDetail,
} from "@/types/api/admin-config";

import { PRIZE_SCOPE_ORDER } from "@/modules/config/doc/prize-scopes";

function rateToPercentUi(rateStr: string): string {
  const n = Number.parseFloat(rateStr);
  if (!Number.isFinite(n)) {
    return "0";
  }
  return String(Math.round(n * 10000) / 100);
}

function inferPercentFrom(dim: 2 | 3 | 4, rows: OddsItemRow[], typeList: AdminPlayTypeRow[]): string {
  const codes = typeList.filter((t) => (t.dimension ?? 2) === dim).map((t) => t.play_code);
  const scope = PRIZE_SCOPE_ORDER[0];
  const hit = rows.find((r) => codes.includes(r.play_code) && r.prize_scope === scope);
  return hit ? rateToPercentUi(String(hit.rebate_rate)) : "0";
}

type RebateConfigDocScreenProps = {
  embedded?: boolean;
};

export function RebateConfigDocScreen({ embedded = false }: RebateConfigDocScreenProps) {
  const { t } = useTranslation(["config", "common"]);
  const { request: requestConfirm, ConfirmDialog } = useConfirmAction();
  const profile = useAdminProfile();
  const canManage = adminHasAnyPermission(profile?.permissions, [PRD_REBATE_MANAGE]);
  const formatDt = useAdminDateTimeFormatter();
  const [types, setTypes] = useState<AdminPlayTypeRow[]>([]);
  const [listRows, setListRows] = useState<ConfigVersionSummary[]>([]);

  const [selectedId, setSelectedId] = useState("");
  const [detail, setDetail] = useState<OddsVersionDetail | null>(null);
  const [draftRows, setDraftRows] = useState<OddsItemRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadingDetail, setLoadingDetail] = useState(false);
  const [saving, setSaving] = useState(false);

  const [p2, setP2] = useState("0");
  const [p3, setP3] = useState("0");
  const [p4, setP4] = useState("0");

  const refreshTypes = useCallback(async () => {
    try {
      const d = await getAdminPlayTypes();
      setTypes(d.items);
    } catch (e) {
      toast.error(e instanceof LotteryApiBizError ? e.message : t("errors.loadFailed", { ns: "common" }));
      setTypes([]);
    }
  }, [t]);

  const refreshList = useCallback(async () => {
    try {
      const d = await getAllConfigVersions(getOddsVersions);
      setListRows(d.items);
    } catch (e) {
      toast.error(e instanceof LotteryApiBizError ? e.message : t("errors.loadFailed", { ns: "common" }));
      setListRows([]);
    }
  }, [t]);

  useEffect(() => {
    queueMicrotask(async () => {
      setLoading(true);
      await refreshTypes();
      await refreshList();
      setLoading(false);
    });
  }, [refreshTypes, refreshList]);

  const loadDetail = useCallback(async (id: number) => {
    setLoadingDetail(true);
    try {
      const pt = await getAdminPlayTypes();
      const typeList = pt.items;
      setTypes(typeList);
      const d = await getOddsVersion(id);
      const rows = d.items.map((it) => ({ ...it }));
      setDetail(d);
      setDraftRows(rows);
      setP2(inferPercentFrom(2, rows, typeList));
      setP3(inferPercentFrom(3, rows, typeList));
      setP4(inferPercentFrom(4, rows, typeList));
    } catch (e) {
      toast.error(e instanceof LotteryApiBizError ? e.message : t("errors.loadFailed", { ns: "common" }));
      setDetail(null);
      setDraftRows([]);
    } finally {
      setLoadingDetail(false);
    }
  }, [t]);

  useEffect(() => {
    if (listRows.length === 0 || selectedId !== "") {
      return;
    }
    queueMicrotask(() => {
      const drafts = listRows.filter((x) => x.status === "draft").sort((a, b) => b.id - a.id);
      const active = listRows.find((x) => x.status === "active");
      const pick = drafts[0] ?? active ?? [...listRows].sort((a, b) => b.id - a.id)[0];
      if (pick) {
        setSelectedId(String(pick.id));
      }
    });
  }, [listRows, selectedId]);

  useEffect(() => {
    if (selectedId === "") {
      return;
    }
    const id = Number(selectedId);
    if (!Number.isFinite(id)) {
      return;
    }
    queueMicrotask(() => {
      void loadDetail(id);
    });
  }, [selectedId, loadDetail]);

  const typesByCode = useMemo(() => {
    const m = new Map<string, AdminPlayTypeRow>();
    for (const t of types) {
      m.set(t.play_code, t);
    }
    return m;
  }, [types]);

  const selectedVersionSummary = useMemo(
    () => listRows.find((x) => String(x.id) === selectedId) ?? null,
    [listRows, selectedId],
  );
  const isSelectedDetail = detail !== null && String(detail.id) === selectedId;
  const selectedStatus = isSelectedDetail ? detail.status : selectedVersionSummary?.status;
  const isDraft = selectedStatus === "draft";
  const canEditDraft = isDraft && canManage;

  function applyDimensionPercentsToRows(rows: OddsItemRow[]): OddsItemRow[] {
    const r2 = Number.parseFloat(p2);
    const r3 = Number.parseFloat(p3);
    const r4 = Number.parseFloat(p4);
    const rate2 = Number.isFinite(r2) ? r2 / 100 : 0;
    const rate3 = Number.isFinite(r3) ? r3 / 100 : 0;
    const rate4 = Number.isFinite(r4) ? r4 / 100 : 0;
    return rows.map((row) => {
      const t = typesByCode.get(row.play_code);
      const dim = (t?.dimension ?? 2) as 2 | 3 | 4;
      const rate = dim === 4 ? rate4 : dim === 3 ? rate3 : rate2;
      return { ...row, rebate_rate: String(rate) };
    });
  }

  async function handleSave() {
    if (!detail || !canEditDraft) {
      return;
    }
    setSaving(true);
    try {
      const nextRows = applyDimensionPercentsToRows(draftRows);
      const payload = nextRows.map((r) => ({
        play_code: r.play_code,
        prize_scope: r.prize_scope,
        odds_value: r.odds_value,
        rebate_rate: Number.parseFloat(String(r.rebate_rate)) || 0,
        commission_rate: Number.parseFloat(String(r.commission_rate)) || 0,
        currency_code: r.currency_code,
        extra_config_json: r.extra_config_json,
      }));
      const d = await putOddsItems(detail.id, payload);
      const rows = d.items.map((it) => ({ ...it }));
      setDetail(d);
      setDraftRows(rows);
      setP2(inferPercentFrom(2, rows, types));
      setP3(inferPercentFrom(3, rows, types));
      setP4(inferPercentFrom(4, rows, types));
      toast.success(t("versionActions.saveDraft", { ns: "config" }));
      void refreshList();
    } catch (e) {
      toast.error(e instanceof LotteryApiBizError ? e.message : t("wallet.saveFailed", { ns: "config" }));
    } finally {
      setSaving(false);
    }
  }

  async function handlePublish() {
    if (!detail || !canEditDraft) {
      return;
    }
    setSaving(true);
    try {
      const d = await publishOddsVersion(detail.id);
      const rows = d.items.map((it) => ({ ...it }));
      setDetail(d);
      setDraftRows(rows);
      setP2(inferPercentFrom(2, rows, types));
      setP3(inferPercentFrom(3, rows, types));
      setP4(inferPercentFrom(4, rows, types));
      toast.success(t("rebate.publishSuccess", { ns: "config" }));
      void refreshList();
      setSelectedId(String(d.id));
    } catch (e) {
      toast.error(e instanceof LotteryApiBizError ? e.message : t("rebate.publishFailed", { ns: "config" }));
    } finally {
      setSaving(false);
    }
  }

  async function handleNewDraft() {
    setSaving(true);
    try {
      const active = listRows.find((x) => x.status === "active");
      const d = await postOddsVersion({
        reason: `rebate draft ${new Date().toISOString()}`,
        clone_from_version_id: active?.id ?? null,
      });
      toast.success(t("rebate.createDraftSuccess", { ns: "config", version: d.version_no }));
      await refreshList();
      setSelectedId(String(d.id));
      const rows = d.items.map((it) => ({ ...it }));
      setDetail(d);
      setDraftRows(rows);
      setP2(inferPercentFrom(2, rows, types));
      setP3(inferPercentFrom(3, rows, types));
      setP4(inferPercentFrom(4, rows, types));
    } catch (e) {
      toast.error(e instanceof LotteryApiBizError ? e.message : t("rebate.createDraftFailed", { ns: "config" }));
    } finally {
      setSaving(false);
    }
  }

  const activeHead = listRows.find((x) => x.status === "active");

  async function handleDeleteVersion(row: ConfigVersionSummary) {
    try {
      await deleteOddsVersion(row.id);
      toast.success(t("versionSwitcher.delete", { ns: "config" }));
      await refreshList();
    } catch (e) {
      toast.error(e instanceof LotteryApiBizError ? e.message : t("rebate.deleteFailed", { ns: "config" }));
      throw e;
    }
  }

  const toolbarBlock = embedded ? null : (
    <ConfigDocToolbar
      switcher={
        <ConfigVersionSwitcher
          versions={listRows}
          selectedId={selectedId}
          onSelectedIdChange={setSelectedId}
          loading={loading}
          sheetTitle={`${t("nav.items.rebate", { ns: "config" })} ${t("versionSwitcher.sheetTitle", { ns: "config" })}`}
          sheetDescription={t("rebate.sheetDescription", { ns: "config" })}
          onDeleteVersion={handleDeleteVersion}
        />
      }
      actions={
        <ConfigVersionActions
          isDraft={isDraft}
          canManage={canManage}
          loadingList={loading}
          loadingDetail={loadingDetail}
          saving={saving}
          publishLabel={t("rebate.publishLabel", { ns: "config" })}
          onRefresh={() => void refreshList()}
          onNewDraft={() => void handleNewDraft()}
          onSaveDraft={() => void handleSave()}
          onPublish={() =>
            requestConfirm({
              title: t("rebate.publishDialog.title", { ns: "config" }),
              description: t("rebate.publishDialog.description", { ns: "config" }),
              confirmLabel: t("rebate.publishDialog.confirm", { ns: "config" }),
              confirmVariant: "destructive",
              onConfirm: () => handlePublish(),
            })
          }
        />
      }
    />
  );

  const contextBlock =
    embedded || !detail ? null : (
      <ConfigContextBanner emphasis={!isDraft}>
        {t("rebate.editingVersion", {
          ns: "config",
          version: detail.version_no,
          status:
            detail.status === "draft"
              ? t("versionStatus.draft", { ns: "config" })
              : detail.status === "active"
                ? t("versionStatus.active", { ns: "config" })
                : t("versionStatus.archived", { ns: "config" }),
        })}
        {!isDraft ? (
          <>
            {" "}
            — <ConfigContextEmphasis>{t("rebate.readOnlyHint", { ns: "config" })}</ConfigContextEmphasis>
          </>
        ) : null}
      </ConfigContextBanner>
    );

  const fieldsBlock = (
    <>
      <div className="grid gap-5 sm:grid-cols-3">
          <div className="grid gap-2">
            <Label>{t("rebate.fields.d2", { ns: "config" })}</Label>
            {canEditDraft ? (
              <Input
                type="number"
                step="0.01"
                min={0}
                className="font-mono tabular-nums"
                disabled={saving}
                value={p2}
                onChange={(e) => setP2(e.target.value)}
              />
            ) : (
              <ConfigReadonlyValue mono>{p2}</ConfigReadonlyValue>
            )}
          </div>
          <div className="grid gap-2">
            <Label>{t("rebate.fields.d3", { ns: "config" })}</Label>
            {canEditDraft ? (
              <Input
                type="number"
                step="0.01"
                min={0}
                className="font-mono tabular-nums"
                disabled={saving}
                value={p3}
                onChange={(e) => setP3(e.target.value)}
              />
            ) : (
              <ConfigReadonlyValue mono>{p3}</ConfigReadonlyValue>
            )}
          </div>
          <div className="grid gap-2">
            <Label>{t("rebate.fields.d4", { ns: "config" })}</Label>
            {canEditDraft ? (
              <Input
                type="number"
                step="0.01"
                min={0}
                className="font-mono tabular-nums"
                disabled={saving}
                value={p4}
                onChange={(e) => setP4(e.target.value)}
              />
            ) : (
              <ConfigReadonlyValue mono>{p4}</ConfigReadonlyValue>
            )}
          </div>
        </div>

        <div className="flex items-start gap-3 px-1">
          <Checkbox
            id="win-enjoy"
            checked
            aria-disabled
            disabled
            aria-label={t("rebate.winEnjoy.label", { ns: "config" })}
          />
          <div className="grid gap-1">
            <Label htmlFor="win-enjoy" className="font-medium leading-snug">
              {t("rebate.winEnjoy.label", { ns: "config" })}
            </Label>
          </div>
        </div>

      {!embedded ? (
        <div className="grid gap-1 text-sm">
          <span className="text-muted-foreground">{t("rebate.effectiveTime", { ns: "config" })}</span>
          <span className="font-mono text-sm">
            {activeHead?.effective_at ? formatDt(activeHead.effective_at) : "—"}
          </span>
        </div>
      ) : null}

      {loading || loadingDetail ? (
        <p className="text-sm text-muted-foreground">{t("states.loading", { ns: "common" })}</p>
      ) : null}
    </>
  );

  if (embedded) {
    return (
      <div className="space-y-6">
        {contextBlock}
        {fieldsBlock}
        <ConfirmDialog />
      </div>
    );
  }

  return (
    <ConfigDocPage
      title={t("nav.items.rebate", { ns: "config" })}
      toolbar={toolbarBlock}
      context={contextBlock}
    >
      {fieldsBlock}
      <ConfirmDialog />
    </ConfigDocPage>
  );
}
