'use client'

import { Form, Formik } from "formik";
import usePost from "@/Utils/Hooks/usePost";
import { CommonUploadAPI, InfluencerPaymentMethodListAPI } from "@/Utils/APIRequest/Endpoints";
import { CustomToast } from "@/Utils/CustomToast";
import { LoaderSVG } from "@/Component/Common/SVGs/CommonSVG";
import GradientButton from "@/Component/Common/Forms/GradientButton";
import FormLabel from "@/Component/Common/Forms/FormLabel";
import FormikInput from "@/Component/Common/Forms/FormikInput";
import FormikSelect from "@/Component/Common/Forms/FormikSelect";
import { ImageLoaderSVG } from "@/Component/Common/SVGs/AuthSVG";
import ImageWithFallback from "@/Component/Common/ImageWithFallback";
import { useState, useMemo } from "react";
import GradientBorderButton from "@/Component/Common/Forms/GradientBorderButton";
import ErrorMessages from "@/Utils/ErrorMessages";
import * as Yup from "yup";
import { useQuery } from "@tanstack/react-query";
import CustomFetch from "@/Utils/APIRequest/AxiosInstance";
import Loader from "@/Layout/Loader";
import { useTranslation } from "@/Utils/Hooks/useTranslate";
import { PaymentMethodField } from "@/Component/Admin/AdminPaymentMethod/types";

const BankAccount = () => {
    const [selectedMethodId, setSelectedMethodId] = useState<string | null>(null);
    const [currentUploadFieldKey, setCurrentUploadFieldKey] = useState<string | null>(null);
    const { translations } = useTranslation();

    // Fetch payment methods list
    const { data: apiData, isPending: paymentMethodsLoading, refetch } = useQuery({
        queryKey: [InfluencerPaymentMethodListAPI],
        queryFn: () => CustomFetch({ url: InfluencerPaymentMethodListAPI }, null, false),
        refetchOnWindowFocus: false,
    });

    // Process API response
    const rawList = useMemo(() => {
        const rawData = apiData?.data?.data?.countryPaymentMethods;
        return Array.isArray(rawData) ? rawData : [];
    }, [apiData]);

    // Extract unique active payment methods for the dropdown
    const methods = useMemo(() => {
        const list: any[] = [];
        rawList.forEach((item: any) => {
            if (item?.payment_method?.is_active) {
                if (!list.find(m => m.id === item.payment_method.id)) {
                    list.push(item.payment_method);
                }
            }
        });
        return list;
    }, [rawList]);

    // Find which method has saved data and auto-select it on first load
    const defaultMethodId = useMemo(() => {
        const saved = rawList.find((item: any) =>
            item?.influencerValue &&
            typeof item.influencerValue === 'object' &&
            Object.keys(item.influencerValue).length > 0
        );
        return saved?.payment_method?.id || null;
    }, [rawList]);

    // Auto-select the method with saved data on first load
    const activeMethodId = selectedMethodId ?? defaultMethodId;

    // Get selected payment method object
    const selectedPaymentMethod = useMemo(() => {
        if (!activeMethodId) return null;
        return methods.find((m: any) => m.id === activeMethodId) || null;
    }, [activeMethodId, methods]);

    // Get saved influencerValue for the currently selected method
    const savedValues = useMemo(() => {
        if (!activeMethodId) return null;
        const item = rawList.find((i: any) =>
            i?.payment_method?.id === activeMethodId &&
            i?.influencerValue &&
            typeof i.influencerValue === 'object' &&
            Object.keys(i.influencerValue).length > 0
        );
        return item?.influencerValue || null;
    }, [activeMethodId, rawList]);

    // Build initial values for Formik based on selected method + saved data
    const initialValues = useMemo(() => {
        const details: any = {};
        if (selectedPaymentMethod?.json_text) {
            selectedPaymentMethod.json_text.forEach((field: PaymentMethodField) => {
                if (savedValues && savedValues[field.key] !== undefined) {
                    details[field.key] = savedValues[field.key];
                } else {
                    details[field.key] = field.type === 'checkbox' ? false : '';
                }
            });
        }
        return { payment_details: details };
    }, [selectedPaymentMethod, savedValues]);

    // Build dynamic validation schema
    const validationSchema = useMemo(() => {
        if (!selectedPaymentMethod?.json_text) return Yup.object().shape({});

        const schema: any = {};
        selectedPaymentMethod.json_text.forEach((field: PaymentMethodField) => {
            if (field.required) {
                switch (field.type) {
                    case 'email':
                        schema[field.key] = Yup.string().email('Invalid email format').required(`${field.label} is required`);
                        break;
                    case 'number':
                        schema[field.key] = Yup.number().typeError(`${field.label} must be a number`).required(`${field.label} is required`);
                        break;
                    case 'checkbox':
                        schema[field.key] = Yup.boolean().oneOf([true], `${field.label} must be checked`);
                        break;
                    default:
                        schema[field.key] = Yup.string().required(`${field.label} is required`);
                }
            }
        });

        return Yup.object().shape({ payment_details: Yup.object().shape(schema) });
    }, [selectedPaymentMethod]);

    // Save API
    const { isPending, mutate } = usePost(InfluencerPaymentMethodListAPI, null, (response) => {
        if (response?.status == 200 || response?.status == 201) {
            CustomToast("success", "Payment details saved successfully");
            refetch();
        }
    }, '');

    const { mutate: mutateUploadFile, isPending: uploadLoader } = usePost(CommonUploadAPI, null, null, 'POST');

    if (paymentMethodsLoading) return <Loader />

    return (
        <>
            <h2 className="text-primary text-xl mb-2 font-medium leading-6">💳 {translations?.bankAccount}</h2>
            <p className="mb-7 text-sm">{translations?.bankAccountDetails}</p>

            {/* Payment Method Selector - OUTSIDE Formik */}
            <div className='w-full max-w-sm mb-5'>
                <FormLabel title="Payment Method *" />
                <select
                    value={activeMethodId || ""}
                    onChange={(e) => setSelectedMethodId(e.target.value || null)}
                    className="appearance-none border border-lightGray rounded-full w-full py-2.5 px-4 pr-4 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-[90%] bg-white"
                >
                    <option value="">Select Payment Method</option>
                    {methods.map((method: any) => (
                        <option key={method.id} value={method.id}>{method.name}</option>
                    ))}
                </select>
            </div>

            {/* Dynamic Form - key forces fresh Formik when method changes */}
            {selectedPaymentMethod && (
                <Formik
                    key={activeMethodId}
                    initialValues={initialValues}
                    validationSchema={validationSchema}
                    onSubmit={(values) => {
                        const payload = {
                            payment_method_id: activeMethodId,
                            json_data: values.payment_details,
                            is_active: true
                        };
                        console.log('Submitting:', payload);
                        (mutate as any)(payload);
                    }}
                >
                    {({ values, errors, setFieldValue, touched }) => (
                        <Form className='flex-1'>
                            <div className='grid grid-cols-12 sm:gap-5 gap-3.5 xs:mb-7 mb-5'>
                                {selectedPaymentMethod.json_text?.map((field: PaymentMethodField) => {
                                    const fieldName = `payment_details.${field.key}`;
                                    const fieldValue = values.payment_details?.[field.key] ?? '';

                                    switch (field.type) {
                                        case 'select':
                                            return (
                                                <div key={field.key} className='md:col-span-6 col-span-12'>
                                                    <FormLabel title={`${field.label}${field.required ? ' *' : ''}`} />
                                                    <FormikSelect
                                                        selectProps={{
                                                            name: fieldName,
                                                            value: fieldValue,
                                                            onChange: (e: any) => setFieldValue(fieldName, e.target.value)
                                                        }}
                                                    >
                                                        <option value="">Select {field.label}</option>
                                                        {field.options?.map((option: string, optIdx: number) => (
                                                            <option key={optIdx} value={option}>{option}</option>
                                                        ))}
                                                    </FormikSelect>
                                                    <ErrorMessages fieldName={fieldName} errors={errors} touched={touched} />
                                                </div>
                                            );

                                        case 'checkbox':
                                            return (
                                                <div key={field.key} className='md:col-span-6 col-span-12'>
                                                    <div className="flex items-center gap-2">
                                                        <input
                                                            type="checkbox"
                                                            id={fieldName}
                                                            name={fieldName}
                                                            checked={!!fieldValue}
                                                            onChange={(e) => setFieldValue(fieldName, e.target.checked)}
                                                            className="w-4 h-4 rounded border-gray-300"
                                                        />
                                                        <label htmlFor={fieldName} className="text-sm font-medium">
                                                            {field.label}{field.required ? ' *' : ''}
                                                        </label>
                                                    </div>
                                                    <ErrorMessages fieldName={fieldName} errors={errors} touched={touched} />
                                                </div>
                                            );

                                        case 'image':
                                            return (
                                                <div key={field.key} className='md:col-span-6 col-span-12 flex items-center mb-3'>
                                                    <div className='w-24 h-24 bg-lightSecondary rounded-lg relative flex items-center justify-center overflow-hidden md:mr-6 mr-3'>
                                                        {uploadLoader && currentUploadFieldKey === field.key ? (
                                                            <ImageLoaderSVG />
                                                        ) : (
                                                            <ImageWithFallback
                                                                src={fieldValue}
                                                                alt={field.label}
                                                                className='w-full h-full object-cover'
                                                                height={120}
                                                                width={120}
                                                            />
                                                        )}
                                                    </div>
                                                    <div className='flex flex-col gap-2'>
                                                        <FormLabel title={`${field.label}${field.required ? ' *' : ''}`} />
                                                        <GradientBorderButton
                                                            buttonType='button'
                                                            customClass='flex items-center !text-base !capitalize !py-2 !px-6'
                                                            disabled={uploadLoader}
                                                        >
                                                            <input
                                                                type='file'
                                                                hidden
                                                                id={`image-${field.key}`}
                                                                accept="image/png, image/jpeg, image/jpg"
                                                                onChange={async (event) => {
                                                                    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;
                                                                        if (!allowedTypes.includes(file.type)) { CustomToast("error", translations?.onlyImageMessage); return; }
                                                                        if (file.size > maxSize) { CustomToast("error", translations?.fileSizeMessage); return; }
                                                                        setCurrentUploadFieldKey(field.key);
                                                                        let formData: any = new FormData();
                                                                        formData.append('file', file);
                                                                        formData.append('type', 'bank');
                                                                        formData.append('root', "images");
                                                                        (mutateUploadFile as any)(formData, {
                                                                            onSuccess: (response: any) => {
                                                                                if (response?.status === 200 || response?.status === 201) {
                                                                                    setFieldValue(fieldName, response?.data?.filepath);
                                                                                    setCurrentUploadFieldKey(null);
                                                                                }
                                                                            },
                                                                            onError: () => setCurrentUploadFieldKey(null)
                                                                        });
                                                                    }
                                                                }}
                                                            />
                                                            <label
                                                                className={`${uploadLoader ? 'cursor-not-allowed' : ''} cursor-pointer`}
                                                                htmlFor={`image-${field.key}`}
                                                            >
                                                                {uploadLoader && currentUploadFieldKey === field.key ? `${translations?.uploading}...` : `Upload ${field.label}`}
                                                            </label>
                                                        </GradientBorderButton>
                                                        <ErrorMessages fieldName={fieldName} errors={errors} touched={touched} />
                                                    </div>
                                                </div>
                                            );

                                        default:
                                            return (
                                                <div key={field.key} className='md:col-span-6 col-span-12'>
                                                    <FormLabel title={`${field.label}${field.required ? ' *' : ''}`} />
                                                    <FormikInput
                                                        inputProps={{
                                                            type: field.type,
                                                            name: fieldName,
                                                            placeholder: `Enter ${field.label}`,
                                                            value: fieldValue,
                                                            onChange: (e: any) => setFieldValue(fieldName, e.target.value)
                                                        }}
                                                    />
                                                    <ErrorMessages fieldName={fieldName} errors={errors} touched={touched} />
                                                </div>
                                            );
                                    }
                                })}
                            </div>

                            <div className="col-span-12 flex justify-end">
                                <GradientButton buttonType="submit" customClass="gap-2 flex items-center justify-center" disabled={isPending}>
                                    {translations?.saveNow} {isPending && <LoaderSVG />}
                                </GradientButton>
                            </div>
                        </Form>
                    )}
                </Formik>
            )}
        </>
    )
}

export default BankAccount
