import { useState } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { useGetCategoryVariants, useCreateCategoryVariant, useUpdateCategoryVariant } from './useCategoryData'
import { CategoryThemeEnum } from '../enum/Enum'
import { type VariantType, type ColorVariantType } from '../types/Types'
import { toast } from 'react-toastify'
import { extractErrorMessage } from '../../../helpers/utils'

interface UseVariantLogicProps {
    id: string | undefined
}

interface CategoryVariantData {
    category: {
        categoryVariants: {
            sizes?: VariantType[]
            colors?: ColorVariantType[]
            meterages?: VariantType[]
        }
        theme: CategoryThemeEnum
        title_fa: string
    }
}

interface ApiResponse {
    results: {
        data: CategoryVariantData
    }
}

export const useVariantLogic = ({ id }: UseVariantLogicProps) => {
    const queryClient = useQueryClient()
    const { data, isLoading } = useGetCategoryVariants(id!)
    const createVariantMutation = useCreateCategoryVariant()
    const updateVariantMutation = useUpdateCategoryVariant()

    const [isModalOpen, setIsModalOpen] = useState(false)
    const [newVariant, setNewVariant] = useState({
        value: '',
        name: '',
        hexColor: '#000000'
    })

    const categoryData = data as ApiResponse | undefined
    const category = categoryData?.results?.data?.category
    const theme = category?.theme
    const categoryVariants = category?.categoryVariants || {
        sizes: [],
        colors: [],
        meterages: []
    }

    const hasExistingVariants =
        (categoryVariants.sizes && categoryVariants.sizes.length > 0) ||
        (categoryVariants.colors && categoryVariants.colors.length > 0) ||
        (categoryVariants.meterages && categoryVariants.meterages.length > 0)

    const resetModal = () => {
        setIsModalOpen(false)
        setNewVariant({ value: '', name: '', hexColor: '#000000' })
    }

    const openModal = () => setIsModalOpen(true)
    const closeModal = () => resetModal()

    const addVariant = async () => {
        if (!id || !categoryData) return

        let variantData

        switch (theme) {
            case CategoryThemeEnum.Sized:
                variantData = {
                    id,
                    theme: CategoryThemeEnum.Sized,
                    sizes: hasExistingVariants
                        ? [...(categoryVariants.sizes || []), { _id: Date.now(), value: newVariant.value }]
                        : [{ _id: Date.now(), value: newVariant.value }]
                }
                break

            case CategoryThemeEnum.Colored:
                variantData = {
                    id,
                    theme: CategoryThemeEnum.Colored,
                    colors: hasExistingVariants
                        ? [...(categoryVariants.colors || []), { name: newVariant.name, hexColor: newVariant.hexColor }]
                        : [{ name: newVariant.name, hexColor: newVariant.hexColor }]
                }
                break

            case CategoryThemeEnum.Meterage:
                variantData = {
                    id,
                    theme: CategoryThemeEnum.Meterage,
                    meterages: hasExistingVariants
                        ? [...(categoryVariants.meterages || []), { _id: Date.now(), value: newVariant.value }]
                        : [{ _id: Date.now(), value: newVariant.value }]
                }
                break

            default:
                return
        }

        const mutation = hasExistingVariants ? updateVariantMutation : createVariantMutation

        mutation.mutate(variantData, {
            onError: (error) => {
                toast.error(extractErrorMessage(error))
            }
        })
        resetModal()
        queryClient.invalidateQueries({ queryKey: ['category', 'variants', id] })
    }

    const deleteVariant = async (variantType: 'sizes' | 'colors' | 'meterages', index: number) => {
        if (!id || !categoryData) return

        let updatedVariants
        let variantData

        switch (variantType) {
            case 'sizes':
                if (!categoryVariants.sizes || index >= categoryVariants.sizes.length) return
                updatedVariants = categoryVariants.sizes.filter((_, i) => i !== index)
                variantData = { id, sizes: updatedVariants }
                break
            case 'colors':
                if (!categoryVariants.colors || index >= categoryVariants.colors.length) return
                updatedVariants = categoryVariants.colors.filter((_, i) => i !== index)
                variantData = { id, colors: updatedVariants }
                break
            case 'meterages':
                if (!categoryVariants.meterages || index >= categoryVariants.meterages.length) return
                updatedVariants = categoryVariants.meterages.filter((_, i) => i !== index)
                variantData = { id, meterages: updatedVariants }
                break
            default:
                return
        }

        await updateVariantMutation.mutateAsync({ ...variantData, theme: theme! })
        queryClient.invalidateQueries({ queryKey: ['category', 'variants', id] })
    }

    return {
        // Data
        category,
        theme,
        categoryVariants,
        isLoading,

        // Modal state
        isModalOpen,
        newVariant,

        // Actions
        openModal,
        closeModal,
        setNewVariant,
        addVariant,
        deleteVariant,

        // Loading states
        isAddingLoading: createVariantMutation.isPending,
        isUpdatingLoading: updateVariantMutation.isPending
    }
}
