"use client";

import { useState, useTransition } from "react";
import Link from "next/link";
import { ArrowLeft, CreditCard, Loader2, Lock, ShieldCheck, X } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { cn } from "@/lib/utils";
import {
  cancelMockPaymentAction,
  confirmMockPaymentAction,
} from "@/lib/appwrite/subscription-actions";
import type { CardBrand, SavedCard } from "@/lib/appwrite/schema";

import { CreditCardVisual } from "./credit-card-visual";

const trFmt = new Intl.NumberFormat("tr-TR", {
  style: "currency",
  currency: "TRY",
  maximumFractionDigits: 0,
});

const BRAND_LABEL: Record<CardBrand, string> = {
  visa: "Visa",
  mastercard: "Mastercard",
  amex: "Amex",
  troy: "troy",
  unknown: "Kart",
};

function formatNumber(v: string): string {
  return v
    .replace(/\D/g, "")
    .slice(0, 16)
    .replace(/(.{4})/g, "$1 ")
    .trim();
}

function formatExpiry(v: string): string {
  const digits = v.replace(/\D/g, "").slice(0, 4);
  if (digits.length < 3) return digits;
  return `${digits.slice(0, 2)}/${digits.slice(2)}`;
}

function formatCvc(v: string): string {
  return v.replace(/\D/g, "").slice(0, 4);
}

function detectBrand(num: string): CardBrand {
  const n = num.replace(/\s/g, "");
  if (/^4/.test(n)) return "visa";
  if (/^(5[1-5]|2[2-7])/.test(n)) return "mastercard";
  if (/^3[47]/.test(n)) return "amex";
  if (/^(9792|65)/.test(n)) return "troy";
  return "unknown";
}

type Props = {
  orderId: string;
  amount: number;
  planName: string;
  planPeriod: string;
  savedCards: SavedCard[];
};

export function MockPaymentForm({
  orderId,
  amount,
  planName,
  planPeriod,
  savedCards,
}: Props) {
  const defaultSaved = savedCards.find((c) => c.isDefault) ?? savedCards[0] ?? null;
  const [mode, setMode] = useState<"saved" | "new">(defaultSaved ? "saved" : "new");
  const [selectedCardId, setSelectedCardId] = useState<string>(defaultSaved?.$id ?? "");

  const [number, setNumber] = useState("");
  const [name, setName] = useState("");
  const [expiry, setExpiry] = useState("");
  const [cvc, setCvc] = useState("");
  const [flipped, setFlipped] = useState(false);
  const [saveCard, setSaveCard] = useState(true);

  const [confirming, startConfirm] = useTransition();
  const [cancelling, startCancel] = useTransition();

  const numberDigits = number.replace(/\s/g, "");
  const expiryDigits = expiry.replace(/\D/g, "");

  const newCardFilled =
    numberDigits.length === 16 &&
    name.trim().length >= 3 &&
    expiryDigits.length === 4 &&
    cvc.length >= 3;

  const filled = mode === "saved" ? Boolean(selectedCardId) : newCardFilled;

  const handleConfirm = () => {
    const fd = new FormData();
    fd.set("orderId", orderId);

    if (mode === "saved" && selectedCardId) {
      fd.set("savedCardId", selectedCardId);
    } else {
      const month = expiryDigits.slice(0, 2);
      const year = expiryDigits.slice(2, 4);
      fd.set("cardLast4", numberDigits.slice(-4));
      fd.set("cardExpiryMonth", month);
      fd.set("cardExpiryYear", `20${year}`);
      fd.set("cardBrand", detectBrand(numberDigits));
      fd.set("cardHolder", name.trim());
      fd.set("saveCard", saveCard ? "true" : "false");
    }

    startConfirm(() => confirmMockPaymentAction(fd));
  };

  const handleCancel = () => {
    const fd = new FormData();
    fd.set("orderId", orderId);
    startCancel(() => cancelMockPaymentAction(fd));
  };

  const busy = confirming || cancelling;

  // Visual sync — saved card preview when in saved mode
  const selected = savedCards.find((c) => c.$id === selectedCardId);
  const visualNumber =
    mode === "saved" && selected
      ? `${"•".repeat(12)} ${selected.last4}`
      : number;
  const visualName =
    mode === "saved" && selected ? selected.holderName ?? "" : name;
  const visualExpiry =
    mode === "saved" && selected
      ? `${String(selected.expiryMonth).padStart(2, "0")}/${String(selected.expiryYear).slice(2)}`
      : expiry;
  const visualCvc = mode === "saved" ? "" : cvc;

  return (
    <div className="grid gap-6 lg:grid-cols-[minmax(0,420px)_1fr]">
      <div className="space-y-4">
        <CreditCardVisual
          number={visualNumber}
          name={visualName}
          expiry={visualExpiry}
          cvc={visualCvc}
          flipped={flipped}
        />

        <div className="bg-emerald-500/5 flex items-start gap-2 rounded-md border p-3 text-xs">
          <ShieldCheck className="size-4 text-emerald-600 shrink-0" />
          <span className="text-muted-foreground">
            Test modu — gerçek kart bilgisi gerekmez. Onayladığında plan{" "}
            <span className="text-foreground font-medium">{planPeriod}</span> boyunca aktif
            olur, tahsilat yapılmaz.
          </span>
        </div>
      </div>

      <div className="space-y-5">
        <div className="space-y-1">
          <div className="text-muted-foreground text-xs uppercase tracking-wider">
            Ödenecek tutar
          </div>
          <div className="flex items-baseline gap-2">
            <span className="text-3xl font-bold">{trFmt.format(amount)}</span>
            <span className="text-muted-foreground text-sm">{planName}</span>
          </div>
        </div>

        {savedCards.length > 0 && (
          <div className="grid grid-cols-2 gap-2 rounded-md border p-1">
            <button
              type="button"
              className={cn(
                "rounded px-3 py-2 text-sm font-medium transition-colors",
                mode === "saved"
                  ? "bg-primary text-primary-foreground"
                  : "text-muted-foreground hover:bg-muted",
              )}
              onClick={() => setMode("saved")}
              disabled={busy}
            >
              Kayıtlı kart
            </button>
            <button
              type="button"
              className={cn(
                "rounded px-3 py-2 text-sm font-medium transition-colors",
                mode === "new"
                  ? "bg-primary text-primary-foreground"
                  : "text-muted-foreground hover:bg-muted",
              )}
              onClick={() => setMode("new")}
              disabled={busy}
            >
              Yeni kart
            </button>
          </div>
        )}

        {mode === "saved" && savedCards.length > 0 ? (
          <div className="space-y-2">
            {savedCards.map((c) => (
              <label
                key={c.$id}
                className={cn(
                  "flex cursor-pointer items-center gap-3 rounded-md border p-3 transition-colors",
                  selectedCardId === c.$id
                    ? "border-primary bg-primary/5"
                    : "hover:bg-muted/50",
                )}
              >
                <input
                  type="radio"
                  name="savedCard"
                  className="size-4"
                  checked={selectedCardId === c.$id}
                  onChange={() => setSelectedCardId(c.$id)}
                  disabled={busy}
                />
                <CreditCard className="text-muted-foreground size-5 shrink-0" />
                <div className="flex-1 text-sm">
                  <div className="font-medium">
                    {BRAND_LABEL[c.brand ?? "unknown"]} •••• {c.last4}
                  </div>
                  <div className="text-muted-foreground text-xs">
                    {c.holderName ?? "İsimsiz"} · Son kullanma{" "}
                    {String(c.expiryMonth).padStart(2, "0")}/{String(c.expiryYear).slice(2)}
                  </div>
                </div>
                {c.isDefault && (
                  <span className="text-muted-foreground text-[10px] uppercase tracking-wider">
                    Varsayılan
                  </span>
                )}
              </label>
            ))}
          </div>
        ) : (
          <div className="grid gap-4">
            <div className="grid gap-2">
              <Label htmlFor="cc-number">Kart numarası</Label>
              <Input
                id="cc-number"
                inputMode="numeric"
                autoComplete="cc-number"
                placeholder="1234 5678 9012 3456"
                value={number}
                onFocus={() => setFlipped(false)}
                onChange={(e) => setNumber(formatNumber(e.target.value))}
                className="font-mono tracking-wider"
                disabled={busy}
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="cc-name">Kart üzerindeki ad</Label>
              <Input
                id="cc-name"
                autoComplete="cc-name"
                placeholder="AD SOYAD"
                value={name}
                onFocus={() => setFlipped(false)}
                onChange={(e) => setName(e.target.value.toUpperCase())}
                className="uppercase"
                disabled={busy}
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="grid gap-2">
                <Label htmlFor="cc-expiry">Son kullanma</Label>
                <Input
                  id="cc-expiry"
                  inputMode="numeric"
                  autoComplete="cc-exp"
                  placeholder="AA/YY"
                  value={expiry}
                  onFocus={() => setFlipped(false)}
                  onChange={(e) => setExpiry(formatExpiry(e.target.value))}
                  className="font-mono"
                  disabled={busy}
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="cc-cvc">CVC</Label>
                <Input
                  id="cc-cvc"
                  inputMode="numeric"
                  autoComplete="cc-csc"
                  placeholder="123"
                  value={cvc}
                  onFocus={() => setFlipped(true)}
                  onBlur={() => setFlipped(false)}
                  onChange={(e) => setCvc(formatCvc(e.target.value))}
                  className="font-mono"
                  disabled={busy}
                />
              </div>
            </div>

            <label className="flex items-start gap-3 rounded-md border bg-muted/30 p-3 text-sm">
              <Checkbox
                id="save-card"
                checked={saveCard}
                onCheckedChange={(v) => setSaveCard(Boolean(v))}
                disabled={busy}
                className="mt-0.5"
              />
              <div className="flex-1">
                <div className="font-medium">Bu kartı kaydet</div>
                <div className="text-muted-foreground mt-0.5 text-xs">
                  Sonraki ödemelerde tek tıkla kullan. Kart numarasının yalnızca son 4 hanesi,
                  markası ve son kullanma tarihi saklanır — ham numara hiçbir yerde tutulmaz.
                </div>
              </div>
            </label>
          </div>
        )}

        <div className="flex flex-col gap-2 pt-2 sm:flex-row">
          <Button
            type="button"
            size="lg"
            className="flex-1"
            onClick={handleConfirm}
            disabled={busy || !filled}
          >
            {confirming ? (
              <>
                <Loader2 className="size-4 animate-spin" />
                Onaylanıyor...
              </>
            ) : (
              <>
                <Lock className="size-4" />
                Güvenli ödeme — {trFmt.format(amount)}
              </>
            )}
          </Button>
          <Button
            type="button"
            size="lg"
            variant="outline"
            onClick={handleCancel}
            disabled={busy}
          >
            {cancelling ? (
              <Loader2 className="size-4 animate-spin" />
            ) : (
              <X className="size-4" />
            )}
            Vazgeç
          </Button>
        </div>

        {!filled && mode === "new" && (
          <p className="text-muted-foreground text-xs">
            Onay butonu etkin olması için tüm kart alanlarını doldurman gerekir. Test modu —
            herhangi bir 16 haneli numara çalışır.
          </p>
        )}

        <Link
          href="/settings/billing"
          className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-xs"
        >
          <ArrowLeft className="size-3" />
          Plan & Faturalandırma'ya dön
        </Link>
      </div>
    </div>
  );
}
