"use client";

import React, {useState} from "react";
import AppButton from "../ui/button";
import {useRouter} from "@/i18n/routing";
import {DeliveryOptions, SettingAppCustomer} from "@/types/appSetting";
import {DownloadOutlined} from "@ant-design/icons";
import {onDownloadContentProduct} from "@/services/apis/product";
import {useTranslations} from "use-intl";
import {showToast} from "@/components/toast/showToast";

interface BEObj {
    openContent: (params: {
        DownloadID: string;
        AuthID: string;
        AuthName: string;
        AuthKey: string;
        CustomName?: string;
        ShowAlertSB?: boolean;
        ShowAlertNSB?: boolean;
    }) => void;
    getContentsURL: (params: {
        cid: string;
        type: number;
        staging?: boolean;
        cdn?: boolean;
    }) => string;
    downloadContents: (options: {
        AuthKey: string;
        ContentsType: string;
        ContentsURL: string;
        ThumbURL: string;
        Title: string;
        Author?: string;
        DistributorName?: string;
        DistributorURL?: string;
        Direction?: string;
        DownloadablePlatform?: string;
        GlobalDownloadID?: string;
        AuthID?: string;
        AuthName?: string;
        Open?: boolean;
        Temporary?: boolean;
        CustomScheme?: boolean;
    }) => void;
}

declare global {
    interface Window {
        BEObj?: BEObj;
    }
}

interface ProductCardProps {
    params?: { contentGroupId: string };
    id: number;
    customerId?: string;
    title: string;
    subtitle: string;
    imageUrl: string;
    contentDownloadId?: string;
    contentId?: string;
    contentGroupId?: string;
    expireDate?: string | null;
    isSettingAppCustomer: SettingAppCustomer;
}

const ProductCard: React.FC<ProductCardProps> = ({
                                                     params,
                                                     id,
                                                     customerId,
                                                     title,
                                                     subtitle,
                                                     imageUrl,
                                                     contentDownloadId,
                                                     contentId,
                                                     contentGroupId,
                                                     isSettingAppCustomer,
                                                     expireDate
                                                 }) => {
    const router = useRouter();
    const t = useTranslations("ManageContentPage");
    const contentGroupIdOnParams = params?.contentGroupId;

    // Determine which button(s) to show based on the new logic
    const hasContentId = Boolean(contentId);
    const hasContentGroupId = Boolean(contentGroupId);
    const hasContentGroupIdOnParams = Boolean(contentGroupIdOnParams);

    // Logic: If both contentId and contentGroupId exist:
    // - If contentGroupIdOnParams exists, show View button
    // - If contentGroupIdOnParams doesn't exist, show View details button

    const deliveryOptions = isSettingAppCustomer.deliveryOptions;

    const showViewButton =
        deliveryOptions?.online &&
        hasContentId &&
        !hasContentGroupId;
    const showViewDetailsButton =
        hasContentGroupId && !hasContentGroupIdOnParams;
    const showDownloadButton = deliveryOptions?.offline && hasContentId && !hasContentGroupId;

    const [isDownloading, setIsDownloading] = useState(false);

    function download(
        title,
        author,
        distributor,
        slug,
        type,
        downloadable,
        direction,
        online
    ) {
        try {
            if (typeof window !== "undefined" && window.BEObj) {
                window.BEObj?.downloadContents({
                    AuthKey:
                    isSettingAppCustomer.beAuthKey,
                    ContentsType: type,
                    ContentsURL: window.BEObj.getContentsURL({
                        cid: slug,
                        type: 1,
                        cdn: true
                    }),
                    ThumbURL: window.BEObj.getContentsURL({
                        cid: slug,
                        type: 2,
                        cdn: true,
                    }),
                    Title: title,
                    Author: author,
                    DistributorName: distributor,
                    DistributorURL: "",
                    Direction: direction,
                    DownloadablePlatform: downloadable,
                    AuthID: isSettingAppCustomer.beUserId,
                    AuthName: isSettingAppCustomer.customerEmail,
                    Open: online,
                    Temporary: online,
                    CustomScheme: true,
                });
            }
        } catch (e) {
            alert((e as Error).message);
        }
    }

    // const handleDownload = async () => {
    //   if (!contentId) return;

    //   try {
    //     setIsDownloading(true);
    //     console.log("contentDownloadId: ", contentDownloadId);
    //     console.log("isSettingAppCustomer: ", isSettingAppCustomer);

    //     if (contentDownloadId) {
    //       if (typeof window !== "undefined" && window.BEObj) {
    //         window.BEObj.openContent({
    //           DownloadID: contentDownloadId,
    //           AuthID: isSettingAppCustomer.beUserId,
    //           AuthName: isSettingAppCustomer.customerEmail,
    //           AuthKey: isSettingAppCustomer.beAuthKey,
    //           ShowAlertSB: false,
    //           ShowAlertNSB: false,
    //         });
    //       } else {
    //         console.error("BEObj not found");
    //       }
    //     } else {
    //       console.error("downloadContentId not found");
    //     }
    //   } catch (error) {
    //     console.error("Error download:", error);
    //   } finally {
    //     setIsDownloading(false);
    //   }
    // };

    const handleCheckSubscriptionExpired = (expireDate?: string | null) => {
        if (!expireDate) return false;
        const currentTime = new Date().getTime();
        const expirationTime = new Date(expireDate).getTime();

        return currentTime > expirationTime;
    }

    const handleDownload = async () => {
        setIsDownloading(true);
        try {
            if (!contentId) throw new Error("contentId not found");
            if (!contentDownloadId) throw new Error("downloadContentId not found");
            const isSubscriptionExpired = handleCheckSubscriptionExpired(expireDate)
            if (isSubscriptionExpired) {
                showToast("error", t("errors.can_not_download_when_subscription_expired"));
                return
            }
            if (typeof window !== "undefined" && window.BEObj) {
                download(
                    title,
                    "",
                    "",
                    contentId,
                    "krpdf",
                    "all",
                    "l2r",
                    false
                );
            } else {
                console.error("BEObj not found");
            }
        } catch (error) {
            console.error("Error download:", error);
        } finally {
            setIsDownloading(false);
        }
    };

    return (
        <div
            className="w-full bg-white rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-all duration-300 mb-4">
            <div className="flex flex-col md:flex-row">
                <div
                    className="md:w-1/4 lg:w-1/5 relative bg-gradient-to-br from-indigo-50 to-purple-50 p-4 flex items-center justify-center">
                    <div className="relative w-full max-w-xs mx-auto">
                        <div
                            className="absolute -right-2 top-2 w-full h-full bg-gray-800 opacity-20 rounded-lg transform rotate-1"></div>
                        <img
                            src={imageUrl || "/placeholder-image.jpg"}
                            alt={title}
                            className="relative w-full object-cover rounded-lg shadow-md transform transition-transform duration-300 hover:scale-105"
                            style={{aspectRatio: "2/3"}}
                        />
                    </div>
                </div>

                <div className="md:w-3/4 lg:w-4/5 p-6 flex flex-col justify-between">
                    <div>
                        <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between mb-3">
                            <div className="flex-1">
                                <h2 className="text-xl md:text-2xl font-bold text-gray-800 line-clamp-1">
                                    {title}
                                </h2>
                            </div>
                        </div>

                        <div className="text-gray-700 mb-4">
                            <p className="line-clamp-2 text-sm md:text-base">
                                {subtitle ? (
                                    <span dangerouslySetInnerHTML={{__html: subtitle}}/>
                                ) : (
                                    ""
                                )}
                            </p>
                        </div>
                    </div>

                    <div className="flex flex-wrap justify-end gap-2 mt-2">
                        {showViewButton && (
                            <AppButton
                                type="primary"
                                className="flex items-center text-white"
                                onClick={() =>
                                    router.push(
                                        `/manage-content/${customerId || ""}/view/${contentId}`
                                    )
                                }
                            >
                                {t("view")}
                            </AppButton>
                        )}

                        {showViewDetailsButton && (
                            <AppButton
                                type="primary"
                                className="flex items-center text-white"
                                onClick={() =>
                                    router.push(
                                        `/manage-content/${
                                            customerId || ""
                                        }/view-group/${contentGroupId}`
                                    )
                                }
                            >
                                {t("viewDetails")}
                            </AppButton>
                        )}

                        {/* {showDownloadButton && (
              <AppButton
                type="default"
                onClick={handleDownload}
                disabled={isDownloading}
                icon={<DownloadOutlined />}
                loading={isDownloading}
              >
                {isDownloading ? t("downloading") : t("download")}
              </AppButton>
            )} */}

                        {showDownloadButton && (
                            <AppButton
                                type="default"
                                onClick={handleDownload}
                                disabled={isDownloading}
                                icon={<DownloadOutlined/>}
                                loading={isDownloading}
                            >
                                {isDownloading ? t("downloading") : t("download")}
                            </AppButton>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
};

export default ProductCard;