import { Form, Formik } from 'formik'
import { RequiredField, YupObject } from "@/Utils/ValidationSchema"
import usePost from "@/Utils/Hooks/usePost"
import { CategoryAPI, CommonUploadAPI } from "@/Utils/APIRequest/Endpoints"
import Modal from '@/Component/Common/Modal'
import FormikInput from '@/Component/Common/Forms/FormikInput'
import ErrorMessages from '@/Utils/ErrorMessages'
import { LoaderSVG } from '@/Component/Common/SVGs/CommonSVG'
import GradientButton from '@/Component/Common/Forms/GradientButton'
import GradientBorderButton from '@/Component/Common/Forms/GradientBorderButton'
import { CustomToast } from '@/Utils/CustomToast'
import BorderButton from '@/Component/Common/Forms/BorderButton'
import FormLabel from '@/Component/Common/Forms/FormLabel'
import { useState, useEffect } from 'react'
import { useTranslation } from '@/Utils/Hooks/useTranslate'
import { ImageLoaderSVG } from '@/Component/Common/SVGs/AuthSVG'
import ImageWithFallback from '@/Component/Common/ImageWithFallback'
import FormikTextarea from '@/Component/Common/Forms/FormikTextarea'
import CustomFetch from '@/Utils/APIRequest/AxiosInstance'
import { useQuery } from '@tanstack/react-query'

const CategoryModal = (props) => {
    const { modal, setModal, refetch } = props;
    const { translations, available } = useTranslation();
    const [imageResponse, setImageResponse] = useState<any>(null);
    const [activeLanguage, setActiveLanguage] = useState<string>('en');

    // Reset imageResponse when modal closes or changes
    useEffect(() => {
        if (!modal) {
            setImageResponse(null);
        }
    }, [modal]);

    // API GET
    const { data: CategoryDetailData, fetchStatus, isPending: CategoryAPIPending, refetch: CategoryAPIRefetch } = useQuery({ queryKey: [CategoryAPI, modal?.id], queryFn: () => CustomFetch({ url: `${CategoryAPI}/${modal?.id}` }, null, false), enabled: !!modal?.id, refetchOnWindowFocus: false, select: (data) => data?.data?.category })

    const { isPending, mutate } = usePost(modal?.id ? `${CategoryAPI}/${modal?.id}` : CategoryAPI, null, (response) => {
        if (response.status == 201 || response.status == 200) {
            CustomToast('success', modal?.id ? 'Category updated successfully' : 'Category added successfully')
            refetch()
            setModal(null)
        }
    }, modal?.id ? 'put' : null);

    const { mutate: mutateUploadFile, isPending: uploadLoader } = usePost(CommonUploadAPI, null, async (response) => {
        if (response?.status === 200 || response?.status === 201) {
            setImageResponse(response?.data);
        }
    }, 'POST');

    const onFileChange = async (event: any) => {
        if (event?.target?.files && event.target.files.length > 0) {
            const file = event.target.files[0];
            const allowedTypes = ['image/png', 'image/jpeg', 'image/jpg'];
            const maxSize = 10 * 1024 * 1024; // 10 MB in bytes

            // Check file type
            if (!allowedTypes.includes(file.type)) {
                CustomToast("error", translations?.onlyImageMessage);
                return;
            }

            // Check file size
            if (file.size > maxSize) {
                CustomToast("error", translations?.fileSizeMessage);
                return;
            }

            let formData: any = new FormData()
            formData.append('file', file);
            formData.append('type', 'category');
            formData.append('root', "images");

            // Call the mutation function
            mutateUploadFile(formData);
        }
    };

    // Initialize form values with multilanguage structure
    const getInitialValues = () => {
        const initialValues: any = {
            tags: CategoryDetailData?.tags ?? modal?.tags ?? ""
        };

        // Initialize title and description for each language from translations array
        available.forEach((lang) => {
            // Find translation object for this language code
            const translation = CategoryDetailData?.translations?.find(
                (t: any) => t.language_code === lang.code
            );

            initialValues[`title_${lang.code}`] = translation?.title ?? "";
            initialValues[`display_title_${lang.code}`] = translation?.display_title ?? "";
            initialValues[`description_${lang.code}`] = translation?.description ?? "";
        });

        return initialValues;
    };

    // Build validation schema - title and display_title required only for English
    const getValidationSchema = () => {
        const schema: any = {};
        available.forEach((lang) => {
            if (lang.code === 'en') {
                schema[`title_${lang.code}`] = RequiredField("Category Title is required");
                schema[`display_title_${lang.code}`] = RequiredField("Category Display Title is required");
            }
        });
        return YupObject(schema);
    };

    return (
        <Modal modalSize="md:w-2/4 xl:w-1/3 2xl:w-1/4" modal={modal} setModal={setModal} headerTitle={`${modal?.id ? "Edit" : "Add"}  Category`} childMainClass='!overflow-y-auto max-h-[80vh]' >
            <Formik
                enableReinitialize
                initialValues={getInitialValues()}
                validationSchema={getValidationSchema()}
                onSubmit={(values: any) => {
                    // Prepare translations array with language_code, title, and description
                    const translationsArray: any[] = [];

                    available.forEach((lang) => {
                        const title = values[`title_${lang.code}`]?.trim() || "";
                        const display_title = values[`display_title_${lang.code}`]?.trim() || "";
                        const description = values[`description_${lang.code}`]?.trim() || "";

                        translationsArray.push({
                            language_code: lang.code,
                            title: title,
                            display_title: display_title,
                            description: description
                        });
                    });

                    let preparedValues = {
                        image: imageResponse?.filepath || CategoryDetailData?.image || "",
                        tags: values.tags || "",
                        translations: translationsArray
                    };

                    (mutate as any)(preparedValues)
                }}
            >
                {({ errors, touched, values }) => (
                    <Form>
                        <div className='flex items-center mb-3'>
                            <div className='w-24 h-24 bg-lightSecondary rounded-full relative flex items-center justify-center overflow-hidden md:mr-6 mr-3'>
                                {
                                    (uploadLoader || (!!modal?.id && CategoryAPIPending)) ?
                                        <ImageLoaderSVG /> :
                                        <ImageWithFallback src={imageResponse?.filepath ? imageResponse?.filepath : (CategoryDetailData?.image || modal?.image)} alt='Profile Image' className='w-full h-full object-cover' height={120} width={120} />
                                }
                            </div>
                            <div className='flex items-center'>
                                <GradientBorderButton buttonType='button' customClass='flex items-center !text-base !capitalize !py-2 !px-6 ' disabled={uploadLoader}>
                                    <input type='file' hidden id='image' accept="image/png, image/jpeg, image/jpg" onChange={onFileChange} />
                                    <label className={`${uploadLoader ? 'cursor-not-allowed' : ''} cursor-pointer`} htmlFor='image'>{uploadLoader ? `${translations?.uploading}...` : translations?.uploadPicture}</label>
                                </GradientBorderButton>
                            </div>
                        </div>

                        {/* Language Tabs */}
                        <div className='mb-4'>
                            <div className="flex items-center border-b border-lightGray">
                                {available.map((lang) => (
                                    <button
                                        key={lang.code}
                                        type="button"
                                        onClick={() => setActiveLanguage(lang.code)}
                                        className={`px-4 py-2 text-sm font-medium transition-colors ${activeLanguage === lang.code
                                            ? 'text-primary border-b-2 border-primary'
                                            : 'text-gray hover:text-black'
                                            }`}
                                    >
                                        {lang.label}
                                    </button>
                                ))}
                            </div>
                        </div>

                        {/* Title Field (Multilanguage) */}
                        <div className='mb-3'>
                            <div className="relative">
                                <FormLabel
                                    title="Enter Category Title"
                                    isRequired={activeLanguage === 'en'}
                                />
                                <FormikInput
                                    skeletonLoading={!!modal?.id && CategoryAPIPending}
                                    inputProps={{
                                        type: "text",
                                        name: `title_${activeLanguage}`,
                                        placeholder: "Enter category title",
                                        maxLength: '40'
                                    }}
                                />
                            </div>
                            <ErrorMessages
                                fieldName={`title_${activeLanguage}`}
                                errors={errors}
                                touched={touched}
                            />
                        </div>

                        {/* Display Title Field (Multilanguage) */}
                        <div className='mb-3'>
                            <div className="relative">
                                <FormLabel
                                    title="Enter Category Display Title"
                                    isRequired={activeLanguage === 'en'}
                                />
                                <FormikInput
                                    skeletonLoading={!!modal?.id && CategoryAPIPending}
                                    inputProps={{
                                        type: "text",
                                        name: `display_title_${activeLanguage}`,
                                        placeholder: "Enter category display title",
                                        maxLength: '40'
                                    }}
                                />
                            </div>
                            <ErrorMessages
                                fieldName={`display_title_${activeLanguage}`}
                                errors={errors}
                                touched={touched}
                            />
                        </div>

                        {/* Description Field (Multilanguage) */}
                        <div className='mb-3'>
                            <div className="relative">
                                <FormLabel title="Enter Description" />
                                <FormikTextarea
                                    skeletonLoading={!!modal?.id && CategoryAPIPending}
                                    textareaProps={{
                                        name: `description_${activeLanguage}`,
                                        placeholder: "Enter description"
                                    }}
                                />
                            </div>
                            <ErrorMessages
                                fieldName={`description_${activeLanguage}`}
                                errors={errors}
                                touched={touched}
                            />
                        </div>

                        {/* Tags Field (General - Not language specific) */}
                        {activeLanguage === "en" && <div className='mb-3'>
                            <div className="relative">
                                <div className='flex items-center gap-1.5'>
                                    <FormLabel title="Enter Category Tags" />
                                    <span className='text-xs text-gray'>(Comma separated)</span>
                                </div>
                                <FormikInput skeletonLoading={!!modal?.id && CategoryAPIPending} inputProps={{ type: "text", name: "tags", placeholder: "Enter category tags" }} />
                            </div>
                            <ErrorMessages fieldName="tags" errors={errors} touched={touched} />
                        </div>}
                        <div className='flex items-center justify-center mt-5'>
                            <GradientButton buttonType={'submit'} customClass={'mr-2 flex justify-center items-center max-w-40'} disabled={isPending}>
                                Submit
                                {isPending && <LoaderSVG customClass='ml-2.5' />}
                            </GradientButton>
                            <BorderButton customClass='flex items-center justify-center' onClick={() => setModal(null)}>
                                Cancel
                            </BorderButton>
                        </div>
                    </Form>
                )}
            </Formik>
        </Modal>
    );
}

export default CategoryModal;
