import { type FC, useState } from 'react';
import { useCreateProductDetail, useCreateProductAttribute, useSaveProduct } 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 { useNavigate } from 'react-router-dom';
import { extractErrorMessage } from '@/helpers/utils';

const CreateProduct: FC = () => {
    const [currentStep, setCurrentStep] = useState<1 | 2 | 3>(1);
    const [productData, setProductData] = useState<Partial<CreateProductDetailRequestType & CreateProductAttributeRequestType & SaveProductRequestType>>({});
    const navigate = useNavigate();
    // API hooks
    const createProductDetailMutation = useCreateProductDetail();
    const createProductAttributeMutation = useCreateProductAttribute();
    const saveProductMutation = useSaveProduct();
    const { data: brandsData } = useGetBrands();
    const { data: categoriesData, isLoading: categoriesLoading } = useGetCategories();

    const handleStep1Submit = (data: CreateProductDetailRequestType) => {
        createProductDetailMutation.mutate(data, {
            onSuccess: (response) => {
                setProductData(prev => ({ ...prev, ...data, productId: response?.results?.draftProduct?.id }));
                setCurrentStep(2);
            },
            onError: (error) => {
                toast.error(extractErrorMessage(error));
            }
        });
    };

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

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

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

        saveProductMutation.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 || [];

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

        return (
            <Step1Form
                onSubmit={handleStep1Submit}
                brands={brands}
                categories={categories}
                loading={createProductDetailMutation.isPending}
            />
        );
    };

    const renderStep2 = () => (
        <Step2Form
            onSubmit={handleStep2Submit}
            loading={createProductAttributeMutation.isPending}
            onPrevious={handlePreviousStep}
            categoryId={productData.category}
        />
    );

    const renderStep3 = () => (
        <Step3Form
            onSubmit={handleStep3Submit}
            loading={saveProductMutation.isPending}
            onPrevious={handlePreviousStep}
        />
    );

    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 CreateProduct;