"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 { useSettingsSection } from "@/modules/settings/hooks/use-settings-section";
import { SETTLEMENT_KEYS } from "@/modules/settings/settings-keys";
import type { AdminSettingBatchItem } from "@/api/admin-settings";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
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="rounded-xl border border-border/70 bg-card overflow-hidden shadow-sm">
            <div className="flex flex-wrap items-center justify-between gap-3 px-4 py-3.5 bg-background/50 transition-colors hover:bg-muted/30 border-b border-border/50">
              <Label className="font-medium cursor-pointer" onClick={() => updateField("autoSettlement", !draft.autoSettlement)}>{t("system.fields.autoSettlement", { ns: "config" })}</Label>
              <Switch
                checked={draft.autoSettlement}
                disabled={loading || saving}
                aria-label={t("system.fields.autoSettlement", { ns: "config" })}
                onCheckedChange={(value) => updateField("autoSettlement", value)}
              />
            </div>

            <div className="flex flex-wrap items-center justify-between gap-3 px-4 py-3.5 bg-background/50 transition-colors hover:bg-muted/30 border-b border-border/50">
              <Label className="font-medium cursor-pointer" onClick={() => updateField("autoApprove", !draft.autoApprove)}>{t("system.fields.autoApprove", { ns: "config" })}</Label>
              <Switch
                checked={draft.autoApprove}
                disabled={loading || saving}
                aria-label={t("system.fields.autoApprove", { ns: "config" })}
                onCheckedChange={(value) => updateField("autoApprove", value)}
              />
            </div>

            <div className="flex flex-wrap items-center justify-between gap-3 px-4 py-3.5 bg-background/50 transition-colors hover:bg-muted/30 border-b border-border/50">
              <Label className="font-medium cursor-pointer" onClick={() => updateField("autoPayout", !draft.autoPayout)}>{t("system.fields.autoPayout", { ns: "config" })}</Label>
              <Switch
                checked={draft.autoPayout}
                disabled={loading || saving}
                aria-label={t("system.fields.autoPayout", { ns: "config" })}
                onCheckedChange={(value) => updateField("autoPayout", value)}
              />
            </div>

            <div className="flex flex-wrap items-center justify-between gap-3 px-4 py-3.5 bg-background/50 transition-colors hover:bg-muted/30">
              <div className="min-w-0 space-y-1 pr-4 cursor-pointer" onClick={() => updateField("applyRebateToPayout", !draft.applyRebateToPayout)}>
                <Label className="font-medium cursor-pointer">{t("system.fields.applyRebateToPayout", { ns: "config" })}</Label>
                <p className="text-[11px] text-muted-foreground/80">{t("system.hints.applyRebateToPayout", { ns: "config" })}</p>
              </div>
              <Switch
                checked={draft.applyRebateToPayout}
                disabled={loading || saving}
                aria-label={t("system.fields.applyRebateToPayout", { ns: "config" })}
                onCheckedChange={(value) => updateField("applyRebateToPayout", value)}
              />
            </div>
          </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 />
    </>
  );
}
