import { useState } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { useGetCategoryById, useCreateCategoryAttribute, useUpdateCategoryAttribute, useDeleteCategoryAttribute } 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 updateAttributeMutation = useUpdateCategoryAttribute()
    const deleteAttributeMutation = useDeleteCategoryAttribute()

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

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

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

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

    const openEditModal = (attribute: any) => {
        setEditingAttributeId(attribute._id)
        setNewAttribute({
            title: attribute.title,
            type: attribute.type,
            multiple: attribute.multiple,
            hint: attribute.hint || '',
            required: attribute.required,
            values: attribute.values.map((v: any) => ({ text: v.text }))
        })
        setIsModalOpen(true)
    }

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

        if (editingAttributeId) {
            // ویرایش ویژگی
            updateAttributeMutation.mutate(
                { attrId: editingAttributeId, ...newAttribute },
                {
                    onSuccess: () => {
                        toast.success('ویژگی با موفقیت ویرایش شد')
                        resetModal()
                        queryClient.invalidateQueries({ queryKey: ['category', id] })
                        queryClient.invalidateQueries({ queryKey: ['category', 'attributes', id] })
                    },
                    onError: (error) => {
                        toast.error(extractErrorMessage(error))
                    }
                }
            )
        } else {
            // ایجاد ویژگی جدید
            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 deleteAttribute = async (attributeId: number) => {
        deleteAttributeMutation.mutate(attributeId, {
            onSuccess: () => {
                toast.success('ویژگی با موفقیت حذف شد')
                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,
        editingAttributeId,

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

        // Loading states
        isAddingLoading: createAttributeMutation.isPending || updateAttributeMutation.isPending,
        isDeletingLoading: deleteAttributeMutation.isPending
    }
}
