"use client";

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

import {
  getAdminSettings,
  updateAdminSetting,
} from "@/api/admin-settings";
import { useConfirmAction } from "@/hooks/use-confirm-action";
import { Button } from "@/components/ui/button";
import { ConfigDocPage } from "@/modules/config/config-doc-page";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { LotteryApiBizError } from "@/types/api/errors";

const WALLET_GROUP = "wallet";

const KEYS = {
  IN_MIN: "wallet.transfer_in_min_minor",
  IN_MAX: "wallet.transfer_in_max_minor",
  OUT_MIN: "wallet.transfer_out_min_minor",
  OUT_MAX: "wallet.transfer_out_max_minor",
} as const;

function minorUnitsToDisplay(n: unknown, decimals = 2): string {
  const num = Number(n);
  if (!Number.isFinite(num)) return "";
  return (num / 100).toFixed(decimals);
}

function displayToMinorUnits(s: string): number {
  const n = parseFloat(s);
  if (Number.isNaN(n) || n < 0) return 0;
  return Math.round(n * 100);
}

interface Draft {
  inMin: string;
  inMax: string;
  outMin: string;
  outMax: string;
}

type WalletConfigDocScreenProps = {
  embedded?: boolean;
};

export function WalletConfigDocScreen({ embedded = false }: WalletConfigDocScreenProps) {
  const { t } = useTranslation(["config", "adminUsers", "common"]);
  const { request: requestConfirm, ConfirmDialog } = useConfirmAction();
  const [draft, setDraft] = useState<Draft>({
    inMin: "",
    inMax: "",
    outMin: "",
    outMax: "",
  });
  const [saved, setSaved] = useState<Draft>({ inMin: "", inMax: "", outMin: "", outMax: "" });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [dirty, setDirty] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await getAdminSettings(WALLET_GROUP);
      const kv: Record<string, unknown> = {};
      for (const item of res.items) {
        kv[item.key] = item.value;
      }
      const d: Draft = {
        inMin: minorUnitsToDisplay(kv[KEYS.IN_MIN] ?? 100),
        inMax: minorUnitsToDisplay(kv[KEYS.IN_MAX] ?? 0),
        outMin: minorUnitsToDisplay(kv[KEYS.OUT_MIN] ?? 100),
        outMax: minorUnitsToDisplay(kv[KEYS.OUT_MAX] ?? 0),
      };
      setDraft(d);
      setSaved(d);
      setDirty(false);
    } catch {
      toast.error(t("wallet.loadFailed", { ns: "config" }));
    } finally {
      setLoading(false);
    }
  }, [t]);

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

  const handleChange = (field: keyof Draft, value: string) => {
    setDraft((prev) => ({ ...prev, [field]: value }));
    setDirty(true);
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      await updateAdminSetting(KEYS.IN_MIN, displayToMinorUnits(draft.inMin));
      await updateAdminSetting(KEYS.IN_MAX, displayToMinorUnits(draft.inMax));
      await updateAdminSetting(KEYS.OUT_MIN, displayToMinorUnits(draft.outMin));
      await updateAdminSetting(KEYS.OUT_MAX, displayToMinorUnits(draft.outMax));
      toast.success(t("wallet.saveSuccess", { ns: "config" }));
      setSaved(draft);
      setDirty(false);
    } catch (error) {
      toast.error(
        error instanceof LotteryApiBizError ? error.message : t("wallet.saveFailed", { ns: "config" }),
      );
    } finally {
      setSaving(false);
    }
  };

  const content = (
    <>
      <div className="grid gap-5 sm:grid-cols-2">
        <div className="space-y-2">
          <Label htmlFor="in-min">{t("wallet.fields.inMin", { ns: "config" })}</Label>
          <Input
            id="in-min"
            type="number"
            min="0"
            step="0.01"
            placeholder={t("wallet.placeholders.min", { ns: "config" })}
            value={draft.inMin}
            onChange={(e) => handleChange("inMin", e.target.value)}
            disabled={loading || saving}
          />
        </div>
        <div className="space-y-2">
          <Label htmlFor="in-max">{t("wallet.fields.inMax", { ns: "config" })}</Label>
          <Input
            id="in-max"
            type="number"
            min="0"
            step="0.01"
            placeholder={t("wallet.placeholders.max", { ns: "config" })}
            value={draft.inMax}
            onChange={(e) => handleChange("inMax", e.target.value)}
            disabled={loading || saving}
          />
        </div>
        <div className="space-y-2">
          <Label htmlFor="out-min">{t("wallet.fields.outMin", { ns: "config" })}</Label>
          <Input
            id="out-min"
            type="number"
            min="0"
            step="0.01"
            placeholder={t("wallet.placeholders.min", { ns: "config" })}
            value={draft.outMin}
            onChange={(e) => handleChange("outMin", e.target.value)}
            disabled={loading || saving}
          />
        </div>
        <div className="space-y-2">
          <Label htmlFor="out-max">{t("wallet.fields.outMax", { ns: "config" })}</Label>
          <Input
            id="out-max"
            type="number"
            min="0"
            step="0.01"
            placeholder={t("wallet.placeholders.max", { ns: "config" })}
            value={draft.outMax}
            onChange={(e) => handleChange("outMax", e.target.value)}
            disabled={loading || saving}
          />
        </div>
      </div>
      <div className="flex items-center gap-4 pt-2">
        <Button
          onClick={() =>
            requestConfirm({
              title: t("wallet.confirmSaveTitle", { ns: "config" }),
              description: t("wallet.confirmSaveDescription", { ns: "config" }),
              confirmLabel: t("confirm.confirmSave", { ns: "common" }),
              onConfirm: () => handleSave(),
            })
          }
          disabled={!dirty || loading || saving}
        >
          {saving ? t("saving", { ns: "adminUsers" }) : t("actions.save", { ns: "adminUsers" })}
        </Button>
        {dirty && (
          <Button
            variant="outline"
            onClick={() => {
              setDraft(saved);
              setDirty(false);
            }}
          >
            {t("wallet.discard", { ns: "config" })}
          </Button>
        )}
      </div>
      <ConfirmDialog />
    </>
  );

  if (embedded) {
    return content;
  }

  return (
    <ConfigDocPage title={t("wallet.title", { ns: "config" })}>{content}</ConfigDocPage>
  );
}
