import { type FC, useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useGetProductById } from './hooks/useProductData';
import { useUpdateProductDetail, useUpdateProductAttribute, useUpdateProduct } from './hooks/useProductData';
import { useGetBrands } from '../brand/hooks/useBrandData';
import { useGetCategories } from '../category/hooks/useCategoryData';
import { StepIndicator, Step1Form, Step2Form, Step3Form } from './components';
import { type CreateProductDetailRequestType, type CreateProductAttributeRequestType, type SaveProductRequestType } from './types/Types';
import { toast } from 'react-toastify';
import { Pages } from '@/config/Pages';
import { extractErrorMessage } from '@/helpers/utils';

const UpdateProduct: FC = () => {
    const { id: productId } = useParams<{ id: string }>();
    const productIdNum = parseInt(productId!, 10);
    const [currentStep, setCurrentStep] = useState<1 | 2 | 3>(1);
    const [productData, setProductData] = useState<Partial<CreateProductDetailRequestType & CreateProductAttributeRequestType & SaveProductRequestType>>({});
    const navigate = useNavigate();

    // Fetch existing product data
    const { data: productDetails, isLoading: productLoading, error: productError } = useGetProductById(productId!);

    // API hooks
    const updateProductDetailMutation = useUpdateProductDetail();
    const updateProductAttributeMutation = useUpdateProductAttribute();
    const updateProductMutation = useUpdateProduct();
    const { data: brandsData } = useGetBrands();
    const { data: categoriesData, isLoading: categoriesLoading } = useGetCategories();

    // Initialize product data when product details are loaded
    useEffect(() => {
        if (productDetails?.results?.product) {
            const product = productDetails.results.product;
            setProductData({
                productId: product._id,
                category: product.category._id,
                brand: product.brand._id,
                model: product.model,
                title_fa: product.title_fa,
                title_en: product.title_en,
                seoTitle: product.seoTitle || '',
                source: product.source,
                isFake: product.isFake,
                attributes: product.specifications?.map(spec => ({
                    id: 0, // This might need to be adjusted based on API
                    values: spec.values.map(() => 0) // This might need to be adjusted based on API
                })) || [],
                description: product.description,
                metaDescription: product.metaDescription,
                tags: product.tags,
                advantages: product.advantages,
                disAdvantages: product.disAdvantages,
                imagesList: product.imagesUrl?.list || [],
                coverImage: product.imagesUrl?.cover || '',
            });
        }
    }, [productDetails]);

    if (productLoading) {
        return (
            <div className="flex justify-center items-center min-h-[400px]">
                <div>در حال بارگذاری اطلاعات محصول...</div>
            </div>
        );
    }

    if (productError) {
        return (
            <div className="flex justify-center items-center min-h-[400px]">
                <div className="text-red-500">خطا در بارگذاری اطلاعات محصول</div>
            </div>
        );
    }

    const handleStep1Submit = (data: CreateProductDetailRequestType) => {
        const fullData = {
            ...data,
            productId: productIdNum
        };

        updateProductDetailMutation.mutate(fullData, {
            onSuccess: () => {
                setProductData(prev => ({ ...prev, ...data }));
                setCurrentStep(2);
            },
            onError: (error) => {
                toast.error(extractErrorMessage(error));
            }
        });
    };

    const handleStep2Submit = (data: Omit<CreateProductAttributeRequestType, 'productId'>) => {
        const fullData = {
            ...data,
            productId: productIdNum
        };

        updateProductAttributeMutation.mutate(fullData, {
            onSuccess: () => {
                setProductData(prev => ({ ...prev, ...data }));
                setCurrentStep(3);
            },
            onError: (error) => {
                toast.error(extractErrorMessage(error));
            }
        });
    };

    const handleStep3Submit = (data: Omit<SaveProductRequestType, 'productId'>) => {
        const fullData = {
            ...data,
            productId: productIdNum
        };

        updateProductMutation.mutate(fullData, {
            onSuccess: () => {
                toast.success('محصول با موفقیت بروزرسانی شد');
                navigate(Pages.products.list);
            },
            onError: (error) => {
                toast.error(extractErrorMessage(error));
            }
        });
    };

    const handlePreviousStep = () => {
        if (currentStep > 1) {
            setCurrentStep((prev) => (prev - 1) as 1 | 2 | 3);
        }
    };

    const renderStep1 = () => {
        const categories = categoriesData?.results?.data || [];
        const brands = brandsData?.results?.brands || [];

        if (categoriesLoading) {
            return <div>در حال بارگذاری دسته‌بندی‌ها...</div>;
        }

        return (
            <Step1Form
                onSubmit={handleStep1Submit}
                brands={brands}
                categories={categories}
                loading={updateProductDetailMutation.isPending}
                initialData={{
                    category: productData.category,
                    brand: productData.brand,
                    model: productData.model,
                    title_fa: productData.title_fa,
                    title_en: productData.title_en,
                    seoTitle: productData.seoTitle,
                    source: productData.source,
                    isFake: productData.isFake,
                }}
            />
        );
    };

    const renderStep2 = () => (
        <Step2Form
            onSubmit={handleStep2Submit}
            loading={updateProductAttributeMutation.isPending}
            onPrevious={handlePreviousStep}
            categoryId={productData.category}
            initialData={{
                attributes: productData.attributes,
                description: productData.description,
                metaDescription: productData.metaDescription,
                tags: productData.tags,
                advantages: productData.advantages,
                disAdvantages: productData.disAdvantages,
            }}
        />
    );

    const renderStep3 = () => (
        <Step3Form
            onSubmit={handleStep3Submit}
            loading={updateProductMutation.isPending}
            onPrevious={handlePreviousStep}
            initialData={{
                imagesList: productData.imagesList,
                coverImage: productData.coverImage,
            }}
        />
    );

    return (
        <div>
            <div className="mb-8">
                <h1 className="text-2xl font-bold text-gray-900 mb-2">بروزرسانی محصول</h1>
                <div className="flex items-center justify-center space-x-8">
                    <StepIndicator step={1} currentStep={currentStep} title="جزئیات محصول" />
                    <StepIndicator step={2} currentStep={currentStep} title="ویژگی‌ها و توضیحات" />
                    <StepIndicator step={3} currentStep={currentStep} title="تصاویر و ذخیره" />
                </div>
            </div>

            <div className='flex-1 text-sm bg-white py-8 xl:px-10 px-6 rounded-3xl'>
                {currentStep === 1 && renderStep1()}
                {currentStep === 2 && renderStep2()}
                {currentStep === 3 && renderStep3()}
            </div>
        </div>
    );
};

export default UpdateProduct;