"use client";

import Link from "next/link";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

import { postAdminAgentLine } from "@/api/admin-agent-lines";
import { getAdminIntegrationSites } from "@/api/admin-integration-sites";
import { AdminPageCard } from "@/components/admin/admin-page-card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { useAsyncEffect } from "@/hooks/use-async-effect";
import { adminSiteCodeLabel } from "@/lib/admin-select-display";
import {
  ADMIN_PASSWORD_MIN_LENGTH,
  validateAdminLoginAccount,
  validateAdminPassword,
} from "@/lib/admin-input-validation";
import { LotteryApiBizError } from "@/types/api/errors";
import type { AdminIntegrationSiteRow } from "@/types/api/admin-integration-site";
import type { AdminAgentLineProvisionResult } from "@/types/api/admin-agent-line";

type AgentLineProvisionWizardProps = {
  embedded?: boolean;
  /** 预选接入站点（如代理线路页当前选中的站点） */
  defaultSiteCode?: string;
  onSuccess?: (result: AdminAgentLineProvisionResult) => void | Promise<void>;
};

function clampPercentInput(value: string): string {
  if (value.trim() === "") {
    return "";
  }

  const parsed = Number.parseFloat(value);
  if (!Number.isFinite(parsed)) {
    return "0";
  }

  return String(Math.min(100, Math.max(0, parsed)));
}

function clampIntegerInput(value: string): string {
  if (value.trim() === "") {
    return "";
  }

  const parsed = Number.parseInt(value, 10);
  if (!Number.isFinite(parsed)) {
    return "0";
  }

  return String(Math.max(0, parsed));
}

export function AgentLineProvisionWizard({
  embedded = false,
  defaultSiteCode,
  onSuccess,
}: AgentLineProvisionWizardProps): React.ReactElement {
  const { t } = useTranslation(["agents", "common"]);
  const [submitting, setSubmitting] = useState(false);
  const [sitesLoading, setSitesLoading] = useState(true);
  const [sites, setSites] = useState<AdminIntegrationSiteRow[]>([]);
  const [form, setForm] = useState({
    site_code: "",
    name: "",
    username: "",
    password: "",
    total_share_rate: "0",
    credit_limit: "0",
    rebate_limit: "0",
    default_player_rebate: "0",
    can_grant_extra_rebate: false,
  });

  useAsyncEffect(() => {
    setSitesLoading(true);
    void getAdminIntegrationSites()
      .then((data) => setSites(data.items))
      .catch(() => setSites([]))
      .finally(() => setSitesLoading(false));
  }, []);

  const unboundSites = useMemo(
    () => sites.filter((row) => !row.has_line_root),
    [sites],
  );

  useAsyncEffect(() => {
    if (sitesLoading || form.site_code !== "" || !defaultSiteCode) {
      return;
    }
    const normalized = defaultSiteCode.trim().toLowerCase();
    const matched = unboundSites.find((row) => row.code.toLowerCase() === normalized);
    if (matched) {
      setForm((f) => ({ ...f, site_code: matched.code }));
    }
  }, [defaultSiteCode, form.site_code, sitesLoading, unboundSites]);

  async function onSubmit(e: React.FormEvent): Promise<void> {
    e.preventDefault();
    if (!form.site_code.trim()) {
      toast.error(t("agents:lineProvision.siteRequired", { defaultValue: "请选择接入站点" }));
      return;
    }
    if (!form.name.trim()) {
      toast.error(t("agents:nameRequired", { defaultValue: "请填写代理名称" }));
      return;
    }
    if (!form.username.trim()) {
      toast.error(t("agents:usernameRequired", { defaultValue: "请填写登录名" }));
      return;
    }
    const usernameIssue = validateAdminLoginAccount(form.username);
    if (usernameIssue === "invalid_charset") {
      toast.error(
        t("agents:usernameInvalidCharset", {
          defaultValue: "登录名只能使用字母、数字、点（.）、下划线和连字符",
        }),
      );
      return;
    }
    if (!form.password.trim()) {
      toast.error(t("agents:passwordRequired", { defaultValue: "请填写密码" }));
      return;
    }
    const passwordIssue = validateAdminPassword(form.password);
    if (passwordIssue === "too_short") {
      toast.error(t("agents:passwordMinLength", { defaultValue: "密码至少 6 位" }));
      return;
    }

    const shareRate = Number.parseFloat(form.total_share_rate);
    const creditLimit = Number.parseInt(form.credit_limit, 10);
    const rebateLimit = Number.parseFloat(form.rebate_limit);
    const defaultPlayerRebate = Number.parseFloat(form.default_player_rebate);

    if (Number.isNaN(shareRate) || shareRate < 0 || shareRate > 100) {
      toast.error(
        t("agents:profile.validation.shareRange", {
          defaultValue: "占成比例须在 0–100 之间",
        }),
      );
      return;
    }
    if (Number.isNaN(creditLimit) || creditLimit < 0) {
      toast.error(
        t("agents:profile.validation.creditInvalid", {
          defaultValue: "授信额度不能为负数",
        }),
      );
      return;
    }
    if (Number.isNaN(rebateLimit) || rebateLimit < 0 || rebateLimit > 100) {
      toast.error(
        t("agents:profile.validation.rebateLimitRange", {
          defaultValue: "回水上限须在 0–100% 之间",
        }),
      );
      return;
    }
    if (
      Number.isNaN(defaultPlayerRebate) ||
      defaultPlayerRebate < 0 ||
      defaultPlayerRebate > 100
    ) {
      toast.error(
        t("agents:profile.validation.defaultRebateRange", {
          defaultValue: "默认玩家回水须在 0–100% 之间",
        }),
      );
      return;
    }
    if (defaultPlayerRebate > rebateLimit) {
      toast.error(
        t("agents:profile.validation.defaultExceedsLimit", {
          defaultValue: "默认玩家回水不能超过回水上限",
        }),
      );
      return;
    }
    setSubmitting(true);
    try {
      const result = await postAdminAgentLine({
        site_code: form.site_code.trim().toLowerCase(),
        name: form.name.trim(),
        username: form.username.trim(),
        password: form.password,
        total_share_rate: shareRate,
        credit_limit: creditLimit,
        rebate_limit: rebateLimit,
        default_player_rebate: defaultPlayerRebate,
        can_grant_extra_rebate: form.can_grant_extra_rebate,
      });
      toast.success(t("agents:lineProvision.success", { defaultValue: "一级代理已创建" }));
      setForm(() => ({
        site_code: "",
        name: "",
        username: "",
        password: "",
        total_share_rate: "0",
        credit_limit: "0",
        rebate_limit: "0",
        default_player_rebate: "0",
        can_grant_extra_rebate: false,
      }));
      const data = await getAdminIntegrationSites();
      setSites(data.items);
      await onSuccess?.(result);
    } catch (err) {
      const msg =
        err instanceof LotteryApiBizError ? err.message : t("common:error.generic");
      toast.error(msg);
    } finally {
      setSubmitting(false);
    }
  }

  const content = (
    <>
      {!embedded ? (
        <p className="mb-2 max-w-xl text-sm text-muted-foreground">
          {t("agents:subnav.provisionHint", {
            defaultValue:
            "请先在「平台管理 → 接入配置」创建接入站点；对接密钥在站点创建时一次性展示。",
          })}
        </p>
      ) : null}
      <p className="mb-4 max-w-xl text-sm text-muted-foreground">
        {t("agents:lineProvision.description", {
          defaultValue:
            "将一级代理绑定到已有接入站点，并配置后台登录账号与占成、授信、回水。",
        })}{" "}
        <Link
          href="/admin/config/integration-sites"
          className="font-medium text-primary underline-offset-4 hover:underline"
        >
          {t("agents:lineProvision.openIntegrationSites", {
            defaultValue: "前往接入站点",
          })}
        </Link>
      </p>
      <form className="grid max-w-xl gap-4" onSubmit={onSubmit}>
        <div className="grid gap-2">
          <Label>{t("agents:lineProvision.siteCode", { defaultValue: "接入站点" })}</Label>
          <Select
            value={form.site_code}
            onValueChange={(value) => setForm((f) => ({ ...f, site_code: value ?? "" }))}
            disabled={sitesLoading || unboundSites.length === 0}
          >
            <SelectTrigger>
              <SelectValue>
                {(v) =>
                  adminSiteCodeLabel(
                    v,
                    unboundSites,
                    sitesLoading
                      ? t("common:loading", { defaultValue: "加载中…" })
                      : unboundSites.length === 0
                        ? t("agents:lineProvision.noUnboundSite", {
                            defaultValue: "暂无未绑定一级代理的站点",
                          })
                        : t("agents:lineProvision.siteCodePlaceholder", {
                            defaultValue: "选择站点",
                          }),
                  )
                }
              </SelectValue>
            </SelectTrigger>
            <SelectContent>
              {unboundSites.map((site) => (
                <SelectItem key={site.id} value={site.code}>
                  {site.name} ({site.code})
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        <div className="grid gap-2">
          <Label>{t("agents:lineProvision.name", { defaultValue: "一级代理名称" })}</Label>
          <Input
            value={form.name}
            onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
            required
          />
        </div>
        <div className="grid gap-2">
          <Label>{t("agents:lineProvision.username", { defaultValue: "后台登录账号" })}</Label>
          <Input
            value={form.username}
            onChange={(e) => setForm((f) => ({ ...f, username: e.target.value }))}
            required
          />
        </div>
        <div className="grid gap-2">
          <Label>{t("agents:lineProvision.password", { defaultValue: "初始密码" })}</Label>
          <Input
            type="password"
            value={form.password}
            onChange={(e) => setForm((f) => ({ ...f, password: e.target.value }))}
            required
            minLength={ADMIN_PASSWORD_MIN_LENGTH}
          />
          <p className="text-xs text-muted-foreground">
            {t("agents:lineProvision.passwordHint", {
              defaultValue: "至少 {{min}} 位",
              min: ADMIN_PASSWORD_MIN_LENGTH,
            })}
          </p>
        </div>

        <p className="text-sm font-medium">
          {t("agents:profile.section", { defaultValue: "占成与授信" })}
        </p>
        <div className="grid gap-3 sm:grid-cols-2">
          <div className="grid gap-2">
            <Label>{t("agents:profile.totalShareRate", { defaultValue: "占成比例 (%)" })}</Label>
            <Input
              type="number"
              min={0}
              max={100}
              step="0.01"
              value={form.total_share_rate}
              onChange={(e) => setForm((f) => ({ ...f, total_share_rate: e.target.value }))}
              onBlur={(e) =>
                setForm((f) => ({ ...f, total_share_rate: clampPercentInput(e.target.value) }))
              }
            />
          </div>
          <div className="grid gap-2">
            <Label>{t("agents:profile.creditLimit", { defaultValue: "授信额度" })}</Label>
            <Input
              type="number"
              min={0}
              value={form.credit_limit}
              onChange={(e) => setForm((f) => ({ ...f, credit_limit: e.target.value }))}
              onBlur={(e) =>
                setForm((f) => ({ ...f, credit_limit: clampIntegerInput(e.target.value) }))
              }
            />
          </div>
          <div className="grid gap-2">
            <Label>{t("agents:profile.rebateLimit", { defaultValue: "回水上限 (%)" })}</Label>
            <Input
              type="number"
              min={0}
              max={100}
              step="0.01"
              value={form.rebate_limit}
              placeholder="50"
              onChange={(e) => setForm((f) => ({ ...f, rebate_limit: e.target.value }))}
              onBlur={(e) =>
                setForm((f) => ({ ...f, rebate_limit: clampPercentInput(e.target.value) }))
              }
            />
          </div>
          <div className="grid gap-2">
            <Label>{t("agents:profile.defaultPlayerRebate", { defaultValue: "默认玩家回水 (%)" })}</Label>
            <Input
              type="number"
              min={0}
              max={100}
              step="0.01"
              value={form.default_player_rebate}
              placeholder="50"
              onChange={(e) => setForm((f) => ({ ...f, default_player_rebate: e.target.value }))}
              onBlur={(e) =>
                setForm((f) => ({
                  ...f,
                  default_player_rebate: clampPercentInput(e.target.value),
                }))
              }
            />
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Switch
            checked={form.can_grant_extra_rebate}
            onCheckedChange={(checked) =>
              setForm((f) => ({ ...f, can_grant_extra_rebate: checked }))
            }
          />
          <Label>
            {t("agents:profile.canGrantExtraRebate", { defaultValue: "允许额外回水" })}
          </Label>
        </div>

        <Button type="submit" disabled={submitting || unboundSites.length === 0}>
          {submitting
            ? t("common:submitting", { defaultValue: "提交中…" })
            : t("agents:lineProvision.submit", { defaultValue: "创建一级代理" })}
        </Button>
      </form>
    </>
  );

  if (embedded) {
    return <div className="space-y-0">{content}</div>;
  }

  return (
    <AdminPageCard title={t("agents:lineProvision.title", { defaultValue: "创建一级代理" })}>
      {content}
    </AdminPageCard>
  );
}
