"use client";

import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { useCallback, useEffect, useMemo, useState } from "react";
import { AppShell } from "@/components/app/AppShell";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { Field, Input, Select } from "@/components/ui/Field";
import { PageContentSkeleton } from "@/components/ui/Skeleton";
import {
  AdminUser,
  ApiError,
  BranchItem,
  apiGet,
  apiPut,
  getStoredUser,
} from "@/lib/api";
import { resolveBranchId } from "@/lib/resolve-branch";
import { getActiveRole } from "@/lib/session-context";

function asObject(value: unknown): Record<string, unknown> {
  return value && typeof value === "object" && !Array.isArray(value)
    ? (value as Record<string, unknown>)
    : {};
}

/** روش‌های پرداخت، اطلاعات کارت/شبا و تنظیمات درگاه مدرسه. */
export default function PaymentSettingsPage() {
  const searchParams = useSearchParams();
  const user = useMemo(() => getStoredUser<AdminUser>(), []);
  const role = getActiveRole();
  const isSuperAdmin = role === "super_admin" || role === "developer" || Boolean(user?.roles.includes("super_admin") || user?.roles.includes("developer"));
  const queryBranchId = Number(searchParams.get("branchId") || 0) || null;
  const fallbackBranch =
    user?.branches.find((b) => b.is_primary)?.id ?? user?.branches[0]?.id ?? null;

  const [branches, setBranches] = useState<BranchItem[]>([]);
  const [branchId, setBranchId] = useState<number | null>(() =>
    resolveBranchId(queryBranchId, fallbackBranch),
  );

  const [payOnline, setPayOnline] = useState(true);
  const [payCardToCard, setPayCardToCard] = useState(true);

  const [gatewayId, setGatewayId] = useState("mock");
  const [merchantId, setMerchantId] = useState("");
  const [paymentApiUrl, setPaymentApiUrl] = useState("");
  const [paymentApiKey, setPaymentApiKey] = useState("");
  const [paymentApiSecret, setPaymentApiSecret] = useState("");

  const [cardBank, setCardBank] = useState("");
  const [cardNumber, setCardNumber] = useState("");
  const [cardHolder, setCardHolder] = useState("");
  const [cardIban, setCardIban] = useState("");

  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null);

  useEffect(() => {
    setBranchId(resolveBranchId(queryBranchId, fallbackBranch));
  }, [queryBranchId, fallbackBranch]);

  const load = useCallback(async () => {
    if (!user) return;
    setLoading(true);
    setError(null);
    try {
      if (isSuperAdmin) {
        const branchList = await apiGet<BranchItem[]>("/branches");
        setBranches(branchList);
        if (!branchId && branchList[0]?.id) {
          setBranchId(branchList[0].id);
          setLoading(false);
          return;
        }
      }
      if (!branchId) {
        setLoading(false);
        return;
      }

      const suffix = `&branch_id=${branchId}`;
      const [methodsRes, cardRes, gateway, merchant, apiUrl, apiKey, apiSecret] = await Promise.all([
        apiGet<{ value: unknown }>(
          `/settings/resolve?key=registration.payment_methods&organization_id=${user.organization_id}${suffix}`,
        ),
        apiGet<{ value: unknown }>(
          `/settings/resolve?key=registration.card_to_card_info&organization_id=${user.organization_id}${suffix}`,
        ),
        apiGet<{ value: string }>(
          `/settings/resolve?key=finance.gateway_id&organization_id=${user.organization_id}${suffix}`,
        ),
        apiGet<{ value: string | null }>(
          `/settings/resolve?key=finance.merchant_id&organization_id=${user.organization_id}${suffix}`,
        ),
        apiGet<{ value: string | null }>(
          `/settings/resolve?key=finance.payment_api_url&organization_id=${user.organization_id}${suffix}`,
        ),
        apiGet<{ value: string | null }>(
          `/settings/resolve?key=finance.payment_api_key&organization_id=${user.organization_id}${suffix}`,
        ),
        apiGet<{ value: string | null }>(
          `/settings/resolve?key=finance.payment_api_secret&organization_id=${user.organization_id}${suffix}`,
        ),
      ]);

      const methods = Array.isArray(methodsRes.value)
        ? (methodsRes.value as string[])
        : ["online", "card_to_card"];
      setPayOnline(methods.includes("online"));
      setPayCardToCard(methods.includes("card_to_card"));

      const card = asObject(cardRes.value);
      setCardBank(String(card.bank ?? ""));
      setCardNumber(String(card.card ?? ""));
      setCardHolder(String(card.holder ?? ""));
      setCardIban(String(card.iban ?? card.sheba ?? ""));

      setGatewayId(String(gateway.value ?? "mock"));
      setMerchantId(String(merchant.value ?? ""));
      setPaymentApiUrl(String(apiUrl.value ?? ""));
      setPaymentApiKey(String(apiKey.value ?? ""));
      setPaymentApiSecret(String(apiSecret.value ?? ""));
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در بارگذاری");
    } finally {
      setLoading(false);
    }
  }, [branchId, isSuperAdmin, user]);

  useEffect(() => {
    void load();
  }, [load]);

  const save = async () => {
    if (!branchId) return;
    if (!payOnline && !payCardToCard) {
      setError("حداقل یکی از روش‌های پرداخت باید فعال باشد.");
      return;
    }
    setSaving(true);
    setError(null);
    setMessage(null);
    try {
      const methods: string[] = [];
      if (payOnline) methods.push("online");
      if (payCardToCard) methods.push("card_to_card");

      await apiPut(`/branches/${branchId}/settings`, {
        key: "registration.payment_methods",
        value: methods,
        inherits: false,
      });
      await apiPut(`/branches/${branchId}/settings`, {
        key: "registration.card_to_card_info",
        value: {
          bank: cardBank,
          card: cardNumber,
          holder: cardHolder,
          iban: cardIban,
        },
        inherits: false,
      });
      await apiPut(`/branches/${branchId}/settings`, {
        key: "finance.gateway_id",
        value: gatewayId,
        inherits: false,
      });
      await apiPut(`/branches/${branchId}/settings`, {
        key: "finance.merchant_id",
        value: merchantId || null,
        inherits: false,
      });
      await apiPut(`/branches/${branchId}/settings`, {
        key: "finance.payment_api_url",
        value: paymentApiUrl || null,
        inherits: false,
      });
      await apiPut(`/branches/${branchId}/settings`, {
        key: "finance.payment_api_key",
        value: paymentApiKey || null,
        inherits: false,
      });
      await apiPut(`/branches/${branchId}/settings`, {
        key: "finance.payment_api_secret",
        value: paymentApiSecret || null,
        inherits: false,
      });
      setMessage("تنظیمات پرداخت ذخیره شد.");
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در ذخیره");
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <AppShell title="پرداخت و درگاه" subtitle="روش‌های پرداخت، کارت‌به‌کارت و درگاه آنلاین">
        <PageContentSkeleton rows={4} />
      </AppShell>
    );
  }

  return (
    <AppShell title="پرداخت و درگاه" subtitle="روش‌های پرداخت، کارت‌به‌کارت و درگاه آنلاین">
      <div className="space-y-4">
        {error ? <Alert tone="error">{error}</Alert> : null}
        {message ? <Alert tone="success">{message}</Alert> : null}

        <div className="flex flex-wrap gap-2">
          <Link
            href={`/pre-registration/settings${branchId ? `?branchId=${branchId}` : ""}`}
            className="rounded-xl bg-slate-100 px-3 py-2 text-xs font-semibold text-slate-700"
          >
            ← تنظیمات پیش‌ثبت‌نام
          </Link>
          {branchId ? (
            <Link
              href={`/pre-registration/grades?branchId=${branchId}`}
              className="rounded-xl bg-slate-100 px-3 py-2 text-xs font-semibold text-slate-700"
            >
              مبلغ هر پایه
            </Link>
          ) : null}
        </div>

        {isSuperAdmin && branches.length > 0 ? (
          <div className="rounded-2xl border border-[var(--border)] bg-white p-4 shadow-card">
            <Field label="مدرسه">
              <Select
                value={branchId ?? ""}
                onChange={(e) => setBranchId(Number(e.target.value) || null)}
              >
                {branches.map((b) => (
                  <option key={b.id} value={b.id}>{b.name}</option>
                ))}
              </Select>
            </Field>
          </div>
        ) : null}

        {!branchId ? (
          <Alert tone="warning">
            مدرسه فعال مشخص نیست. از{" "}
            <Link href="/select-context" className="underline">انتخاب زمینه</Link> اقدام کنید.
          </Alert>
        ) : (
          <>
            <div className="rounded-2xl border border-[var(--border)] bg-white p-4 shadow-card sm:p-5">
              <h2 className="mb-1 text-sm font-bold text-primary">روش‌های پرداخت فعال</h2>
              <p className="mb-4 text-xs leading-6 text-[var(--muted)]">
                مشخص کنید اولیا در پیش‌ثبت‌نام کدام روش‌ها را ببینند. مبلغ هر پایه جداگانه در قوانین پایه تنظیم می‌شود.
              </p>
              <div className="grid gap-2 sm:grid-cols-2">
                <label
                  className={`flex cursor-pointer gap-3 rounded-xl border p-3 text-sm ${
                    payOnline ? "border-primary/40 bg-primary/5" : "border-[var(--border)]"
                  }`}
                >
                  <input
                    type="checkbox"
                    className="mt-0.5"
                    checked={payOnline}
                    onChange={(e) => setPayOnline(e.target.checked)}
                  />
                  <span>
                    <span className="font-semibold">درگاه پرداخت آنلاین</span>
                    <span className="mt-1 block text-xs text-[var(--muted)]">پرداخت از طریق درگاه متصل به مدرسه</span>
                  </span>
                </label>
                <label
                  className={`flex cursor-pointer gap-3 rounded-xl border p-3 text-sm ${
                    payCardToCard ? "border-primary/40 bg-primary/5" : "border-[var(--border)]"
                  }`}
                >
                  <input
                    type="checkbox"
                    className="mt-0.5"
                    checked={payCardToCard}
                    onChange={(e) => setPayCardToCard(e.target.checked)}
                  />
                  <span>
                    <span className="font-semibold">کارت‌به‌کارت / واریز</span>
                    <span className="mt-1 block text-xs text-[var(--muted)]">نمایش اطلاعات حساب و آپلود رسید</span>
                  </span>
                </label>
              </div>
            </div>

            {payOnline ? (
              <div className="rounded-2xl border border-[var(--border)] bg-white p-4 shadow-card sm:p-5">
                <h2 className="mb-4 text-sm font-bold text-primary">اطلاعات درگاه آنلاین</h2>
                <div className="grid gap-4 sm:grid-cols-2">
                  <Field label="نوع درگاه">
                    <Select value={gatewayId} onChange={(e) => setGatewayId(e.target.value)}>
                      <option value="mock">Mock (تست)</option>
                      <option value="holding_payment">میکروسرویس پرداخت هلدینگ</option>
                    </Select>
                  </Field>
                  <Field label="کد ترمینال (Terminal)">
                    <Input
                      value={merchantId}
                      onChange={(e) => setMerchantId(e.target.value)}
                      placeholder="مثلاً shahr-main"
                    />
                  </Field>
                  <Field label="آدرس API پرداخت">
                    <Input
                      value={paymentApiUrl}
                      onChange={(e) => setPaymentApiUrl(e.target.value)}
                      placeholder="https://payment.hcei.ir"
                      dir="ltr"
                    />
                  </Field>
                  <Field label="API Key">
                    <Input
                      value={paymentApiKey}
                      onChange={(e) => setPaymentApiKey(e.target.value)}
                      placeholder="X-API-Key"
                      dir="ltr"
                    />
                  </Field>
                  <Field label="API Secret">
                    <Input
                      type="password"
                      value={paymentApiSecret}
                      onChange={(e) => setPaymentApiSecret(e.target.value)}
                      placeholder="X-API-Secret"
                      dir="ltr"
                    />
                  </Field>
                </div>
              </div>
            ) : null}

            {payCardToCard ? (
              <div className="rounded-2xl border border-[var(--border)] bg-white p-4 shadow-card sm:p-5">
                <h2 className="mb-1 text-sm font-bold text-primary">اطلاعات حساب کارت‌به‌کارت</h2>
                <p className="mb-4 text-xs leading-6 text-[var(--muted)]">
                  این اطلاعات در پورتال به اولیا نشان داده می‌شود.
                </p>
                <div className="grid gap-4 sm:grid-cols-2">
                  <Field label="نام بانک">
                    <Input
                      value={cardBank}
                      onChange={(e) => setCardBank(e.target.value)}
                      placeholder="مثلاً ملت"
                    />
                  </Field>
                  <Field label="صاحب حساب">
                    <Input
                      value={cardHolder}
                      onChange={(e) => setCardHolder(e.target.value)}
                      placeholder="نام صاحب کارت / حساب"
                    />
                  </Field>
                  <Field label="شماره کارت">
                    <Input
                      value={cardNumber}
                      onChange={(e) => setCardNumber(e.target.value)}
                      placeholder="6037-...."
                      dir="ltr"
                    />
                  </Field>
                  <Field label="شماره شبا" hint="با IR شروع می‌شود">
                    <Input
                      value={cardIban}
                      onChange={(e) => setCardIban(e.target.value)}
                      placeholder="IR000000000000000000000000"
                      dir="ltr"
                    />
                  </Field>
                </div>
              </div>
            ) : null}

            <Button loading={saving} onClick={() => void save()}>
              ذخیره تنظیمات پرداخت
            </Button>
          </>
        )}
      </div>
    </AppShell>
  );
}
