'use client';

import { useEffect, useState } from 'react';
import PrimaryButton from '@/Component/Common/Forms/PrimaryButton';
import { ArrowBackBlackSVG, CloseModalSVG } from '@/Component/Common/SVGs/CommonSVG';
import usePost from '@/Utils/Hooks/usePost';
import { CustomToast } from '@/Utils/CustomToast';
import { CountryRecommendedCampaignsAPI, CountryRecommendedMinApplicationAPI } from '@/Utils/APIRequest/Endpoints';
import HotCategoryRules from './HotCategoryRules';
import CategoryCampaignListing from './CategoryCampaignListing';
import {
    CountryRecommendedCategory,
    getCategoryTitle,
    getCountryRecommendedId,
    isAllCategory,
    isHotCategory,
} from './types';
import { useQuery } from '@tanstack/react-query';
import CustomFetch from '@/Utils/APIRequest/AxiosInstance';

interface CategoryDetailPanelProps {
    selectedCountryId: string;
    category: CountryRecommendedCategory | null;
    onCampaignsChanged: () => void;
    onMinApplicationSaved: () => void;
    onClose?: () => void;
    isVisibleOnMobile?: boolean;
}

const CategoryDetailPanel = ({
    selectedCountryId,
    category,
    onCampaignsChanged,
    onMinApplicationSaved,
    onClose,
    isVisibleOnMobile = false,
}: CategoryDetailPanelProps) => {
    const [addModalOpen, setAddModalOpen] = useState(false);
    const categoryId = category?.id ?? '';
    const countryRecommendedId = category ? getCountryRecommendedId(category) : '';
    const title = category ? getCategoryTitle(category) : '';
    const showHotRules = category ? isHotCategory(category) : false;
    const showAllRules = category ? isAllCategory(category) : false;
    const [page, setPage] = useState(1);
    const PER_PAGE = 10;

    useEffect(() => {
        setAddModalOpen(false);
        setPage(1);
    }, [categoryId, selectedCountryId]);

    const { data: campaignsData, isPending, isFetching, refetch, fetchStatus } = useQuery({
        queryKey: [CountryRecommendedCampaignsAPI, categoryId, selectedCountryId, page],
        queryFn: () =>
            CustomFetch(
                {
                    url: CountryRecommendedCampaignsAPI,
                    params: { category_id: categoryId, country_id: selectedCountryId, page, per_page: PER_PAGE },
                },
                null,
                false
            ),
        refetchOnWindowFocus: false,
        refetchOnMount: 'always',
        staleTime: 0,
        enabled: !!categoryId,
        select: (data) => data?.data,
    });

    const { isPending: isSavingMinApp, mutate: saveMinApplication } = usePost(
        CountryRecommendedMinApplicationAPI,
        null,
        (response) => {
            if (response?.status === 200 || response?.status === 201) {
                CustomToast('success', 'Minimum applications updated');
                onMinApplicationSaved();
            }
        },
        'patch'
    );

    const handleSaveMinApplication = (value: number) => {
        const payload: any = {
            country_recommended_id: countryRecommendedId,
            min_application: value,
        };
        saveMinApplication(payload);
    };

    const mobileVisibilityClass = isVisibleOnMobile ? 'max-[991px]:block' : 'max-[991px]:hidden';

    if (!category) {
        return (
            <div
                className={`bg-white border border-lightGray rounded-2xl p-6 h-full items-center justify-center col-span-12 min-[992px]:col-span-8 hidden min-[992px]:flex ${mobileVisibilityClass}`}
            >
                <p className="text-sm text-neutral-500">Select a category to view details</p>
            </div>
        );
    }

    return (
        <div
            className={`bg-white border border-lightGray rounded-2xl p-5 h-full flex flex-col col-span-12 min-[992px]:col-span-8 min-[992px]:block ${mobileVisibilityClass}`}
        >
            <div className="flex items-center justify-between gap-3 mb-5 max-md:flex-wrap">
                <div className="flex items-center gap-3 min-w-0">
                    {onClose && (
                        <button
                            type="button"
                            onClick={onClose}
                            className="min-[992px]:hidden shrink-0 p-1 rounded-lg hover:bg-lightGray/60 transition-colors"
                            aria-label="Close category details"
                        >
                            <ArrowBackBlackSVG customClass="w-5 h-5" />
                        </button>
                    )}
                    <div className="flex items-center gap-2 flex-wrap">
                        <h3 className="text-base font-semibold text-neutral-900 truncate text-wrap">
                            Campaigns in {title}
                            {campaignsData !== undefined && (
                                <span className="text-xs text-neutral-500 border border-lightGray rounded-full inline-block px-2.5 py-0.5 ms-2 bg-lightGray/30">
                                    {campaignsData.total} {campaignsData.total === 1 ? 'campaign' : 'campaigns'}
                                </span>
                            )}
                        </h3>

                    </div>
                    {/* <span className="inline-block mt-1 text-xs font-medium text-success bg-success/10 px-2.5 py-0.5 rounded-full">
                        Active
                    </span> */}
                </div>
                {!showAllRules && (
                    <PrimaryButton
                        buttonType="button"
                        customClass="!py-2 !px-4 text-sm whitespace-nowrap"
                        onClick={() => setAddModalOpen(true)}
                    >
                        + Add Campaign
                    </PrimaryButton>
                )}
            </div>

            {showHotRules && (
                <HotCategoryRules
                    minApplication={category.min_application ?? 0}
                    isSaving={isSavingMinApp}
                    onSave={handleSaveMinApplication}
                />
            )}

            {/* {!showHotRules && (
                <div className="border border-lightGray rounded-xl p-4 mb-5 bg-lightGray/20">
                    <p className="text-xs text-neutral-500">
                        Campaigns in this category will be shown to influencers based on the rules below.
                    </p>
                </div>
            )} */}

            <CategoryCampaignListing
                key={`${selectedCountryId}-${categoryId}`}
                categoryId={categoryId}
                selectedCountryId={selectedCountryId}
                title={title}
                addModalOpen={addModalOpen}
                setAddModalOpen={setAddModalOpen}
                onCampaignsChanged={onCampaignsChanged}
                isHotCategory={showHotRules}
                isAllCategory={showAllRules}
                campaignsData={campaignsData}
                page={page}
                setPage={setPage}
                isPending={isPending}
                isFetching={isFetching}
                fetchStatus={fetchStatus}
                refetch={refetch}
            />
        </div>
    );
};

export default CategoryDetailPanel;
