"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 { DRAW_KEYS } from "@/modules/settings/settings-keys";
import type { AdminSettingBatchItem } from "@/api/admin-settings";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { adminHasAnyPermission } from "@/lib/admin-permissions";
import { PRD_DRAW_RESULT_MANAGE } from "@/lib/admin-prd";
import { useAdminProfile } from "@/stores/admin-session";

interface DrawDraft {
  requireManualReview: boolean;
  cooldownMinutes: string;
}

const INITIAL: DrawDraft = {
  requireManualReview: false,
  cooldownMinutes: "15",
};

function fromKv(kv: Record<string, unknown>): DrawDraft {
  return {
    requireManualReview: Boolean(kv[DRAW_KEYS.REQUIRE_MANUAL_REVIEW] ?? false),
    cooldownMinutes: String(kv[DRAW_KEYS.COOLDOWN_MINUTES] ?? 15),
  };
}

function buildDirtyItems(draft: DrawDraft, saved: DrawDraft): AdminSettingBatchItem[] {
  const items: AdminSettingBatchItem[] = [];

  if (draft.requireManualReview !== saved.requireManualReview) {
    items.push({ key: DRAW_KEYS.REQUIRE_MANUAL_REVIEW, value: draft.requireManualReview });
  }
  if (draft.cooldownMinutes !== saved.cooldownMinutes) {
    items.push({
      key: DRAW_KEYS.COOLDOWN_MINUTES,
      value: Math.max(0, Number.parseInt(draft.cooldownMinutes || "0", 10) || 0),
    });
  }

  return items;
}

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

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

  return (
    <>
      <AdminPageCard
        title={t("system.sections.draw", { ns: "config" })}
        description={t("system.sections.drawDescription", { ns: "config" })}
      >
        <div className="space-y-6">
          <div className="overflow-hidden rounded-xl border border-border/70 bg-card shadow-sm">
            <SettingsToggleRow
              label={t("system.fields.manualReview", { ns: "config" })}
              hint={t("system.hints.manualReview", { ns: "config" })}
              checked={draft.requireManualReview}
              disabled={!canManage || loading || saving}
              onCheckedChange={(value) => updateField("requireManualReview", value)}
            />
          </div>

          <div className="max-w-sm space-y-2">
            <Label htmlFor="cooldown-minutes" className="text-muted-foreground">
              {t("system.fields.cooldownMinutes", { ns: "config" })}
            </Label>
            <p className="text-sm text-muted-foreground">
              {t("system.hints.cooldownMinutes", { ns: "config" })}
            </p>
            <Input
              id="cooldown-minutes"
              type="number"
              min="0"
              step="1"
              value={draft.cooldownMinutes}
              placeholder={t("system.placeholders.cooldownMinutes", { ns: "config" })}
              onChange={(e) => updateField("cooldownMinutes", e.target.value)}
              disabled={!canManage || loading || saving}
              className="h-10 bg-background/50 transition-colors focus:bg-background"
            />
          </div>

          <SettingsSectionActions
            dirty={dirty}
            loading={!canManage || loading}
            saving={saving}
            onSave={() =>
              requestConfirm({
                title: t("system.confirmSaveDrawTitle", { ns: "config" }),
                description: t("system.confirmSaveDrawDescription", { 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 />
    </>
  );
}