"use client";

import { Button } from "@heroui/react";
import { CheckCircle2, CreditCard, Crown, Wallet } from "lucide-react";
import { BaseModal } from "@/components/modal";
import RiyalIcon from "@/components/ui/RiyalIcon";
import PaddleElectronicPaymentInfo from "@/components/paddles/PaddleElectronicPaymentInfo";

interface ConfirmActionModalProps {
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  title: string;
  description: string;
  cancelLabel: string;
  confirmLabel: string;
  confirmColor: "warning" | "danger";
  isLoading: boolean;
  onConfirm: () => void;
  onCancel: () => void;
}

export function ConfirmActionModal({
  isOpen,
  onOpenChange,
  title,
  description,
  cancelLabel,
  confirmLabel,
  confirmColor,
  isLoading,
  onConfirm,
  onCancel,
}: ConfirmActionModalProps) {
  return (
    <BaseModal
      isOpen={isOpen}
      onOpenChange={onOpenChange}
      placement="center"
      contentClassName="w-full max-w-md rounded-2xl p-6"
      title={title}
    >
      <div className="space-y-4">
        <p className="text-sm text-slate-600">{description}</p>
        <div className="flex justify-end gap-3">
          <Button variant="flat" onPress={onCancel}>
            {cancelLabel}
          </Button>
          <Button color={confirmColor} isLoading={isLoading} onPress={onConfirm}>
            {confirmLabel}
          </Button>
        </div>
      </div>
    </BaseModal>
  );
}

interface OfferModalProps {
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  isRtl: boolean;
  title: string;
  description: string;
  offerDeadlineLabel: string | null;
  offerAmountLabel: string;
  offerAmountPlaceholder: string;
  offerAmount: string;
  onOfferAmountChange: (value: string) => void;
  minOfferPrice: number;
  cancelLabel: string;
  confirmLabel: string;
  sendingOffer: boolean;
  onCancel: () => void;
  onConfirm: () => void;
}

export function OfferModal({
  isOpen,
  onOpenChange,
  isRtl,
  title,
  description,
  offerDeadlineLabel,
  offerAmountLabel,
  offerAmountPlaceholder,
  offerAmount,
  onOfferAmountChange,
  minOfferPrice,
  cancelLabel,
  confirmLabel,
  sendingOffer,
  onCancel,
  onConfirm,
}: OfferModalProps) {
  const parsedOfferAmount = Number(offerAmount || 0);
  const hasAmountError =
    offerAmount.trim().length > 0 &&
    (Number.isNaN(parsedOfferAmount) || parsedOfferAmount <= minOfferPrice);
  const isConfirmDisabled = sendingOffer || !offerAmount.trim() || hasAmountError;

  return (
    <BaseModal
      isOpen={isOpen}
      onOpenChange={onOpenChange}
      placement="center"
      contentClassName="w-full max-w-lg overflow-hidden rounded-[30px] border border-[#dbe7df] p-0 shadow-[0_32px_70px_-40px_rgba(15,81,50,0.45)]"
      headerClassName="border-b border-[#e6eee9] bg-[linear-gradient(180deg,#f7fbf8_0%,#ffffff_100%)] px-6 py-5"
      bodyClassName="px-6 py-6"
      title={title}
    >
      <div className="space-y-5" dir={isRtl ? "rtl" : "ltr"}>
        {/* <div className="rounded-2xl border border-[#d8e7dd] bg-[linear-gradient(180deg,#f8fcf9_0%,#ffffff_100%)] p-4 shadow-[inset_0_1px_0_rgba(255,255,255,0.85)]">
          <p className="whitespace-pre-line text-sm leading-7 text-slate-700">
            {description}
          </p>
        </div> */}

        <div className="grid gap-3 sm:grid-cols-2">
          {offerDeadlineLabel ? (
            <div className="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3">
              <div className="text-[11px] font-bold uppercase tracking-[0.14em] text-slate-400">
                {isRtl ? "آخر موعد" : "Deadline"}
              </div>
              <div className="mt-1 text-sm font-semibold text-slate-700">
                {offerDeadlineLabel}
              </div>
            </div>
          ) : null}

          
        </div>

        <div className="space-y-2">
          <label className="text-sm font-semibold text-slate-700">
            {offerAmountLabel}
          </label>
          <div
            className={`flex items-center gap-3 rounded-2xl border px-4 py-3 transition ${
              hasAmountError
                ? "border-red-300 bg-red-50/70"
                : "border-[#d8e7dd] bg-white focus-within:border-[#0F5132] focus-within:ring-2 focus-within:ring-[#0F5132]/15"
            }`}
          >
            <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-[#0F5132]/10 text-[#0F5132]">
              <RiyalIcon className="h-4 w-5" />
            </div>
            <input
              type="number"
              min="0"
              step="1"
              value={offerAmount}
              onChange={(event) => onOfferAmountChange(event.target.value)}
              placeholder={offerAmountPlaceholder}
              className="w-full bg-transparent text-base font-bold text-slate-900 placeholder:text-slate-400 focus:outline-none"
            />
          </div>
          {minOfferPrice > 0 ? (
            <p
              className={`text-xs ${
                hasAmountError ? "text-red-600" : "text-slate-500"
              }`}
            >
              {isRtl
                ? `يجب أن يكون العرض أكبر من ${minOfferPrice.toLocaleString()}`
                : `Offer must be greater than ${minOfferPrice.toLocaleString()}`}
              <span className="mx-1 inline-flex align-middle">
                <RiyalIcon className="h-3.5 w-3.5" />
              </span>
            </p>
          ) : null}
        </div>

        <div className="flex justify-end gap-3 pt-1">
          <Button
            variant="flat"
            onPress={onCancel}
            className="rounded-xl border border-[#d8e7dd] bg-white px-5 text-[#0F5132]"
          >
            {cancelLabel}
          </Button>
          <Button
            color="primary"
            isLoading={sendingOffer}
            isDisabled={isConfirmDisabled}
            onPress={onConfirm}
            className="rounded-xl bg-[linear-gradient(135deg,#0F5132_0%,#1B7A50_100%)] px-5 text-white shadow-[0_20px_36px_-24px_rgba(15,81,50,0.55)]"
          >
            {confirmLabel}
          </Button>
        </div>
      </div>
    </BaseModal>
  );
}

interface PaddlePurchaseModalProps {
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  isRtl: boolean;
  title: string;
  description: string;
  selectedPaddleRoomName: string;
  selectedPaddleRoomNumber: string;
  selectedPaymentMethodLabel: string;
  normalPaddlePrice: number;
  premiumPaddlePrice: number;
  walletBalance: number;
  paddlePaymentMethod: "wallet" | "gateway" | "apple_pay";
  setPaddlePaymentMethod: (value: "wallet" | "gateway" | "apple_pay") => void;
  showApplePay: boolean;
  paddleType: "normal" | "premium";
  setPaddleType: (value: "normal" | "premium") => void;
  canAffordNormalPaddle: boolean;
  canAffordPremiumPaddle: boolean;
  buyingPaddle: boolean;
  canBuyPremiumInLive: boolean;
  normalWalletStatusMessage: string;
  premiumWalletStatusMessage: string;
  hasWalletShortfall: boolean;
  normalShortfall: number;
  premiumShortfall: number;
  formatAmount: (value: number) => string;
  onOpenTopUp?: () => void;
  onPurchasePaddle: (type: "normal" | "premium") => void;
}

export function PaddlePurchaseModal({
  isOpen,
  onOpenChange,
  isRtl,
  title,
  description,
  selectedPaddleRoomName,
  selectedPaddleRoomNumber,
  selectedPaymentMethodLabel,
  normalPaddlePrice,
  premiumPaddlePrice,
  walletBalance,
  paddlePaymentMethod,
  setPaddlePaymentMethod,
  showApplePay,
  paddleType,
  setPaddleType,
  canAffordNormalPaddle,
  canAffordPremiumPaddle,
  buyingPaddle,
  canBuyPremiumInLive,
  normalWalletStatusMessage,
  premiumWalletStatusMessage,
  hasWalletShortfall,
  normalShortfall,
  premiumShortfall,
  formatAmount,
  onOpenTopUp,
  onPurchasePaddle,
}: PaddlePurchaseModalProps) {
  return (
    <BaseModal
      isOpen={isOpen}
      onOpenChange={onOpenChange}
      placement="center"
      dis={description}
      contentClassName="w-full max-w-3xl overflow-hidden rounded-xl p-0"
      bodyClassName="p-0"
      title={title}
    >
      <div className="space-y-6 p-6 text-sm text-slate-700">
        <div className="grid gap-3 md:grid-cols-3">
          <div className="rounded-xl border border-slate-200 bg-slate-50 px-4 py-3">
            <div className="text-xs text-slate-500">
              {isRtl ? "الغرفة المختارة" : "Selected room"}
            </div>
            <div className="mt-1 truncate font-bold text-slate-900">
              {selectedPaddleRoomName}
            </div>
            <div className="mt-1 text-xs text-slate-500">
              {isRtl
                ? `رقم الغرفة: ${selectedPaddleRoomNumber}`
                : `Room #: ${selectedPaddleRoomNumber}`}
            </div>
          </div>

          <div className="rounded-xl border border-slate-200 bg-slate-50 px-4 py-3">
            <div className="text-xs text-slate-500">
              {isRtl ? "رصيد المحفظة" : "Wallet balance"}
            </div>
            <div className="mt-1 font-bold text-slate-900">
              {formatAmount(walletBalance)}
            </div>
          </div>

          <div className="rounded-xl border border-slate-200 bg-slate-50 px-4 py-3">
            <div className="text-xs text-slate-500">
              {isRtl ? "طريقة الدفع المحددة" : "Selected payment"}
            </div>
            <div className="mt-1 font-bold text-slate-900">
              {selectedPaymentMethodLabel}
            </div>
          </div>
        </div>

        <div className="space-y-3">
          <div className="flex items-center justify-between gap-2">
            <div className="text-sm font-bold text-slate-800 min-w-0 flex-1">
              {isRtl ? "طريقة الدفع" : "Payment Method"}
            </div>
            <PaddleElectronicPaymentInfo paymentMethod={paddlePaymentMethod} />
          </div>

          <div className="grid gap-3 sm:grid-cols-2">
            <label
              className={`cursor-pointer rounded-xl border p-4 transition ${
                paddlePaymentMethod === "gateway"
                  ? "border-blue-500 bg-blue-50"
                  : "border-slate-200 bg-white hover:border-blue-300"
              }`}
            >
              <input
                type="radio"
                name="live_paddle_payment_method"
                checked={paddlePaymentMethod === "gateway"}
                onChange={() => setPaddlePaymentMethod("gateway")}
                className="sr-only"
              />
              <div className="flex items-center gap-3">
                <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-blue-600/10 text-blue-700">
                  <CreditCard className="h-5 w-5" />
                </div>
                <div>
                  <div className="font-semibold text-slate-900">
                    {isRtl ? "دفع إلكتروني" : "Online Payment"}
                  </div>
                  <div className="text-xs text-slate-500">
                    Visa, Mastercard, mada
                  </div>
                </div>
                {paddlePaymentMethod === "gateway" ? (
                  <CheckCircle2 className="ms-auto h-4 w-4 text-blue-600" />
                ) : null}
              </div>
            </label>

            {showApplePay && (
              <label
                className={`cursor-pointer rounded-xl border p-4 transition ${
                  paddlePaymentMethod === "apple_pay"
                    ? "border-slate-900 bg-slate-50"
                    : "border-slate-200 bg-white hover:border-slate-400"
                }`}
              >
                <input
                  type="radio"
                  name="live_paddle_payment_method"
                  checked={paddlePaymentMethod === "apple_pay"}
                  onChange={() => setPaddlePaymentMethod("apple_pay")}
                  className="sr-only"
                />
                <div className="flex items-center gap-3">
                  <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-slate-900">
                    <svg viewBox="0 0 24 24" className="w-5 h-5 fill-white" aria-hidden="true">
                      <path d="M17.05 20.28c-.98.95-2.05.8-3.08.35-1.09-.46-2.09-.48-3.24 0-1.44.62-2.2.44-3.06-.35C2.79 15.25 3.51 7.7 9.05 7.4c1.28.07 2.16.72 2.98.73 1.16-.1 2.26-.79 3.47-.68 1.45.13 2.54.79 3.25 2.02-3.13 1.87-2.39 5.88.3 6.97-.5 1.32-1.29 2.59-2 3.84zM12.03 7.25c-.15-2.23 1.66-4.07 3.74-4.25.29 2.58-2.34 4.5-3.74 4.25z"/>
                    </svg>
                  </div>
                  <div>
                    <div className="font-semibold text-slate-900">
                      Apple Pay
                    </div>
                    <div className="text-xs text-slate-500">
                      {isRtl ? "الدفع عبر Apple Pay" : "Pay with Apple Pay"}
                    </div>
                  </div>
                  {paddlePaymentMethod === "apple_pay" ? (
                    <CheckCircle2 className="ms-auto h-4 w-4 text-slate-700" />
                  ) : null}
                </div>
              </label>
            )}

            <label
              className={`cursor-pointer rounded-xl border p-4 transition ${
                paddlePaymentMethod === "wallet"
                  ? "border-emerald-500 bg-emerald-50"
                  : "border-slate-200 bg-white hover:border-emerald-300"
              }`}
            >
              <input
                type="radio"
                name="live_paddle_payment_method"
                checked={paddlePaymentMethod === "wallet"}
                onChange={() => setPaddlePaymentMethod("wallet")}
                className="sr-only"
              />
              <div className="flex items-center gap-3">
                <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-emerald-600/10 text-emerald-700">
                  <Wallet className="h-5 w-5" />
                </div>
                <div>
                  <div className="font-semibold text-slate-900">
                    {isRtl ? "المحفظة" : "Wallet"}
                  </div>
                  <div className="text-xs text-slate-500">
                    {isRtl
                      ? "الدفع من الرصيد المتاح"
                      : "Pay from available balance"}
                  </div>
                </div>
                {paddlePaymentMethod === "wallet" ? (
                  <CheckCircle2 className="ms-auto h-4 w-4 text-emerald-600" />
                ) : null}
              </div>
            </label>
          </div>
        </div>

        <div className="space-y-3">
          <div className="text-sm font-bold text-slate-800">
            {isRtl ? "اختر نوع المضرب" : "Choose Paddle Type"}
          </div>

          <div className="grid gap-4 md:grid-cols-2">
            <div
              onClick={() => setPaddleType("normal")}
              className={`flex cursor-pointer flex-col rounded-2xl border bg-white p-5 transition ${
                paddleType === "normal"
                  ? "border-[#0F5132] ring-2 ring-[#0F5132]/10"
                  : "border-slate-200 hover:border-[#0F5132]"
              }`}
            >
              <div className="flex items-start justify-between">
                <div>
                  <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">
                    {isRtl ? "الخيار القياسي" : "Standard Option"}
                  </div>
                  <h4 className="mt-1 text-base font-bold text-slate-900">
                    {isRtl ? "مضرب عادي" : "Normal Paddle"}
                  </h4>
                </div>
                <div className="rounded-full bg-slate-100 px-2.5 py-1 text-xs font-bold text-slate-700">
                  {isRtl ? "عادي" : "Normal"}
                </div>
              </div>

              <div className="mt-4 rounded-xl border border-slate-200 bg-slate-50 px-3 py-2">
                <div className="text-xs text-slate-500">
                  {isRtl ? "السعر" : "Price"}
                </div>
                <div className="text-2xl font-black text-[#0F5132]">
                  {formatAmount(normalPaddlePrice)}
                </div>
              </div>

              <ul className="mt-4 space-y-2 text-xs text-slate-600">
                <li className="flex items-center gap-2">
                  <CheckCircle2 className="h-4 w-4 text-emerald-600" />
                  <span>
                    {isRtl
                      ? "استخدام واحد لمزاد واحد"
                      : "Single use for one auction"}
                  </span>
                </li>
                <li className="flex items-center gap-2">
                  <CheckCircle2 className="h-4 w-4 text-emerald-600" />
                  <span>
                    {isRtl
                      ? "مناسب للمشاركة القياسية"
                      : "Suitable for standard participation"}
                  </span>
                </li>
              </ul>

              <div
                className={`mt-3 min-h-[20px] text-xs font-medium transition-opacity ${
                  canAffordNormalPaddle ? "text-emerald-700" : "text-amber-700"
                } ${
                  paddlePaymentMethod === "wallet"
                    ? "opacity-100"
                    : "pointer-events-none select-none opacity-0"
                }`}
              >
                {normalWalletStatusMessage}
              </div>

              <div className="mt-auto pt-4">
                <Button
                  onPress={() => onPurchasePaddle("normal")}
                  isDisabled={
                    buyingPaddle ||
                    (paddlePaymentMethod === "wallet" && !canAffordNormalPaddle)
                  }
                  className="w-full rounded-xl bg-[#0F5132] px-4 py-3 font-bold text-white transition-all hover:bg-[#0F5132]/90 disabled:cursor-not-allowed disabled:opacity-60"
                >
                  {buyingPaddle && paddleType === "normal"
                    ? isRtl
                      ? "جاري المعالجة..."
                      : "Processing..."
                    : isRtl
                      ? "شراء مضرب عادي"
                      : "Buy Normal Paddle"}
                </Button>
              </div>
            </div>

            {canBuyPremiumInLive ? (
              <div
                onClick={() => setPaddleType("premium")}
                className={`flex cursor-pointer flex-col rounded-2xl border border-emerald-200 bg-gradient-to-b from-emerald-50 to-white p-5 transition ${
                  paddleType === "premium"
                    ? "border-[#0F5132] ring-2 ring-[#0F5132]/10"
                    : "hover:border-emerald-400"
                }`}
              >
                <div className="flex items-start justify-between">
                  <div>
                    <div className="text-xs font-semibold uppercase tracking-wide text-emerald-700">
                      {isRtl ? "الخيار المتقدم" : "Advanced Option"}
                    </div>
                    <h4 className="mt-1 text-base font-bold text-slate-900">
                      {isRtl ? "مضرب بريميوم" : "Premium Paddle"}
                    </h4>
                  </div>
                  <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-emerald-100 text-emerald-700">
                    <Crown className="h-5 w-5" />
                  </div>
                </div>

                <div className="mt-4 rounded-xl border border-emerald-200 bg-white px-3 py-2">
                  <div className="text-xs text-slate-500">
                    {isRtl ? "السعر" : "Price"}
                  </div>
                  <div className="text-2xl font-black text-[#0F5132]">
                    {formatAmount(premiumPaddlePrice)}
                  </div>
                </div>

                <ul className="mt-4 space-y-2 text-xs text-slate-700">
                  <li className="flex items-center gap-2">
                    <CheckCircle2 className="h-4 w-4 text-emerald-600" />
                    <span>
                      {isRtl
                        ? "صالح لمزادات متعددة"
                        : "Valid for multiple auctions"}
                    </span>
                  </li>
                  <li className="flex items-center gap-2">
                    <CheckCircle2 className="h-4 w-4 text-emerald-600" />
                    <span>
                      {isRtl
                        ? "أولوية في المشاركة حسب شروط المزاد"
                        : "Priority access based on auction policy"}
                    </span>
                  </li>
                </ul>

                <div
                  className={`mt-3 min-h-[20px] text-xs font-medium transition-opacity ${
                    canAffordPremiumPaddle ? "text-emerald-700" : "text-amber-700"
                  } ${
                    paddlePaymentMethod === "wallet"
                      ? "opacity-100"
                      : "pointer-events-none select-none opacity-0"
                  }`}
                >
                  {premiumWalletStatusMessage}
                </div>

                <div className="mt-auto pt-4">
                  <Button
                    onPress={() => onPurchasePaddle("premium")}
                    isDisabled={
                      buyingPaddle ||
                      (paddlePaymentMethod === "wallet" && !canAffordPremiumPaddle)
                    }
                    className="w-full rounded-xl bg-gradient-to-r from-emerald-600 to-teal-600 px-4 py-3 font-bold text-white transition-all hover:from-emerald-700 hover:to-teal-700 disabled:cursor-not-allowed disabled:opacity-60"
                  >
                    {buyingPaddle && paddleType === "premium"
                      ? isRtl
                        ? "جاري المعالجة..."
                        : "Processing..."
                      : isRtl
                        ? "شراء مضرب بريميوم"
                        : "Buy Premium Paddle"}
                  </Button>
                </div>
              </div>
            ) : null}
            {hasWalletShortfall ? (
              <div className="space-y-2 rounded-xl border h-fit border-amber-200 bg-amber-50 px-4 py-3">
                <div className="text-xs font-semibold text-amber-800">
                  {isRtl
                    ? "رصيد المحفظة غير كافٍ"
                    : "Insufficient wallet balance"}
                </div>
                {normalShortfall > 0 ? (
                  <div className="text-xs text-amber-800">
                    {isRtl
                      ? `المضرب العادي يحتاج: ${formatAmount(normalShortfall)}`
                      : `Normal paddle needs: ${formatAmount(normalShortfall)}`}
                  </div>
                ) : null}
                {canBuyPremiumInLive && premiumShortfall > 0 ? (
                  <div className="text-xs text-amber-800">
                    {isRtl
                      ? `المضرب البريميوم يحتاج: ${formatAmount(premiumShortfall)}`
                      : `Premium paddle needs: ${formatAmount(premiumShortfall)}`}
                  </div>
                ) : null}
                <div className="text-xs text-amber-700">
                  {isRtl
                    ? "يمكنك اختيار الدفع الإلكتروني مباشرة."
                    : "You can continue with online payment."}
                </div>
                {onOpenTopUp ? (
                  <button
                    type="button"
                    onClick={onOpenTopUp}
                    className="mt-2 w-full sm:w-auto px-4 py-2 rounded-lg bg-emerald-600 text-white text-xs font-bold hover:bg-emerald-700 transition-colors"
                  >
                    {isRtl ? "شحن المحفظة" : "Top up wallet"}
                  </button>
                ) : null}
              </div>
            ) : null}
          </div>
        </div>
      </div>
    </BaseModal>
  );
}
