import { useState } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { useGetCategoryById, useCreateCategoryAttribute } from './useCategoryData'
import { type CreateCategoryAttributeType } from '../types/Types'
import { toast } from 'react-toastify'
import { extractErrorMessage } from '../../../helpers/utils'

interface UseAttributesLogicProps {
    id: string | undefined
}

export const useAttributesLogic = ({ id }: UseAttributesLogicProps) => {
    const queryClient = useQueryClient()
    const { data, isLoading } = useGetCategoryById(id!)
    const createAttributeMutation = useCreateCategoryAttribute()

    const [isModalOpen, setIsModalOpen] = useState(false)
    const [newAttribute, setNewAttribute] = useState<CreateCategoryAttributeType>({
        title: '',
        type: 'text',
        required: false,
        values: []
    })

    const categoryData = data?.results?.data
    const category = categoryData

    const resetModal = () => {
        setIsModalOpen(false)
        setNewAttribute({
            title: '',
            type: 'text',
            required: false,
            values: []
        })
    }

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

    const addAttribute = async () => {
        if (!id || !newAttribute.title.trim()) return

        createAttributeMutation.mutate(
            { id, data: newAttribute },
            {
                onSuccess: () => {
                    toast.success('ویژگی با موفقیت اضافه شد')
                    resetModal()
                    queryClient.invalidateQueries({ queryKey: ['category', id] })
                    queryClient.invalidateQueries({ queryKey: ['category', 'attributes', id] })
                },
                onError: (error) => {
                    toast.error(extractErrorMessage(error))
                }
            }
        )
    }

    const updateNewAttribute = (field: keyof CreateCategoryAttributeType, value: any) => {
        setNewAttribute(prev => ({
            ...prev,
            [field]: value
        }))
    }

    const addValueToAttribute = (text: string) => {
        if (!text.trim()) return
        setNewAttribute(prev => ({
            ...prev,
            values: [...prev.values, { text: text.trim() }]
        }))
    }

    const removeValueFromAttribute = (index: number) => {
        setNewAttribute(prev => ({
            ...prev,
            values: prev.values.filter((_, i) => i !== index)
        }))
    }

    return {
        // Data
        category,
        isLoading,

        // Modal state
        isModalOpen,
        newAttribute,

        // Actions
        openModal,
        closeModal,
        setNewAttribute: updateNewAttribute,
        addAttribute,
        addValueToAttribute,
        removeValueFromAttribute,

        // Loading states
        isAddingLoading: createAttributeMutation.isPending
    }
}
