"use client";

import { useCallback } from "react";
import { useTranslation } from "react-i18next";

import { AdminPageCard } from "@/components/admin/admin-page-card";
import { useConfirmAction } from "@/hooks/use-confirm-action";
import { SettingsSectionActions } from "@/modules/settings/components/settings-section-actions";
import { SettingsToggleRow } from "@/modules/settings/components/settings-toggle-row";
import { useSettingsSection } from "@/modules/settings/hooks/use-settings-section";
import { SETTLEMENT_KEYS } from "@/modules/settings/settings-keys";
import type { AdminSettingBatchItem } from "@/api/admin-settings";
import { adminHasAnyPermission } from "@/lib/admin-permissions";
import { PRD_PAYOUT_MANAGE } from "@/lib/admin-prd";
import { useAdminProfile } from "@/stores/admin-session";

interface SettlementDraft {
  autoSettlement: boolean;
  autoApprove: boolean;
  autoPayout: boolean;
  applyRebateToPayout: boolean;
}

const INITIAL: SettlementDraft = {
  autoSettlement: true,
  autoApprove: true,
  autoPayout: true,
  applyRebateToPayout: false,
};

function fromKv(kv: Record<string, unknown>): SettlementDraft {
  return {
    autoSettlement: Boolean(kv[SETTLEMENT_KEYS.AUTO_SETTLEMENT] ?? true),
    autoApprove: Boolean(kv[SETTLEMENT_KEYS.AUTO_APPROVE] ?? true),
    autoPayout: Boolean(kv[SETTLEMENT_KEYS.AUTO_PAYOUT] ?? true),
    applyRebateToPayout: Boolean(kv[SETTLEMENT_KEYS.APPLY_REBATE_TO_PAYOUT] ?? false),
  };
}

function buildDirtyItems(draft: SettlementDraft, saved: SettlementDraft): AdminSettingBatchItem[] {
  const items: AdminSettingBatchItem[] = [];
  if (draft.autoSettlement !== saved.autoSettlement) {
    items.push({ key: SETTLEMENT_KEYS.AUTO_SETTLEMENT, value: draft.autoSettlement });
  }
  if (draft.autoApprove !== saved.autoApprove) {
    items.push({ key: SETTLEMENT_KEYS.AUTO_APPROVE, value: draft.autoApprove });
  }
  if (draft.autoPayout !== saved.autoPayout) {
    items.push({ key: SETTLEMENT_KEYS.AUTO_PAYOUT, value: draft.autoPayout });
  }
  if (draft.applyRebateToPayout !== saved.applyRebateToPayout) {
    items.push({ key: SETTLEMENT_KEYS.APPLY_REBATE_TO_PAYOUT, value: draft.applyRebateToPayout });
  }
  return items;
}

export function SettlementSettingsPanel() {
  const { t } = useTranslation(["config", "adminUsers", "common"]);
  const profile = useAdminProfile();
  const canManage = adminHasAnyPermission(profile?.permissions, [PRD_PAYOUT_MANAGE]);
  const { request: requestConfirm, ConfirmDialog } = useConfirmAction();
  const buildItems = useCallback(buildDirtyItems, []);
  const section = useSettingsSection({
    initialDraft: INITIAL,
    fromKv,
    buildDirtyItems: buildItems,
    saveSuccessKey: "system.saveSettlementSuccess",
    saveFailedKey: "system.saveFailed",
  });

  const { draft, loading, saving, dirty, updateField, discard, save } = section;

  if (!canManage) {
    return null;
  }

  return (
    <>
      <AdminPageCard
        title={t("system.sections.settlement", { ns: "config" })}
        description={t("system.sections.settlementDescription", { ns: "config" })}
      >
        <div className="space-y-5">
          <div className="overflow-hidden rounded-xl border border-border/70 bg-card shadow-sm divide-y divide-border/50">
            <SettingsToggleRow
              label={t("system.fields.autoSettlement", { ns: "config" })}
              hint={t("system.hints.autoSettlement", { ns: "config" })}
              checked={draft.autoSettlement}
              disabled={loading || saving}
              onCheckedChange={(value) => updateField("autoSettlement", value)}
            />
            <SettingsToggleRow
              label={t("system.fields.autoApprove", { ns: "config" })}
              hint={t("system.hints.autoApprove", { ns: "config" })}
              checked={draft.autoApprove}
              disabled={loading || saving}
              onCheckedChange={(value) => updateField("autoApprove", value)}
            />
            <SettingsToggleRow
              label={t("system.fields.autoPayout", { ns: "config" })}
              hint={t("system.hints.autoPayout", { ns: "config" })}
              checked={draft.autoPayout}
              disabled={loading || saving}
              onCheckedChange={(value) => updateField("autoPayout", value)}
            />
            <SettingsToggleRow
              label={t("system.fields.applyRebateToPayout", { ns: "config" })}
              hint={t("system.hints.applyRebateToPayout", { ns: "config" })}
              checked={draft.applyRebateToPayout}
              disabled={loading || saving}
              onCheckedChange={(value) => updateField("applyRebateToPayout", value)}
            />
          </div>

          <SettingsSectionActions
            dirty={dirty}
            loading={loading}
            saving={saving}
            onSave={() =>
              requestConfirm({
                title: t("system.confirmSaveSettlementTitle", { ns: "config" }),
                description: t("system.confirmSaveSettlementDescription", { ns: "config" }),
                confirmLabel: t("confirm.confirmSave", { ns: "common" }),
                onConfirm: () => {
                  void save();
                },
              })
            }
            onDiscard={discard}
            saveLabel={t("actions.save", { ns: "adminUsers" })}
            savingLabel={t("saving", { ns: "adminUsers" })}
            discardLabel={t("system.discard", { ns: "config" })}
          />
        </div>
      </AdminPageCard>
      <ConfirmDialog />
    </>
  );
}