import BorderButton from '@/Component/Common/Forms/BorderButton';
import FormikInput from '@/Component/Common/Forms/FormikInput';
import FormikSelect from '@/Component/Common/Forms/FormikSelect';
import FormikTextarea from '@/Component/Common/Forms/FormikTextarea';
import FormLabel from '@/Component/Common/Forms/FormLabel';
import GradientButton from '@/Component/Common/Forms/GradientButton';
import Modal from '@/Component/Common/Modal';
import { ImageLoaderSVG } from '@/Component/Common/SVGs/AuthSVG';
import { LoaderSVG } from '@/Component/Common/SVGs/CommonSVG';
import { CommonUploadAPI, TroubleshootAPI } from '@/Utils/APIRequest/Endpoints';
import { CustomToast } from '@/Utils/CustomToast';
import usePost from '@/Utils/Hooks/usePost';
import { RequiredField, YupObject } from '@/Utils/ValidationSchema';
import ValidationMsg from '@/Utils/ValidationSchema/ValidationMsg';
import { ErrorMessage, Form, Formik } from 'formik';
import Link from 'next/link';
import { useState } from 'react';
import { RiAttachment2, RiDeleteBin2Line, RiUploadCloud2Line } from 'react-icons/ri';

const TroubleshootModal = (props) => {
    const { setModal, modal, translations } = props;
    const [uploadedFiles, setUploadedFiles] = useState<any>([]);
    const [fileType, setFileType] = useState(false);

    // Post  API
    const { isPending, mutate } = usePost(TroubleshootAPI, null, (response) => {
        if (response?.status == 200 || response?.status == 201) {
            setModal(null);
            CustomToast("success", `${translations?.issueReported}`);
        }
    }, '');

    const { mutate: mutateUploadFile, isPending: uploadLoader } = usePost(CommonUploadAPI, null, (response) => {
        if (response?.status === 200 || response?.status === 201) {
            const newFile = { fileName: response?.data?.fileName, fileType: fileType, filepath: response?.data?.filepath };
            setUploadedFiles((prevFiles) => [...prevFiles, newFile]);
        }
    }, 'POST')

    const handleFileChange = (event) => {
        if (event?.target?.files && event.target.files.length > 0) {
            const file = event.target.files[0];
            // Define allowed extensions
            const allowedImageTypes = [
                "image/jpeg",
                "image/png",
                "image/heic",
                "image/gif",
                "image/webp"
            ];
            const allowedVideoTypes = [
                "video/mp4", "video/mov", "video/mkv", "video/quicktime", "video/x-msvideo", "video/x-matroska", "video/webm"
            ];

            let fileType: any = allowedImageTypes.includes(file.type)
                ? "image"
                : allowedVideoTypes.includes(file.type)
                    ? "video"
                    : "unknown";

            setFileType(fileType);

            const maxSize = 10 * 1024 * 1024; // 10 MB in bytes
            const allowedTypes = [...allowedImageTypes, ...allowedVideoTypes];


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

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

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

            mutateUploadFile(formData);
        }
    };

    const handleRemoveFile = (fileName) => {
        setUploadedFiles((prevFiles) => prevFiles.filter((file) => file.fileName !== fileName));
    };

    return (
        <Modal modalSize="w-full md:w-2/3 lg:w-1/2 xl:w-1/3 2xl:w-1/4" modal={modal} setModal={setModal} childMainClass="!max-h-[90vh] overflow-y-auto" headerTitle={translations?.troubleshootModalTitle}>
            <h3 className="text-2xl font-semibold mb-5">{translations?.reportIssue}</h3>
            <Formik
                enableReinitialize
                initialValues={{
                    platform: "",
                    handle: "",
                    description: "",
                }}
                validationSchema={YupObject({
                    platform: RequiredField(translations?.platformValidation),
                    handle: RequiredField(translations?.handleValidation),
                    description: RequiredField(translations?.descriptionValidation),
                })}
                onSubmit={(values: any) => {
                    const formattedValues = {
                        ...values,
                        attachments: uploadedFiles
                    };

                    console.log(formattedValues);
                    mutate(formattedValues);
                }}
            >
                {({ values, setFieldValue, errors }) => {
                    return (
                        <Form className="grid grid-cols-12 md:gap-y-5 gap-y-3 gap-x-3">
                            <div className="flex flex-col col-span-12">
                                <FormLabel title={translations?.socialMediaPlatform} isRequired />
                                <div className="relative">
                                    <FormikSelect customClass="!rounded-2xl !py-3 !font-medium !text-black !bg-[95%]" selectProps={{ name: "platform" }} >
                                        <option value={""} className="!text-gray">{translations?.selectPlatform}</option>
                                        <option value={"instagram"}>{translations?.instagram}</option>
                                        <option value={"facebook"}>{translations?.facebook}</option>
                                        <option value={"youtube"}>{translations?.youtube}</option>
                                        <option value={"tiktok"}>{translations?.tiktok}</option>
                                    </FormikSelect>
                                </div>
                                <ErrorMessage name="platform" component="div" render={(msg) =>
                                    <ValidationMsg errorMsg={msg} />
                                } />
                            </div>
                            <div className="flex flex-col col-span-12">
                                <FormLabel title={translations?.yourHandle} isRequired />
                                <div className="relative">
                                    <FormikInput inputProps={{ type: "text", name: "handle", autoComplete: "new-email", placeholder: `${translations?.yourHandlePlaceholder}` }} />
                                </div>
                                <ErrorMessage name="handle" component="div" render={(msg) =>
                                    <ValidationMsg errorMsg={msg} />
                                } />
                            </div>
                            <div className="flex flex-col col-span-12">
                                <FormLabel title={translations?.describeIssue} isRequired />
                                <FormikTextarea textareaProps={{ type: "text", name: "description", autoComplete: "new-email", placeholder: `${translations?.descriptionPlaceholder}`, rows: 3 }} />
                                <ErrorMessage name="description" component="div" render={(msg) =>
                                    <ValidationMsg errorMsg={msg} />
                                } />
                            </div>
                            {uploadedFiles.length > 0 &&
                                <div className="flex flex-col col-span-12">
                                    <ul className="flex items-center gap-2 col-span-12 flex-wrap mb-3">
                                        {uploadedFiles.map((file) => (
                                            <li
                                                key={file.id}
                                                className="bg-lightGray/50 py-1 px-3 rounded-md flex gap-2 text-sm"
                                            >
                                                <div className="flex flex-col">
                                                    <span className="text-xs whitespace-nowrap">{file.fileName}</span>
                                                </div>
                                                <button
                                                    type="button"
                                                    className="text-red-600"
                                                    onClick={() => handleRemoveFile(file.fileName)}
                                                >
                                                    <RiDeleteBin2Line className="text-lg" />
                                                </button>
                                            </li>
                                        ))}
                                    </ul>
                                </div>
                            }
                            <div className="flex items-center justify-between gap-3.5 col-span-12 mb-5">
                                <div className="flex items-center gap-2">
                                    <RiAttachment2 className="text-2xl text-tertiary" />
                                    <input type='file' hidden id='dispute_attachment' accept=".jpg,.jpeg,.png,.heic,.gif,.webp,.mp4,.mov,.webm,.mkv" className="-indent-24 border-b border-black/30 text-black w-full absolute opacity-0 outline-none top-0 left-0 z-50 h-full cursor-pointer p-0" onChange={handleFileChange} />
                                    <label htmlFor="dispute_attachment" className={`cursor-pointer flex items-center justify-center gap-1.5 text-sm ${uploadLoader ? 'pointer-events-none' : ''}`}>
                                        {translations?.addAttachment1}
                                        {uploadLoader && <ImageLoaderSVG />}
                                    </label>
                                </div>
                                <div className="flex items-center justify-end gap-3.5 ">
                                    <BorderButton buttonType="button" title={translations?.cancel} customClass="!rounded-lg" onClick={() => setModal(false)} />
                                    <GradientButton buttonType="submit" customClass="flex items-center justify-center gap-1.5 !rounded-lg" disabled={isPending} >
                                        {translations?.reportError}
                                        {isPending && <LoaderSVG />}
                                    </GradientButton>
                                </div>
                            </div>
                        </Form>
                    );

                }}
            </Formik>
            <Link href="https://www.connector.cc/creator-trouble-shooting" target='_blank' className="text-darkGray hover:underline hover:text-primary text-xs" dangerouslySetInnerHTML={{ __html: translations?.extraLink }}></Link>
        </Modal>
    )
}

export default TroubleshootModal
