"use client";

import { BaseModal } from "@/components/modal";
import DynamicButton from "@/components/button";
import { useAppToast } from "@/app/[lang]/providers";
import { useTranslations } from "next-intl";
import {
  usePremiumPlan,
  usePurchasePremiumPaddle,
  UserPaddle,
} from "@/lib/clientQueries";
import { useQueryClient } from "@tanstack/react-query";
import Money from "@/components/ui/Money";
import { toMoneyNumber } from "@/lib/moneyParse";

interface PaddlePurchaseModalProps {
  open: boolean;
  onClose: () => void;
  paddles: UserPaddle[];
  walletBalance: number;
  paddlePrice?: string | number;
  isOwner?: boolean;
  isLoading?: boolean;
  auctionId: string;
  auctionType: "normal" | "annual";
  auctionAnimalType?: "horse" | "camel" | null;
  onSelectPaddle: (paddleId: string) => void;
  onBuyNormal: () => void;
}

const formatDate = (dateString: string | null | undefined): string => {
  if (!dateString) return "";
  try {
    const date = new Date(dateString);
    return new Intl.DateTimeFormat("en-EN", {
      year: "numeric",
      month: "long",
      day: "numeric",
    }).format(date);
  } catch {
    return dateString;
  }
};

const getTypeBadge = (type?: string) => {
  switch (type) {
    case "vip":
      return (
        <span className="px-2 py-1 text-xs font-bold rounded-full bg-purple-100 text-purple-700">
          VIP
        </span>
      );
    case "premium":
      return (
        <span className="px-2 py-1 text-xs font-bold rounded-full bg-blue-100 text-blue-700">
          Premium
        </span>
      );
    case "normal":
    default:
      return (
        <span className="px-2 py-1 text-xs font-bold rounded-full bg-gray-100 text-gray-700">
          عادي
        </span>
      );
  }
};

const isPaddleDisabled = (paddle: UserPaddle): boolean => {
  return (
    paddle.is_available === false ||
    paddle.can_use_for_auction === false ||
    paddle.status === "expired" ||
    paddle.status === "consumed"
  );
};

const getDisabledReason = (
  paddle: UserPaddle,
  auctionAnimalType?: "horse" | "camel" | null,
): string => {
  if (paddle.status === "expired") return "منتهي";
  if (paddle.status === "consumed") return "مستهلك";
  if (paddle.is_available === false) return "محجوز";
  if (paddle.can_use_for_auction === false) {
    if (
      paddle.type === "vip" &&
      paddle.allowed_auction_type &&
      auctionAnimalType &&
      paddle.allowed_auction_type !== auctionAnimalType
    ) {
      return paddle.allowed_auction_type === "horse"
        ? "مخصص لمزاد خيل"
        : paddle.allowed_auction_type === "camel"
          ? "مخصص لمزاد إبل"
          : "مخصص لمزاد آخر";
    }
    return "غير متاح لهذا المزاد";
  }
  return "";
};

export default function PaddlePurchaseModal({
  open,
  onClose,
  paddles,
  walletBalance,
  paddlePrice,
  isOwner,
  isLoading,
  auctionId,
  auctionType,
  auctionAnimalType,
  onSelectPaddle,
  onBuyNormal,
}: PaddlePurchaseModalProps) {
  const toast = useAppToast();
  const tToast = useTranslations("TOAST");
  const queryClient = useQueryClient();
  const purchasePremiumPaddle = usePurchasePremiumPaddle();
  const { data: premiumPlan } = usePremiumPlan();
  const required = toMoneyNumber(paddlePrice, 0);
  const canAfford = walletBalance >= required;

  const hasActivePremium = paddles.some(
    (p) =>
      p.type === "premium" && p.status !== "expired" && p.status !== "consumed",
  );

  const handlePremiumPurchase = async () => {
    try {
      await purchasePremiumPaddle.mutateAsync();
      toast.success(tToast("premium_paddle_purchased"));
      queryClient.invalidateQueries({
        queryKey: ["available-paddles", auctionId, auctionType],
      });
      queryClient.invalidateQueries({ queryKey: ["premium-plan"] });
    } catch (error: any) {
      const msg =
        error?.response?.data?.message ||
        error?.message ||
        tToast("premium_paddle_purchase_error");
      toast.error(String(msg));
    }
  };

  return (
    <BaseModal
      isOpen={open}
      onOpenChange={(nextOpen) => {
        if (!nextOpen) onClose();
      }}
      title="شراء مضرب"
      contentClassName="w-[min(92vw,760px)]"
    >
      <div className="space-y-6 text-sm text-slate-700">
        <div className="p-3 rounded-xl bg-slate-50 border">
          <div className="font-semibold">رصيد المحفظة</div>
          <div className="text-slate-600 text-sm mt-1">
            الرصيد المتاح: <Money value={walletBalance} />
          </div>
        </div>

        <div className="space-y-3">
          <h3 className="text-base font-bold text-slate-900">
            استخدم مضرب موجود
          </h3>
          {paddles.length === 0 ? (
            <div className="text-slate-500">
              لا توجد مضارب متاحة لهذا المزاد حالياً.
            </div>
          ) : (
            <div className="space-y-3 max-h-[320px] overflow-y-auto">
              {paddles.map((paddle) => {
                const disabled = isPaddleDisabled(paddle);
                const reason = getDisabledReason(
                  paddle,
                  auctionAnimalType || null,
                );
                return (
                  <div
                    key={paddle.id}
                    className={`p-4 rounded-xl border-2 transition-all ${
                      disabled
                        ? "bg-slate-50 border-slate-200 opacity-60"
                        : "bg-white border-slate-200 hover:border-[#0F5132] hover:shadow-md"
                    }`}
                  >
                    <div className="flex items-start justify-between gap-4">
                      <div className="flex-1 space-y-2">
                        <div className="flex items-center gap-3">
                          <div className="font-bold text-lg text-slate-800">
                            #{paddle.unique_id}
                          </div>
                          {getTypeBadge(paddle.type)}
                          {disabled && reason && (
                            <span className="px-2 py-1 text-xs font-medium rounded-full bg-red-100 text-red-700">
                              {reason}
                            </span>
                          )}
                        </div>

                        <div className="space-y-1 text-sm text-slate-600">
                          {(paddle.type === "premium" ||
                            paddle.type === "vip") &&
                            paddle.remaining_uses != null && (
                              <div className="flex items-center gap-2">
                                <span className="font-medium">
                                  المتبقي من الاستخدام:
                                </span>
                                <span className="font-bold text-[#0F5132]">
                                  {paddle.remaining_uses}
                                </span>
                              </div>
                            )}

                          {paddle.expires_at && (
                            <div className="flex items-center gap-2">
                              <span className="font-medium">ينتهي في:</span>
                              <span>{formatDate(paddle.expires_at)}</span>
                            </div>
                          )}

                          {paddle.type === "vip" &&
                            paddle.allowed_auction_type && (
                              <div className="flex items-center gap-2">
                                <span className="font-medium">
                                  نوع المزاد المسموح:
                                </span>
                                <span>
                                  {paddle.allowed_auction_type === "horse"
                                    ? "خيل"
                                    : paddle.allowed_auction_type === "camel"
                                      ? "إبل"
                                      : paddle.allowed_auction_type}
                                </span>
                              </div>
                            )}
                        </div>
                      </div>

                      <DynamicButton
                        onClick={() => onSelectPaddle(paddle.id)}
                        isDisabled={disabled || isLoading}
                        className="px-4 py-2 rounded-lg bg-[#0F5132] text-white hover:bg-[#0F5132]/90 disabled:opacity-50 disabled:cursor-not-allowed whitespace-nowrap"
                      >
                        استخدام هذا المضرب
                      </DynamicButton>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        <div className="space-y-3">
          <h3 className="text-base font-bold text-slate-900">شراء مضرب عادي</h3>
          <div className="p-4 rounded-xl bg-white border space-y-2">
            <div className="text-slate-600">
              قيمة المضرب:{" "}
              <span className="font-bold text-[#0F5132]">
                <Money value={required} />
              </span>
            </div>
            <DynamicButton
              onClick={onBuyNormal}
              isDisabled={isLoading || !canAfford || isOwner}
              className="px-4 py-2 rounded-lg bg-[#0F5132] text-white hover:bg-[#0F5132]/90 disabled:opacity-60 disabled:cursor-not-allowed"
            >
              تأكيد الشراء ودفع الرسوم
            </DynamicButton>
            {!canAfford && (
              <div className="text-xs text-amber-700">
                الرصيد غير كافٍ لشراء المضرب.
              </div>
            )}
            {isOwner && (
              <div className="text-xs text-amber-700">
                لا يمكنك شراء مضرب لأنك مالك هذا المزاد.
              </div>
            )}
          </div>
        </div>

        <div className="space-y-3">
          <h3 className="text-base font-bold text-slate-900">
            شراء مضرب بريميوم
          </h3>
          <div className="p-4 rounded-xl bg-blue-50 border border-blue-200 space-y-2">
            {hasActivePremium ? (
              <div className="text-slate-600">
                لديك مضرب بريميوم بالفعل. استخدمه من قسم "استخدم مضرب موجود".
              </div>
            ) : premiumPlan ? (
              <>
                <div className="text-slate-600">
                  المضرب البريميوم قابل لإعادة الاستخدام في مزادات متعددة.
                </div>
                <div className="text-sm text-slate-600">
                  السعر:{" "}
                  <span className="font-bold">
                    <Money value={toMoneyNumber(premiumPlan.price, 0)} />
                  </span>
                </div>
                <div className="text-sm text-slate-600">
                  عدد مرات الاستخدام:{" "}
                  <span className="font-bold">{premiumPlan.usage_limit}</span>
                </div>
                <div className="text-sm text-slate-600">
                  الصلاحية:{" "}
                  <span className="font-bold">
                    {premiumPlan.validity_days} يوم
                  </span>
                </div>
                <DynamicButton
                  onClick={handlePremiumPurchase}
                  isLoading={purchasePremiumPaddle.isPending}
                  isDisabled={premiumPlan.active === false}
                  className="px-4 py-2 rounded-lg bg-[#0F5132] text-white hover:bg-[#0F5132]/90"
                >
                  شراء بريميوم
                </DynamicButton>
                {premiumPlan.active === false && (
                  <div className="text-xs text-amber-700">
                    خطة البريميوم غير مفعلة حاليا.
                  </div>
                )}
              </>
            ) : (
              <div className="text-slate-600">
                لا توجد خطة بريميوم متاحة حاليا.
              </div>
            )}
          </div>
        </div>
      </div>
    </BaseModal>
  );
}
