import { useState } from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { ErrorMessage, Form, Formik } from "formik";
import Modal from "../Modal";
import { RequiredField, YupObject } from "@/Utils/ValidationSchema";
import FormLabel from "../Forms/FormLabel";
import FormikTextarea from "../Forms/FormikTextarea";
import ValidationMsg from "@/Utils/ValidationSchema/ValidationMsg";
import BorderButton from "../Forms/BorderButton";
import GradientButton from "../Forms/GradientButton";
import { LoaderSVG } from "../SVGs/CommonSVG";
import usePost from "@/Utils/Hooks/usePost";
import { CommonUploadAPI, DisputeAPI } from "@/Utils/APIRequest/Endpoints";
import { CustomToast } from "@/Utils/CustomToast";
import FormikSelect from "../Forms/FormikSelect";
import { RiDeleteBin2Line, RiUpload2Fill, RiUploadCloud2Line } from "react-icons/ri";
import { ConvertBytes } from "@/Utils/Other/BytesToMBKB";

const DISPUTE_REASON_OPTIONS = [
    { value: "Request help from customer service", labelKey: "requestHelpFromCustomerService" },
    { value: "Creator is unresponsive", labelKey: "creatorUnresponsive" },
    { value: "Work submitted is incomplete", labelKey: "workSubmittedIncomplete" },
    { value: "Brand unfairly rejected work", labelKey: "brandUnfairlyRejectedWork" },
    { value: "Dispute", labelKey: "dispute" },
    { value: "Draft not proper", labelKey: "draftNotProper" },
    { value: "Post not proper", labelKey: "postNotProper" },
];

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

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

    const AddMemberToGroup = (GUID: string) => {
        if (!GUID) return Promise.resolve();

        const membersList: CometChat.GroupMember[] = [
            new CometChat.GroupMember("admin", CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT),
        ];

        return CometChat.addMembersToGroup(GUID, membersList, []).then(
            (response: Object) => {
                console.log("responseyy", response);
            },
            (error: CometChat.CometChatException) => {
                // Already a member / group quirks should not block filing the dispute
                const code = String(error?.code || '');
                const msg = String(error?.message || '');
                if (
                    code === 'ERR_ALREADY_JOINED' ||
                    code === 'ERR_ALREADY_A_MEMBER' ||
                    /already/i.test(msg)
                ) {
                    return;
                }
                console.log("Something went wrong", error);
                // Still allow dispute API — admin add failure is non-blocking for submit
            }
        );
    };

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

    const handleFileChange = (event) => {
        if (event?.target?.files && event.target.files.length > 0) {
            const file = event.target.files[0];

            console.log(file);
            
            setFileType(file?.type);

            const imageMaxSize = 10 * 1024 * 1024; // 10 MB in bytes
            const docMaxSize = 50 * 1024 * 1024; // 50 MB in bytes
            const videoMaxSize = 500 * 1024 * 1024; // 500 MB in bytes

            const allowedImageTypes = ["image/jpeg", "image/png", "image/webp", "image/svg+xml", "image/heic", "image/heif"];
            const allowedVideoTypes = ["video/mp4", "video/mov", "video/mkv", "video/quicktime", "video/x-msvideo", "video/x-matroska", "video/webm"];
            const allowedDocTypes = ["application/pdf", "application/vnd.oasis.opendocument.presentation", "application/vnd.oasis.opendocument.spreadsheet", "application/vnd.oasis.opendocument.text", "application/vnd.oasis.opendocument.presentation", "application/vnd.oasis.opendocument.spreadsheet", "application/vnd.oasis.opendocument.text", "application/docx", "application/xlsx", "application/pptx", "application/vnd.ms-word", "application/vnd.ms-excel", "application/vnd.ms-powerpoint", "application/rtf", "application/vnd.oasis.opendocument.presentation", "application/vnd.oasis.opendocument.spreadsheet", "application/vnd.oasis.opendocument.text", "application/vnd.oasis.opendocument.presentation", "application/vnd.oasis.opendocument.spreadsheet", "application/vnd.oasis.opendocument.text", "application/docx", "application/xlsx", "application/pptx", "application/vnd.ms-word", "application/vnd.ms-excel", "application/vnd.ms-powerpoint", "application/rtf", "application/docx", "application/xlsx", "application/pptx", "application/vnd.ms-word", "application/vnd.ms-excel", "application/vnd.ms-powerpoint", "application/rtf", "application/docx", "application/xlsx", "application/pptx", "application/vnd.ms-word", "application/vnd.ms-excel", "application/vnd.ms-powerpoint", "application/rtf", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/vnd.openxmlformats-officedocument.presentationml.presentation", "application/vnd.oasis.opendocument.presentation", "application/vnd.oasis.opendocument.spreadsheet", "application/vnd.oasis.opendocument.text", "application/docx", "application/xlsx", "application/pptx", "application/vnd.ms-word", "application/vnd.ms-excel", "application/vnd.ms-powerpoint", "application/rtf"];


            if (![...allowedImageTypes, ...allowedVideoTypes, ...allowedDocTypes].includes(file.type)) {
                CustomToast("error", translations?.draftMediaValidation);
                return;
            }

            // Check file size
            if (allowedImageTypes.includes(file.type) && file.size > imageMaxSize) {
                CustomToast("error", translations?.draftImageValidation.replace(":imageSize", (imageMaxSize / 1024 / 1024)));
                return;
            }

            if (allowedVideoTypes.includes(file.type) && file.size > videoMaxSize) {
                CustomToast("error", translations?.draftVideoValidation.replace(":videoSize", (videoMaxSize / 1024 / 1024)));
                return;
            }

            if (allowedDocTypes.includes(file.type) && file.size > docMaxSize) {
                CustomToast("error", translations?.draftDocValidation.replace(":docSize", (docMaxSize / 1024 / 1024)));
                return;
            }

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

            mutateUploadFile(formData);
        }
    };

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

    return (
        <Modal modalSize="w-full max-sm:max-w-sm md:w-1/2 xl:w-1/3" modal={modal} setModal={setModal} childMainClass="max-h-[90vh] overflow-y-auto">
            <h3 className="text-2xl font-semibold mb-5">{translations?.dispute}</h3>
            <Formik
                enableReinitialize
                initialValues={{
                    reason: modal?.disputeReason ?? "",
                    description: "",
                }}
                validationSchema={YupObject({
                    reason: RequiredField(translations?.reasonValidation),
                    description: RequiredField(translations?.descriptionValidation),
                })}
                onSubmit={async (values: any) => {
                    // if (uploadedFiles.length === 0) {
                    //     CustomToast("error", "Please upload at least one file.");
                    //     return;
                    // }
                    const preparedValues: any = { ...values }
                    preparedValues.campaign_influencer_id = modal?.campaign?.campaignInfluencers?.[0]?.id;
                    preparedValues.campaign_id = modal?.campaign?.id;
                    const formattedValues = {
                        ...preparedValues,
                        attachment: uploadedFiles
                    };

                    // Add admin to CometChat group first, then file the dispute
                    const guid = modal?.campaign?.campaignInfluencers?.[0]?.id;
                    setIsAddingMember(true);
                    try {
                        await AddMemberToGroup(guid);
                        mutate(formattedValues);
                    } finally {
                        setIsAddingMember(false);
                    }
                }}
            >
                {({ 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?.disputeReason} />
                                {modal?.disputeReason ? (
                                    <div className="border border-gray rounded-xl py-3 px-4 text-base font-medium text-black bg-gray/10">
                                        {translations?.[DISPUTE_REASON_OPTIONS.find(o => o.value === modal.disputeReason)?.labelKey ?? ''] ?? modal.disputeReason}
                                    </div>
                                ) : (
                                    <>
                                        <div className="relative">
                                            <FormikSelect customClass="!border-gray !rounded-xl !py-3 !text-lg !font-medium !text-black !bg-[95%]" selectProps={{ name: "reason" }} >
                                                <option value={""} className="!text-gray">{translations?.selectReason}</option>
                                                {DISPUTE_REASON_OPTIONS.map((opt) => (
                                                    <option key={opt.value} value={opt.value}>{translations?.[opt.labelKey] ?? opt.value}</option>
                                                ))}
                                            </FormikSelect>
                                        </div>
                                        <ErrorMessage name="reason" component="div" render={(msg) =>
                                            <ValidationMsg errorMsg={msg} />
                                        } />
                                    </>
                                )}
                            </div>
                            <div className="flex flex-col col-span-12">
                                <FormLabel title={translations?.description} />
                                <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>
                            <div className="flex flex-col col-span-12">
                                <FormLabel title={translations?.uploadSupportingDocuments} />
                                {uploadedFiles.length > 0 &&
                                    <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"
                                            >
                                                <div className="flex flex-col">
                                                    <span className="text-sm 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 className="relative border border-gray rounded-lg flex items-center justify-center flex-col p-5 text-center">
                                    <RiUploadCloud2Line className="text-2xl text-gray mb-2.5" />
                                    <input type='file' hidden id='dispute_attachment' accept=".jpg,.jpeg,.png,.webp,.svg,.pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.txt,.mp4,.mov,.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={`px-2.5 py-1 text-base text-white bg-primary cursor-pointer flex items-center justify-center max-w-32 rounded-md gap-1.5 ${uploadLoader ? 'pointer-events-none' : ''}`}>
                                        {translations?.addFiles}
                                        {uploadLoader && <LoaderSVG />}
                                    </label>
                                    <span className="text-gray mt-2.5 text-sm">{translations?.acceptAllFiles}</span>
                                </div>
                            </div>
                            <div className="flex items-center justify-end gap-3.5 col-span-12">
                                <BorderButton buttonType="button" title={translations?.cancel} onClick={() => setModal(false)} />
                                <GradientButton buttonType="submit" customClass="flex items-center justify-center gap-1.5" disabled={isPending || isAddingMember || uploadLoader} >
                                    {translations?.submitDispute}
                                    {(isPending || isAddingMember) && <LoaderSVG />}
                                </GradientButton>
                            </div>
                        </Form>
                    );

                }}
            </Formik>
        </Modal>
    )
}

export default DisputeModal
