import { useMemo, useState } from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";
import { ErrorMessage, Form, Formik } from "formik";
import { RequiredField, YupObject } from "@/Utils/ValidationSchema";
import ValidationMsg from "@/Utils/ValidationSchema/ValidationMsg";
import usePost from "@/Utils/Hooks/usePost";
import { AdminPaymentAPI, CommonUploadAPI, DisputeAPI, InfluencerPaymentMethodListAPI } from "@/Utils/APIRequest/Endpoints";
import { CustomToast } from "@/Utils/CustomToast";
import { RiDeleteBin2Line, RiUpload2Fill, RiUploadCloud2Line } from "react-icons/ri";
import Modal from "@/Component/Common/Modal";
import FormLabel from "@/Component/Common/Forms/FormLabel";
import FormikSelect from "@/Component/Common/Forms/FormikSelect";
import FormikTextarea from "@/Component/Common/Forms/FormikTextarea";
import { CloseModalSVG, LoaderSVG } from "@/Component/Common/SVGs/CommonSVG";
import BorderButton from "@/Component/Common/Forms/BorderButton";
import GradientButton from "@/Component/Common/Forms/GradientButton";
import FormikInput from "@/Component/Common/Forms/FormikInput";
import { useQuery } from "@tanstack/react-query";
import CustomFetch from "@/Utils/APIRequest/AxiosInstance";
import ImageWithFallback from "@/Component/Common/ImageWithFallback";
import { PaymentMethodField } from "@/Component/Admin/AdminPaymentMethod/types";

const AdminPaymentModal = (props) => {
    const { modal, setModal, refetch } = props;
    const isReadOnly = !!modal?.isReadOnly;

    const [selectedMethodId, setSelectedMethodId] = useState<string | null>(null);
    const influencerId = modal?.influencer?.id;
    // const [uploadedFiles, setUploadedFiles] = useState<any>([]);

    // Post  API
    const { isPending, mutate } = usePost(`${AdminPaymentAPI}/${modal?.id}`, null, (response) => {
        if (response?.status == 200 || response?.status == 201) {
            refetch();
            setModal(null);
            CustomToast("success", "Payment successful");
        }
    }, 'patch');

    const { data: paymentMethodApiData, isPending: paymentMethodLoading } = useQuery({
        queryKey: [InfluencerPaymentMethodListAPI, influencerId],
        queryFn: () => CustomFetch({ url: InfluencerPaymentMethodListAPI, params: { user_id: influencerId } }, null, false),
        enabled: !!influencerId,
        refetchOnWindowFocus: false
    });

    const rawMethodList = useMemo(() => {
        const rawData = paymentMethodApiData?.data?.data?.countryPaymentMethods;
        return Array.isArray(rawData) ? rawData : [];
    }, [paymentMethodApiData]);

    const methods = useMemo(() => {
        const list: any[] = [];
        rawMethodList.forEach((item: any) => {
            if (item?.payment_method?.is_active) {
                if (!list.find((m) => String(m.id) === String(item.payment_method.id))) {
                    list.push(item.payment_method);
                }
            }
        });
        return list;
    }, [rawMethodList]);

    const defaultMethodId = useMemo(() => {
        const saved = rawMethodList.find((item: any) =>
            item?.influencerValue &&
            typeof item.influencerValue === 'object' &&
            Object.keys(item.influencerValue).length > 0
        );
        return saved?.payment_method?.id ? String(saved?.payment_method?.id) : null;
    }, [rawMethodList]);

    const activeMethodId = selectedMethodId ?? defaultMethodId;

    const selectedPaymentMethod = useMemo(() => {
        if (!activeMethodId) return null;
        return methods.find((m: any) => String(m.id) === String(activeMethodId)) || null;
    }, [activeMethodId, methods]);

    const selectedMethodValues = useMemo(() => {
        if (!activeMethodId) return {};
        const selectedData = rawMethodList.find(
            (item: any) =>
                String(item?.payment_method?.id) === String(activeMethodId) &&
                item?.influencerValue &&
                typeof item.influencerValue === 'object'
        );
        return selectedData?.influencerValue || {};
    }, [activeMethodId, rawMethodList]);

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

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

    //         const maxSize = 5 * 1024 * 1024; // 5 MB in bytes
    //         const allowedTypes = ["image/jpeg", "image/png", "application/pdf"];

    //         if (!allowedTypes.includes(file.type)) {
    //             CustomToast("error", "Only JPEG, PNG, and PDF files are allowed.");
    //             return;
    //         }

    //         // Check file size
    //         if (file.size > maxSize) {
    //             CustomToast("error", "File size must be 5 MB or less.");
    //             return;
    //         }

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

    //         mutateUploadFile(formData);
    //     }
    // };

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

    return (
        <Modal modalSize="md:w-2/4 xl:w-1/3 2xl:w-1/4" modal={modal} setModal={setModal} childMainClass="max-h-[90vh] overflow-y-auto">
            <h3 className="text-3xl font-semibold mb-5">Payment to {modal?.influencer?.first_name} {modal?.influencer?.last_name}</h3>
            {isReadOnly && (<button className="absolute -top-4 -right-4 " onClick={() => setModal(null)}>
                <CloseModalSVG />
            </button>
            )}
            <Formik
                enableReinitialize
                initialValues={{
                    amount: modal?.influencer_payable_amount,
                    comment: "",
                }}
                validationSchema={YupObject({
                    // comment: RequiredField('Comment is required'),
                })}
                onSubmit={(values: any) => {
                    if (isReadOnly) return;

                    // if (uploadedFiles.length === 0) {
                    //     CustomToast("error", "Please upload at least one file.");
                    //     return;
                    // }
                    const preparedValues: any = { ...values }
                    const formattedValues = {
                        ...preparedValues,
                        invoice_receipt: '',
                    };
                    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={`Payable Amount (${modal?.currency})`} />
                                <div className="relative">
                                    <FormikInput inputProps={{ type: "text", name: "amount", autoComplete: "new-email", readOnly: true }} />
                                </div>
                                <ErrorMessage name="reason" component="div" render={(msg) =>
                                    <ValidationMsg errorMsg={msg} />
                                } />
                            </div>
                            {!isReadOnly && (
                                <div className="flex flex-col col-span-12">
                                    <FormLabel title="Comment" />
                                    <FormikTextarea textareaProps={{ type: "text", name: "comment", autoComplete: "new-email", placeholder: "Enter comment", rows: 3, readOnly: isReadOnly, disabled: isReadOnly }} />
                                    {/* <ErrorMessage name="comment" component="div" render={(msg) =>
                                    <ValidationMsg errorMsg={msg} />
                                } /> */}
                                </div>
                            )}

                            <div className="flex flex-col col-span-12">
                                <h4 className="text-base font-medium mb-3">Payment Method Details</h4>
                                {paymentMethodLoading ? (
                                    <p>Loading payment methods...</p>
                                ) : (
                                    <>
                                        <div className="w-full mb-4">
                                            {/* <FormLabel title="Payment Method" /> */}
                                            <select
                                                value={activeMethodId || ""}
                                                onChange={(e) => setSelectedMethodId(e.target.value || null)}
                                                className="appearance-none border border-lightGray rounded-xl w-full py-2.5 px-4 pr-4 sm:text-base text-sm text-darkGray font-medium placeholder:text-white/50 bg-transparent placeholder:font-normal focus:outline-none  focus-visible:outline-none bg-[url('/assets/images/select-arrow.svg')] bg-no-repeat bg-[95%] *:bg-white *:px-2 *:py-1 bg-white"
                                            >
                                                <option value="">Select Payment Method</option>
                                                {methods.map((method: any) => (
                                                    <option key={method.id} value={method.id}>{method.name}</option>
                                                ))}
                                            </select>
                                        </div>

                                        {selectedPaymentMethod?.json_text?.length > 0 && (
                                            <div className="grid grid-cols-12 md:gap-y-4 gap-y-3 gap-x-3 mb-2">
                                                {selectedPaymentMethod.json_text.map((field: PaymentMethodField) => {
                                                    const fieldValue = selectedMethodValues?.[field.key];

                                                    if (field.type === 'image') {
                                                        return (
                                                            <div key={field.key} className="col-span-12 sm:col-span-6">
                                                                <FormLabel title={field.label} />
                                                                <div className="w-24 h-24 bg-lightSecondary rounded-lg relative flex items-center justify-center overflow-hidden">
                                                                    <ImageWithFallback
                                                                        src={fieldValue}
                                                                        alt={field.label}
                                                                        className="w-full h-full object-cover"
                                                                        height={120}
                                                                        width={120}
                                                                    />
                                                                </div>
                                                            </div>
                                                        );
                                                    }

                                                    if (field.type === 'checkbox') {
                                                        return (
                                                            <div key={field.key} className="col-span-12 sm:col-span-6">
                                                                <div className="flex items-center gap-2 mt-8">
                                                                    <input type="checkbox" checked={!!fieldValue} readOnly disabled className="w-4 h-4 rounded border-gray-300" />
                                                                    <label className="text-sm font-medium">{field.label}</label>
                                                                </div>
                                                            </div>
                                                        );
                                                    }

                                                    if (field.type === 'select') {
                                                        return (
                                                            <div key={field.key} className="col-span-12 sm:col-span-6">
                                                                <FormLabel title={field.label} />
                                                                <FormikSelect
                                                                    selectProps={{
                                                                        value: fieldValue || '',
                                                                        disabled: true,
                                                                        name: field.key
                                                                    }}
                                                                >
                                                                    <option value="">Select {field.label}</option>
                                                                    {field.options?.map((option: string, idx: number) => (
                                                                        <option key={idx} value={option}>{option}</option>
                                                                    ))}
                                                                </FormikSelect>
                                                            </div>
                                                        );
                                                    }

                                                    return (
                                                        <div key={field.key} className="col-span-12 sm:col-span-6">
                                                            <FormLabel title={field.label} />
                                                            <FormikInput
                                                                inputProps={{
                                                                    type: 'text',
                                                                    value: fieldValue || '',
                                                                    readOnly: true,
                                                                    disabled: true,
                                                                    name: field.key
                                                                }}
                                                            />
                                                        </div>
                                                    );
                                                })}
                                            </div>
                                        )}
                                    </>
                                )}
                            </div>

                            {/* <div className="flex flex-col col-span-12">
                                <FormLabel title="Upload Payment Receipt" />
                                {uploadedFiles.length > 0 &&
                                    <ul className="flex items-center gap-2 col-span-12 flex-wrap mb-3">
                                        {uploadedFiles.map((file, index) => (
                                            <li
                                                key={index}
                                                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>
                                }
                                {uploadedFiles.length == 0 &&
                                <div className="relative border border-gray rounded-lg flex items-center justify-center flex-col p-5">
                                    <RiUploadCloud2Line className="text-3xl text-gray mb-2.5" />
                                    <input type='file' hidden id='invoice_receipt' accept=".jpg,.jpeg,.png,.pdf" 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="invoice_receipt" className={`px-2.5 py-1 text-lg text-white bg-primary cursor-pointer flex items-center justify-center max-w-32 rounded-md gap-1.5 ${uploadLoader ? 'pointer-events-none' : ''}`}>
                                        Add Files
                                        {uploadLoader && <LoaderSVG />}
                                    </label>
                                    <span className="text-gray mt-2.5">Accept JPG, JPEG, PNG, PDF</span>
                                </div>}
                            </div> */}
                            {!isReadOnly && (
                                <div className="flex items-center justify-end gap-3.5 col-span-12">
                                    <BorderButton buttonType="button" title="Cancel" onClick={() => setModal(false)} />
                                    <GradientButton buttonType="submit" customClass="flex items-center justify-center gap-1.5" disabled={isPending} >
                                        Submit
                                        {isPending && <LoaderSVG />}
                                    </GradientButton>
                                </div>
                            )}
                        </Form>
                    );

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

export default AdminPaymentModal
