"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Copy, Check } from "lucide-react";
import { TopBar } from "@/components/ui/TopBar";
import { Button } from "@/components/ui/Button";
import { Skeleton } from "@/components/ui/Skeleton";
import { fetchActivePaymentMethods } from "@/lib/data/payment-methods";
import { PaymentAccount } from "@/lib/types";
import { useOrderStore } from "@/lib/order-store";
import { useTranslation } from "@/lib/i18n/LanguageProvider";
import { useSettings } from "@/lib/data/settings-provider";
import { cn } from "@/lib/cn";

export default function PaymentMethodsPage() {
  const router = useRouter();
  const { t } = useTranslation();
  const { settings } = useSettings();
  const { draft, hydrated, setDraft } = useOrderStore();
  const [accounts, setAccounts] = useState<PaymentAccount[]>([]);
  const [loading, setLoading] = useState(true);
  const [selected, setSelected] = useState<PaymentAccount | null>(draft.paymentMethod);
  const [copiedId, setCopiedId] = useState<string | null>(null);

  // draft.paymentMethod at first render is whatever was there before
  // hydration finished loading (usually null) — `selected`'s initial
  // value above won't pick up a persisted selection that loads in
  // after mount, so sync it explicitly once hydration completes.
  useEffect(() => {
    if (hydrated && draft.paymentMethod && !selected) {
      setSelected(draft.paymentMethod);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [hydrated, draft.paymentMethod]);

  useEffect(() => {
    // Wait for hydration before deciding there's no package selected —
    // draft.pkg is only reliably "genuinely empty" once the persisted
    // draft (if any) has finished loading; checking before that would
    // bounce someone with a perfectly good draft back to /packages.
    if (!hydrated) return;
    // No package selected yet (e.g. deep-linked directly) — send them back
    // to pick one instead of letting them reach a broken checkout.
    if (!draft.pkg) {
      router.replace("/packages");
      return;
    }
    let active = true;
    fetchActivePaymentMethods()
      .then((result) => active && setAccounts(result))
      .finally(() => active && setLoading(false));
    return () => {
      active = false;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [hydrated, draft.pkg]);

  async function copyNumber(id: string, number: string) {
    try {
      await navigator.clipboard.writeText(number.replace(/\s/g, ""));
      setCopiedId(id);
      setTimeout(() => setCopiedId((c) => (c === id ? null : c)), 1500);
    } catch {
      // clipboard not available — ignore silently
    }
  }

  function handleContinue() {
    if (!selected) return;
    setDraft({ paymentMethod: selected });
    router.push("/upload-screenshot");
  }

  return (
    <div className="flex flex-1 flex-col">
      <TopBar title={t("paymentMethods.title")} />

      <div className="flex flex-1 flex-col gap-4 px-4 pb-6 pt-2">
        <p className="text-sm text-muted">
          {settings.paymentInstructions}
        </p>

        {loading ? (
          <div className="flex flex-col gap-3">
            <Skeleton className="h-28 w-full !rounded-4xl" />
            <Skeleton className="h-28 w-full !rounded-4xl" />
            <Skeleton className="h-28 w-full !rounded-4xl" />
          </div>
        ) : (
          <div className="flex flex-col gap-3">
            {accounts.map((acc) => {
              const isSelected = selected?.dbId === acc.dbId;
              return (
                <button
                  key={acc.dbId}
                  type="button"
                  onClick={() => setSelected(acc)}
                  className={cn(
                    "flex flex-col gap-3 rounded-4xl glass px-4 py-4 text-left transition-all",
                    isSelected && "ring-2 ring-gold shadow-glow-gold"
                  )}
                >
                  <div className="flex items-center gap-3">
                    <span className={cn("h-3 w-3 shrink-0 rounded-full", acc.colorClass)} />
                    <span className="flex-1 text-sm font-semibold">{acc.label}</span>
                    <span
                      className={cn(
                        "flex h-5 w-5 items-center justify-center rounded-full border-2",
                        isSelected
                          ? "border-gold bg-gold"
                          : "border-black/15 dark:border-white/20"
                      )}
                    >
                      {isSelected && <Check size={12} strokeWidth={3} className="text-ink" />}
                    </span>
                  </div>
                  <div className="flex items-center justify-between rounded-2xl bg-black/5 px-3.5 py-3 dark:bg-white/5">
                    <div>
                      <p className="text-[11px] text-muted">{acc.accountTitle}</p>
                      <p className="tnum font-mono text-sm font-semibold">
                        {acc.accountNumber}
                      </p>
                    </div>
                    <span
                      role="button"
                      onClick={(e) => {
                        e.stopPropagation();
                        copyNumber(acc.dbId, acc.accountNumber);
                      }}
                      className="flex h-8 w-8 items-center justify-center rounded-full bg-black/5 dark:bg-white/10"
                    >
                      {copiedId === acc.dbId ? (
                        <Check size={14} className="text-teal" />
                      ) : (
                        <Copy size={14} className="text-muted" />
                      )}
                    </span>
                  </div>
                </button>
              );
            })}
          </div>
        )}

        <div className="mt-auto">
          <Button size="lg" fullWidth disabled={!selected} onClick={handleContinue}>
            {t("paymentMethods.sentPayment")}
          </Button>
        </div>
      </div>
    </div>
  );
}
