"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 { FRONTEND_KEYS } from "@/modules/settings/settings-keys";
import type { AdminSettingBatchItem } from "@/api/admin-settings";
import { Label } from "@/components/ui/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import { adminHasAnyPermission } from "@/lib/admin-permissions";
import { PRD_ODDS_MANAGE, PRD_REBATE_MANAGE } from "@/lib/admin-prd";
import { useAdminProfile } from "@/stores/admin-session";

interface FrontendDraft {
  playRulesHtmlZh: string;
  playRulesHtmlEn: string;
  playRulesHtmlNe: string;
}

const INITIAL: FrontendDraft = {
  playRulesHtmlZh: "",
  playRulesHtmlEn: "",
  playRulesHtmlNe: "",
};

function fromKv(kv: Record<string, unknown>): FrontendDraft {
  const legacyHtml = String(kv[FRONTEND_KEYS.PLAY_RULES_HTML] ?? "");
  return {
    playRulesHtmlZh: String(kv[FRONTEND_KEYS.PLAY_RULES_HTML_ZH] ?? legacyHtml),
    playRulesHtmlEn: String(kv[FRONTEND_KEYS.PLAY_RULES_HTML_EN] ?? ""),
    playRulesHtmlNe: String(kv[FRONTEND_KEYS.PLAY_RULES_HTML_NE] ?? ""),
  };
}

function buildDirtyItems(draft: FrontendDraft, saved: FrontendDraft): AdminSettingBatchItem[] {
  const items: AdminSettingBatchItem[] = [];
  if (draft.playRulesHtmlZh !== saved.playRulesHtmlZh) {
    items.push({ key: FRONTEND_KEYS.PLAY_RULES_HTML_ZH, value: draft.playRulesHtmlZh });
    items.push({ key: FRONTEND_KEYS.PLAY_RULES_HTML, value: draft.playRulesHtmlZh });
  }
  if (draft.playRulesHtmlEn !== saved.playRulesHtmlEn) {
    items.push({ key: FRONTEND_KEYS.PLAY_RULES_HTML_EN, value: draft.playRulesHtmlEn });
  }
  if (draft.playRulesHtmlNe !== saved.playRulesHtmlNe) {
    items.push({ key: FRONTEND_KEYS.PLAY_RULES_HTML_NE, value: draft.playRulesHtmlNe });
  }
  return items;
}

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

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

  return (
    <>
      <AdminPageCard title={t("system.frontendConfig", { ns: "config" })}>
        <div className="grid gap-4">
          <div className="space-y-1">
            <Label className="font-medium text-muted-foreground">
              {t("system.fields.playRulesHtml", { ns: "config" })}
            </Label>
            <p className="text-xs text-muted-foreground/80">
              {t("system.fields.playRulesHtmlDesc", { ns: "config" })}
            </p>
          </div>
          <Tabs defaultValue="zh" className="w-full">
            <TabsList className="w-full max-w-md bg-muted/40">
              <TabsTrigger value="zh">{t("play.locales.zh", { ns: "config" })}</TabsTrigger>
              <TabsTrigger value="en">{t("play.locales.en", { ns: "config" })}</TabsTrigger>
              <TabsTrigger value="ne">{t("play.locales.ne", { ns: "config" })}</TabsTrigger>
            </TabsList>
            <TabsContent value="zh" className="mt-3">
              <Textarea
                id="play-rules-html-zh"
                value={draft.playRulesHtmlZh}
                onChange={(e) => updateField("playRulesHtmlZh", e.target.value)}
                disabled={!canManage || loading || saving}
                className="min-h-[200px] font-mono text-xs bg-background/50 transition-colors focus:bg-background"
                placeholder="<div>...</div>"
              />
            </TabsContent>
            <TabsContent value="en" className="mt-3">
              <Textarea
                id="play-rules-html-en"
                value={draft.playRulesHtmlEn}
                onChange={(e) => updateField("playRulesHtmlEn", e.target.value)}
                disabled={!canManage || loading || saving}
                className="min-h-[200px] font-mono text-xs bg-background/50 transition-colors focus:bg-background"
                placeholder="<div>...</div>"
              />
            </TabsContent>
            <TabsContent value="ne" className="mt-3">
              <Textarea
                id="play-rules-html-ne"
                value={draft.playRulesHtmlNe}
                onChange={(e) => updateField("playRulesHtmlNe", e.target.value)}
                disabled={!canManage || loading || saving}
                className="min-h-[200px] font-mono text-xs bg-background/50 transition-colors focus:bg-background"
                placeholder="<div>...</div>"
              />
            </TabsContent>
          </Tabs>

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