"use client";

import { useGetCartItems } from "@/app/[name]/(Main)/cart/hooks/useCartData";
import { useGetUserWallet } from "@/app/[name]/(Main)/transactions/hooks/useTransactionData";
import { useGetProfile, useSingleUpload } from "@/app/[name]/(Profile)/profile/hooks/userProfileData";
import { toast } from "@/components/Toast";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { extractErrorMessage } from "@/lib/func";
import { Card, Icon, Wallet2 } from "iconsax-react";
import Image from "next/image";
import { glassSurfaceCard } from "@/lib/styles/glassSurface";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { PaymentMethodEnum } from "../../enum/Enum";
import { useGetPaymentMethod } from "../../hooks/useOrderData";
import { useCheckoutStore } from "../../store/Store";

type PaymentSectionProps = {
  paymentType: string;
  onPaymentTypeChange: (id: string) => void;
};

type CreditCardOption = {
  cardNumber: string;
  cardOwner: string;
};

const getIconByMethod = (method: PaymentMethodEnum): Icon => {
  if (method === PaymentMethodEnum.Online || method === PaymentMethodEnum.CreditCard) {
    return Card;
  }
  if (method === PaymentMethodEnum.Cash || method === PaymentMethodEnum.Wallet) {
    return Wallet2;
  }
  return Card;
};

export const PaymentSection = ({ paymentType, onPaymentTypeChange }: PaymentSectionProps) => {
  const { t: tOrderDetail } = useTranslation("parallels", { keyPrefix: "OrderDetail" });
  const { t: tOrders } = useTranslation("orders");
  const { data: paymentMethod } = useGetPaymentMethod();
  const { setIsSelectedPayment, paymentDesc, setPaymentDesc, paymentAttachments, setPaymentAttachments } = useCheckoutStore();
  const { data: userWallet } = useGetUserWallet();
  const { isSuccess } = useGetProfile();
  const { data: cartData } = useGetCartItems(isSuccess);
  const { mutateAsync: singleUpload, isPending: isUploading } = useSingleUpload();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [selectedCardNumber, setSelectedCardNumber] = useState<string>("");

  const walletAmount = userWallet?.data?.balance ?? 0;
  const totalAmount = cartData?.data?.total ?? 0;
  const isWalletInsufficient = walletAmount < totalAmount;

  const formatPrice = useCallback((value: number) => value.toLocaleString("fa-IR"), []);

  const getPaymentMethodTranslation = useCallback(
    (method: string, fallbackTitle: string) => {
      const translationKey = `paymentMethod.${method}`;
      const translation = tOrders(translationKey);
      return translation !== translationKey ? translation : fallbackTitle;
    },
    [tOrders],
  );

  const paymentOptions = useMemo(() => {
    if (!paymentMethod?.data) return [];

    return paymentMethod.data
      .filter((item) => item.enabled)
      .sort((a, b) => a.order - b.order)
      .map((item) => ({
        id: item.id,
        label: getPaymentMethodTranslation(item.method, item.description),
        icon: getIconByMethod(item.method),
        method: item.method,
        cardNumber: item.cardNumber,
        cardOwner: item.cardOwner,
        cards:
          item.cards?.map((card) => ({
            cardNumber: card.cardNumber,
            cardOwner: card.owner,
          })) ?? [],
        description: item.description,
        isWallet: item.method === PaymentMethodEnum.Wallet,
      }));
  }, [paymentMethod, getPaymentMethodTranslation]);

  const selectedCreditCard = useMemo(() => {
    const selected = paymentOptions.find((opt) => opt.id === paymentType);
    if (selected?.method === PaymentMethodEnum.CreditCard) return selected;
    return null;
  }, [paymentOptions, paymentType]);

  const handlePaymentTypeChange = (value: string) => {
    const selected = paymentOptions.find((opt) => opt.id === value);
    if (selected?.method !== PaymentMethodEnum.CreditCard) {
      setPaymentDesc("");
      setPaymentAttachments([]);
      setSelectedCardNumber("");
    }
    onPaymentTypeChange(value);
    setIsSelectedPayment(true);
  };

  const creditCardOptions = useMemo<CreditCardOption[]>(() => {
    if (!selectedCreditCard) return [];

    const normalizedCards = selectedCreditCard.cards.filter(
      (card): card is CreditCardOption => !!card.cardNumber && !!card.cardOwner,
    );

    if (normalizedCards.length > 0) return normalizedCards;

    if (selectedCreditCard.cardNumber && selectedCreditCard.cardOwner) {
      return [{ cardNumber: selectedCreditCard.cardNumber, cardOwner: selectedCreditCard.cardOwner }];
    }

    return [];
  }, [selectedCreditCard]);

  useEffect(() => {
    if (creditCardOptions.length === 0) {
      setSelectedCardNumber("");
      return;
    }

    const hasSelectedCard = creditCardOptions.some((item) => item.cardNumber === selectedCardNumber);
    if (!hasSelectedCard) {
      setSelectedCardNumber(creditCardOptions[0].cardNumber);
    }
  }, [creditCardOptions, selectedCardNumber]);

  const selectedCard = useMemo(
    () => creditCardOptions.find((item) => item.cardNumber === selectedCardNumber) ?? null,
    [creditCardOptions, selectedCardNumber],
  );

  const handleCopyCardNumber = useCallback(
    async (cardNumber: string) => {
      try {
        await navigator.clipboard.writeText(cardNumber);
        toast(tOrderDetail("SectionPayment.CreditCard.CopySuccess"), "success");
      } catch {
        toast(tOrderDetail("SectionPayment.CreditCard.CopyError"), "error");
      }
    },
    [tOrderDetail],
  );

  const handleReceiptUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    try {
      const response = await singleUpload(file);
      if (response?.data?.url) {
        setPaymentAttachments([response.data.url]);
        toast(tOrderDetail("SectionPayment.CreditCard.UploadSuccess"), "success");
      }
    } catch (error) {
      toast(extractErrorMessage(error), "error");
    } finally {
      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
    }
  };

  return (
    <section className={glassSurfaceCard('p-4')}>
      <div className="py-3">
        <h3 className="text-sm2 font-medium leading-5">{tOrderDetail("SectionPayment.Title")}</h3>

        <RadioGroup value={paymentType} onValueChange={handlePaymentTypeChange} className="flex flex-col gap-6 mt-6">
          {paymentOptions.map(({ id, label, icon: Icon, isWallet }) => {
            const isDisabled = isWallet && isWalletInsufficient;

            return (
              <div key={id} className="flex items-center justify-between">
                <RadioGroupItem value={id} id={`paymentMethod${id}`} disabled={isDisabled} />
                <label className={`flex items-center gap-2 ${isDisabled ? "cursor-not-allowed opacity-50" : "cursor-pointer"}`} htmlFor={`paymentMethod${id}`}>
                  <div className="flex gap-1">
                    {isWallet && <span className="text-xs text-gray-500 dark:text-gray-400 mt-1">({formatPrice(walletAmount)} T)</span>}
                    <span className="text-xs mt-0.5">{label}</span>
                  </div>
                  <Icon size={16} color="currentColor" className="mr-2" />
                </label>
              </div>
            );
          })}
        </RadioGroup>

        {selectedCreditCard && (
          <div className="mt-6 pt-4 border-t border-border flex flex-col gap-4">
            {creditCardOptions.length > 0 && (
              <div className="space-y-3">
                <p className="text-xs text-gray-500 dark:text-gray-400">
                  {`تعداد کارت های مقصد: ${creditCardOptions.length}`}
                </p>
                {creditCardOptions.map((card) => {
                  const isActiveCard = selectedCardNumber === card.cardNumber;
                  return (
                    <button
                      key={card.cardNumber}
                      type="button"
                      onClick={() => setSelectedCardNumber(card.cardNumber)}
                      className={`w-full rounded-normal border px-3 py-2 text-right transition-colors ${
                        isActiveCard ? "border-primary bg-primary/5" : "border-border hover:border-primary/50"
                      }`}
                    >
                      <span className="block text-xs text-gray-500 dark:text-gray-400">{card.cardOwner}</span>
                      <span className="block text-sm font-medium mt-1" dir="ltr">
                        {card.cardNumber}
                      </span>
                    </button>
                  );
                })}
              </div>
            )}
            {selectedCard && (
              <div className="flex items-start justify-between gap-4">
                {selectedCard.cardOwner && (
                  <div>
                    <span className="text-xs text-gray-500 dark:text-gray-400">{tOrderDetail("SectionPayment.CreditCard.CardOwnerLabel")}</span>
                    <p className="text-sm font-medium mt-1">{selectedCard.cardOwner}</p>
                  </div>
                )}
                {selectedCard.cardNumber && (
                  <div className="text-left">
                    <span className="text-xs text-gray-500 dark:text-gray-400">{tOrderDetail("SectionPayment.CreditCard.CardNumberLabel")}</span>
                    <button
                      type="button"
                      className="block text-sm font-medium mt-1 cursor-pointer hover:text-primary transition-colors"
                      dir="ltr"
                      onClick={() => handleCopyCardNumber(selectedCard.cardNumber)}
                    >
                      {selectedCard.cardNumber}
                    </button>
                  </div>
                )}
              </div>
            )}
            {/* {selectedCreditCard.description && (
                            <p className='text-xs text-gray-500 dark:text-gray-400 leading-5'>
                                {selectedCreditCard.description}
                            </p>
                        )} */}
            <div>
              <label className="text-xs text-gray-500 dark:text-gray-400" htmlFor="paymentDesc">
                {tOrderDetail("SectionPayment.CreditCard.PaymentDescLabel")}
              </label>
              <textarea
                id="paymentDesc"
                className="w-full px-2 py-2.5 mt-2 text-xs leading-6 outline-0 border border-border rounded-normal resize-none focus:ring-0"
                placeholder={tOrderDetail("SectionPayment.CreditCard.PaymentDescPlaceholder")}
                value={paymentDesc}
                onChange={(e) => setPaymentDesc(e.target.value)}
                rows={2}
              />
            </div>
            <div>
              <span className="text-xs text-gray-500 dark:text-gray-400">{tOrderDetail("SectionPayment.CreditCard.ReceiptLabel")}</span>
              <input ref={fileInputRef} type="file" accept="image/*" className="hidden" onChange={handleReceiptUpload} />
              {paymentAttachments[0] ? (
                <div className="mt-2 relative w-full h-32 rounded-normal overflow-hidden border border-border">
                  <Image src={paymentAttachments[0]} alt="receipt" fill className="object-contain" />
                  <button
                    type="button"
                    className="absolute top-2 left-2 text-xs bg-white/90 dark:bg-background/90 px-2 py-1 rounded-normal"
                    onClick={() => fileInputRef.current?.click()}
                    disabled={isUploading}
                  >
                    {isUploading ? tOrderDetail("SectionPayment.CreditCard.Uploading") : tOrderDetail("SectionPayment.CreditCard.UploadReceipt")}
                  </button>
                </div>
              ) : (
                <button
                  type="button"
                  className="w-full mt-2 py-3 text-sm2 border border-dashed border-border rounded-normal text-gray-500 dark:text-gray-400 hover:border-primary transition-colors"
                  onClick={() => fileInputRef.current?.click()}
                  disabled={isUploading}
                >
                  {isUploading ? tOrderDetail("SectionPayment.CreditCard.Uploading") : tOrderDetail("SectionPayment.CreditCard.UploadReceipt")}
                </button>
              )}
            </div>
          </div>
        )}
      </div>
    </section>
  );
};
