'use client';

import { useEffect, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import Select from 'react-select';
import CustomFetch from '@/Utils/APIRequest/AxiosInstance';
import {
    CountriesAPI,
    CountryRecommendedCategoryListAPI,
    CountryRecommendedOrderAPI,
    CountryRecommendedToggleAPI,
} from '@/Utils/APIRequest/Endpoints';
import usePost from '@/Utils/Hooks/usePost';
import { CustomToast } from '@/Utils/CustomToast';
import CategoryListPanel from './CategoryListPanel';
import CategoryDetailPanel from './CategoryDetailPanel';
import { CountryRecommendedCategory } from './types';

// type DiscoveryTab = 'categories' | 'display-settings' | 'discovery-rules';
type DiscoveryTab = 'categories' | 'display-settings' | 'discovery-rules';

const DESKTOP_BREAKPOINT = 992;

const useIsDesktop = () => {
    const [isDesktop, setIsDesktop] = useState(() =>
        typeof window !== 'undefined'
            ? window.matchMedia(`(min-width: ${DESKTOP_BREAKPOINT}px)`).matches
            : true
    );

    useEffect(() => {
        const mediaQuery = window.matchMedia(`(min-width: ${DESKTOP_BREAKPOINT}px)`);
        const handleChange = () => setIsDesktop(mediaQuery.matches);
        handleChange();
        mediaQuery.addEventListener('change', handleChange);
        return () => mediaQuery.removeEventListener('change', handleChange);
    }, []);

    return isDesktop;
};

const AdminCampaignDiscovery = () => {
    const [activeTab, setActiveTab] = useState<DiscoveryTab>('categories');
    const [selectedCountryId, setSelectedCountryId] = useState<string | null>(null);
    const [selectedCategory, setSelectedCategory] = useState<CountryRecommendedCategory | null>(null);
    const [showMobileDetail, setShowMobileDetail] = useState(false);
    const isDesktop = useIsDesktop();

    const { data: countriesData } = useQuery({
        queryKey: [CountriesAPI],
        queryFn: () => CustomFetch({ url: CountriesAPI }, null, false),
        refetchOnWindowFocus: false,
        select: (data) => data?.data?.data ?? data?.data ?? [],
    });

    const countryOptions = (Array.isArray(countriesData) ? countriesData : []).map((c: any) => ({
        value: String(c.id),
        label: c.country_name ?? c.name ?? String(c.id),
    }));

    useEffect(() => {
        if (!selectedCountryId && countryOptions.length > 0) {
            setSelectedCountryId(countryOptions[0].value);
        }
    }, [countryOptions, selectedCountryId]);

    const {
        data: recommendedData,
        isPending: recommendedLoading,
        refetch: refetchRecommended,
    } = useQuery({
        queryKey: [CountryRecommendedCategoryListAPI, selectedCountryId, true],
        queryFn: () =>
            CustomFetch(
                {
                    url: CountryRecommendedCategoryListAPI,
                    params: { country_id: selectedCountryId, recommended: true },
                },
                null,
                false
            ),
        refetchOnWindowFocus: false,
        enabled: !!selectedCountryId,
        select: (data) => data?.data?.data ?? data?.data ?? [],
    });

    const {
        data: otherData,
        isPending: otherLoading,
        refetch: refetchOther,
    } = useQuery({
        queryKey: [CountryRecommendedCategoryListAPI, selectedCountryId, false],
        queryFn: () =>
            CustomFetch(
                {
                    url: CountryRecommendedCategoryListAPI,
                    params: { country_id: selectedCountryId, recommended: false },
                },
                null,
                false
            ),
        refetchOnWindowFocus: false,
        enabled: !!selectedCountryId,
        select: (data) => data?.data?.data ?? data?.data ?? [],
    });

    const recommendedCategories: CountryRecommendedCategory[] = Array.isArray(recommendedData)
        ? recommendedData
        : [];
    const otherCategories: CountryRecommendedCategory[] = Array.isArray(otherData) ? otherData : [];

    useEffect(() => {
        if (!selectedCategory && recommendedCategories.length > 0 && isDesktop) {
            setSelectedCategory(recommendedCategories[0]);
        }
    }, [recommendedCategories, selectedCategory, isDesktop]);

    useEffect(() => {
        if (isDesktop) {
            setShowMobileDetail(false);
        }
    }, [isDesktop]);

    useEffect(() => {
        if (selectedCategory) {
            const stillExists = [...recommendedCategories, ...otherCategories].some(
                (c) => c.id === selectedCategory.id
            );
            if (!stillExists && recommendedCategories.length > 0) {
                setSelectedCategory(recommendedCategories[0]);
            }
        }
    }, [recommendedCategories, otherCategories, selectedCategory]);

    const refetchCategoryLists = () => {
        refetchRecommended();
        refetchOther();
    };

    const {
        isPending: isTogglingCategory,
        mutate: toggleCategory,
        variables: toggleVariables,
    } = usePost(
        CountryRecommendedToggleAPI,
        null,
        (response) => {
            if (response?.status === 200 || response?.status === 201) {
                CustomToast('success', 'Category updated');
                refetchCategoryLists();
            }
        },
        'patch'
    );

    const togglingCategoryId =
        isTogglingCategory && toggleVariables ? (toggleVariables as any).category_id : null;

    const { mutate: reorderCategory } = usePost(
        CountryRecommendedOrderAPI,
        null,
        (response) => {
            if (response?.status === 200 || response?.status === 201) {
                refetchRecommended();
            }
        },
        'patch'
    );

    const handleToggleCategory = (category: CountryRecommendedCategory) => {
        if (!selectedCountryId || isTogglingCategory) return;
        const payload: any = {
            country_id: selectedCountryId,
            category_id: category.id,
        };
        toggleCategory(payload);
    };

    const handleReorderRecommended = (category: CountryRecommendedCategory, newOrderBy: number) => {
        const countryRecommendedId =
            category.country_recommended_id ?? category.recommed_id ?? category.recommended_id;
        if (!countryRecommendedId) return;
        let obj: any = {
            country_recommended_id: countryRecommendedId,
            country_id: selectedCountryId,
            order_by: newOrderBy,
        }
        reorderCategory(obj);
    };

    const handleCountryChange = (option: { value: string; label: string } | null) => {
        setSelectedCountryId(option?.value ?? null);
        setSelectedCategory(null);
        setShowMobileDetail(false);
    };

    const handleSelectCategory = (category: CountryRecommendedCategory) => {
        setSelectedCategory(category);
        if (!isDesktop) {
            setShowMobileDetail(true);
        }
    };

    const handleCloseMobileDetail = () => {
        setShowMobileDetail(false);
    };

    const tabs: { id: DiscoveryTab; label: string }[] = [
        { id: 'categories', label: 'Categories' },
        // { id: 'display-settings', label: 'Display Settings' },
        // { id: 'discovery-rules', label: 'Discovery Rules' },
    ];

    return (
        <div>
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-5">
                <div>
                    <h2 className="text-xl font-bold text-neutral-900">Campaign Discovery Management</h2>
                    <p className="text-sm text-neutral-500 mt-1">
                        Configure how campaigns are discovered and displayed to influencers
                    </p>
                </div>
                <div className="min-w-[200px]">
                    <Select
                        options={countryOptions}
                        value={countryOptions.find((o) => o.value === selectedCountryId) ?? null}
                        onChange={handleCountryChange}
                        placeholder="Select country"
                        className="text-sm"
                    />
                </div>
            </div>

            <div className="flex items-center border-b border-lightGray mb-5 gap-3 overflow-x-auto pb-4">
                {tabs.map((tab) => (
                    <button
                        key={tab.id}
                        type="button"
                        onClick={() => setActiveTab(tab.id)}
                        className={`text-sm cursor-pointer border rounded-full px-5 py-2 whitespace-nowrap transition-colors ${
                            activeTab === tab.id
                                ? 'text-white bg-primary font-medium border-transparent'
                                : 'text-black font-medium border-lightGray hover:border-primary/30'
                        }`}
                    >
                        {tab.label}
                    </button>
                ))}
            </div>

            {activeTab === 'categories' && (
                <div className="grid grid-cols-12 gap-3 min-h-[600px] items-start">
                    <CategoryListPanel
                        recommendedCategories={recommendedCategories}
                        otherCategories={otherCategories}
                        selectedCategoryId={selectedCategory?.id ?? null}
                        isLoading={recommendedLoading || otherLoading}
                        onSelectCategory={handleSelectCategory}
                        onToggleCategory={handleToggleCategory}
                        onReorderRecommended={handleReorderRecommended}
                        isHiddenOnMobile={showMobileDetail}
                        togglingCategoryId={togglingCategoryId}
                    />
                    <CategoryDetailPanel
                        selectedCountryId={selectedCountryId ?? ''}
                        category={selectedCategory}
                        onCampaignsChanged={refetchCategoryLists}
                        onMinApplicationSaved={refetchRecommended}
                        onClose={handleCloseMobileDetail}
                        isVisibleOnMobile={showMobileDetail}
                    />
                </div>
            )}

            {activeTab === 'display-settings' && (
                <div className="bg-white border border-lightGray rounded-2xl p-8 text-center">
                    <p className="text-sm text-neutral-500">Display Settings coming soon</p>
                </div>
            )}

            {activeTab === 'discovery-rules' && (
                <div className="bg-white border border-lightGray rounded-2xl p-8 text-center">
                    <p className="text-sm text-neutral-500">Discovery Rules coming soon</p>
                </div>
            )}
        </div>
    );
};

export default AdminCampaignDiscovery;
