import PhoneInput from "react-phone-input-2";
import Select from 'react-select';
import AsyncSelect from 'react-select/async';
import { ErrorMessage, Field } from "formik";
import FormikInput from "@/Component/Common/Forms/FormikInput";
import FormLabel from "@/Component/Common/Forms/FormLabel"
import ValidationMsg from "@/Utils/ValidationSchema/ValidationMsg";
import SkeletonLoader from "@/Layout/SkeletonLoader";
import FormikSelect from "@/Component/Common/Forms/FormikSelect";
import { useSelector } from "react-redux";
import { AppStore } from "@/lib/store";
import FormikTextarea from "../Forms/FormikTextarea";

const AdminUserEditForm = (props) => {
    const { translations, skeletonLoading, handlePhoneChange, values, setFieldValue, UserDetailData, categoryOptions, errors, currentKeyword, setCurrentKeyword, CountryList, keywordOptions, loadKeywordOptions, loadCategoryOptions } = props;
    const loginUserDetails: any = useSelector((state: AppStore) => state.userDetailSlice?.userDetails);

    // const mergedOptions = [
    //     ...(keywordOptions || []),
    //     ...(values.keywords || [])
    // ].filter(
    //     (v, i, arr) =>
    //         arr.findIndex(o => o.value === v.value) === i
    // );

    const mergedCategoryOptions = [
        ...(categoryOptions || []),
        ...(values.industries || [])
    ].filter(
        (v, i, arr) =>
            arr.findIndex(o => o.value === v.value) === i
    );

    return (
        <div className='grid grid-cols-12 sm:gap-5 gap-3.5 xs:mb-7 mb-5'>
            <div className='2xl:col-span-4 lg:col-span-6 col-span-12'>
                <FormLabel title={translations.firstName} skeletonLoading={skeletonLoading} />
                <div className="relative">
                    <FormikInput inputProps={{ type: "text", name: "first_name", placeholder: `${translations.firstNamePlaceholder}`, autoComplete: "new-email" }} skeletonLoading={skeletonLoading} />
                </div>
                <ErrorMessage name="first_name" component="div" render={(msg) =>
                    <ValidationMsg errorMsg={msg} />
                } />
            </div>
            <div className='2xl:col-span-4 lg:col-span-6 col-span-12'>
                <FormLabel title={translations.lastName} skeletonLoading={skeletonLoading} />
                <div className="relative">
                    <FormikInput inputProps={{ type: "text", name: "last_name", placeholder: `${translations.lastNamePlaceholder}`, autoComplete: "new-email" }} skeletonLoading={skeletonLoading} />
                </div>
                {/* <ErrorMessage name="last_name" component="div" render={(msg) =>
                    <ValidationMsg errorMsg={msg} />
                } /> */}
            </div>
            {UserDetailData?.role == 'influencer' &&
                <div className='2xl:col-span-4 lg:col-span-6 col-span-12'>
                    <FormLabel title={translations.displayName} skeletonLoading={skeletonLoading} />
                    <div className="relative">
                        <FormikInput inputProps={{ type: "text", name: "display_name", placeholder: `${translations.displayNamePlaceholder}`, autoComplete: "new-email" }} skeletonLoading={skeletonLoading} />
                    </div>
                    <ErrorMessage name="display_name" component="div" render={(msg) =>
                        <ValidationMsg errorMsg={msg} />
                    } />
                </div>
            }
            <div className='2xl:col-span-4 lg:col-span-6 col-span-12'>
                <FormLabel title={translations.email} skeletonLoading={skeletonLoading} />
                <div className="relative">
                    <FormikInput inputProps={{ type: "text", name: "email", placeholder: `${translations.emailPlaceholder}`, autoComplete: "new-email", disabled: true }} skeletonLoading={skeletonLoading} />
                </div>
                <ErrorMessage name="email" component="div" render={(msg) =>
                    <ValidationMsg errorMsg={msg} />
                } />
            </div>
            <div className="2xl:col-span-4 lg:col-span-6 col-span-12">
                <FormLabel title={translations.mobileNumber} skeletonLoading={skeletonLoading} />
                <div className='grid grid-cols-12 sm:gap-1 gap-2'>
                    <div className="sm:col-span-4 col-span-4 relative">
                        {skeletonLoading ? <SkeletonLoader height={54} rows={1} /> :
                            <PhoneInput country={'hk'} preferredCountries={['hk', 'sg']} value={values['country_code']} onChange={(value, country) => handlePhoneChange(value, country, setFieldValue)} enableSearch={true} disableSearchIcon={true} autoFormat={false} countryCodeEditable={true}
                                containerClass='absolute top-[50%] translate-y-[-50%] left-0 !w-full z-10 !h-full !rounded-2xl border border-neutral-200 bg-white'
                                inputClass='!w-full !bg-transparent !border-0 !h-auto !font-normal focus:outline-none !pl-10 !pointer-events-none !text-sm !text-gray !font-medium !h-full' buttonClass='!bg-transparent hover:!bg-transparent !border-0 !rounded-2xl' dropdownClass='!bg-white' searchClass='!bg-white !w-full !ml-0 !p-2 0' />
                        }
                    </div>
                    <div className="sm:col-span-8 col-span-8">
                        <div className="relative">
                            <FormikInput inputProps={{ type: "text", name: "phone_number", placeholder: `${translations.mobileNumberPlaceholder}`, autoComplete: "new-email" }} skeletonLoading={skeletonLoading} />
                        </div>
                    </div>
                </div>
                <ErrorMessage name="phone_number" component="div" render={(msg) =>
                    <ValidationMsg errorMsg={msg} />
                } />
            </div>

            <div className="2xl:col-span-4 lg:col-span-6 col-span-12">
                <FormLabel title={translations.country} skeletonLoading={skeletonLoading} />
                <div className="relative">
                    {skeletonLoading ? <SkeletonLoader height={54} rows={1} /> :
                        <Select
                            name="country"
                            options={CountryList}
                            className='country-select'
                            classNamePrefix="edit-custom-select"
                            placeholder="Select Country"
                            value={values.country}
                            onChange={(selectedOptions) => {
                                setFieldValue('country', selectedOptions ? [selectedOptions] : []); // Store as an array
                            }}
                        />}
                </div>
                <ErrorMessage name="country" component="div" render={() =>
                    <ValidationMsg errorMsg={errors?.country} />
                } />
            </div>
            <div className='2xl:col-span-4 lg:col-span-6 col-span-12'>
                <FormLabel title={translations?.currency} skeletonLoading={skeletonLoading} />
                <div className="relative">
                    {skeletonLoading ? <SkeletonLoader height={54} rows={1} /> :
                        <FormikSelect customClass="!border-neutral-200 !text-darkGray !rounded-2xl !py-3 !text-sm !font-medium !bg-[95%]" selectProps={{ name: "currency" }} skeletonLoading={skeletonLoading}>
                            <option value={"USD"}>USD</option>
                            <option value={"HKD"}>HKD</option>
                            <option value={"SGD"}>SGD</option>
                        </FormikSelect>}
                </div>
                <ErrorMessage name="currency" component="div" render={(msg) =>
                    <ValidationMsg errorMsg={msg} />
                } />
            </div>
            <div className="2xl:col-span-4 lg:col-span-6 col-span-12">
                <FormLabel title={translations?.gender} skeletonLoading={skeletonLoading} />
                <div className="relative">
                    {skeletonLoading ? <SkeletonLoader height={54} rows={1} /> :
                        <div className="flex items-center gap-3">
                            <label htmlFor='male' className="flex-1 relative cursor-pointer">
                                <Field type="radio" id="male" name="gender" value="male" className="hidden peer" />
                                <span className='peer-checked:bg-gradient-to-br from-secondary to-primary peer-checked:text-white peer-checked:font-medium text-center border border-neutral-200 rounded-2xl w-full block px-2 py-3 text-sm bg-white'>{translations?.male}</span>
                            </label>
                            <label htmlFor='female' className="flex-1 relative cursor-pointer">
                                <Field type="radio" id="female" name="gender" value="female" className="hidden peer" />
                                <span className='peer-checked:bg-gradient-to-br from-secondary to-primary peer-checked:text-white peer-checked:font-medium text-center border border-neutral-200 rounded-2xl w-full block px-2 py-3 text-sm bg-white'>{translations?.female}</span>
                            </label>
                            <label htmlFor='other' className="flex-1 relative cursor-pointer">
                                <Field type="radio" id="other" name="gender" value="other" className="hidden peer" />
                                <span className='peer-checked:bg-gradient-to-br from-secondary to-primary peer-checked:text-white peer-checked:font-medium text-center border border-neutral-200 rounded-2xl w-full block px-2 py-3 text-sm bg-white'>{translations?.other}</span>
                            </label>
                        </div>
                    }
                </div>
                {/* <ErrorMessage name="gender" component="div" render={() =>
                    <ValidationMsg errorMsg={errors?.gender} />
                } /> */}
            </div>

            {UserDetailData?.role == 'brand' &&
                <>
                    <div className='2xl:col-span-4 lg:col-span-6 col-span-12'>
                        <FormLabel title={translations.companyName} skeletonLoading={skeletonLoading} />
                        <div className="relative">
                            <FormikInput inputProps={{ type: "text", name: "company_name", placeholder: `${translations.companyNamePlaceholder}`, autoComplete: "new-email" }} skeletonLoading={skeletonLoading} />
                        </div>
                        <ErrorMessage name="company_name" component="div" render={() =>
                            <ValidationMsg errorMsg={translations.companyNameRequired} />
                        } />
                    </div>
                    <div className='2xl:col-span-4 lg:col-span-6 col-span-12'>
                        <FormLabel title={translations?.businessType} skeletonLoading={skeletonLoading} />
                        <div className="relative">
                            <FormikSelect customClass="!border-neutral-200 !text-darkGray !rounded-2xl !py-3 !text-sm !font-medium !bg-[95%]" selectProps={{ name: "business_type" }} skeletonLoading={skeletonLoading}>
                                <option value={"Agency"}>{translations.agency}</option>
                                <option value={"In House"}>{translations.inHouse}</option>
                                <option value={"Small Business Owner"}>{translations.smallBusinessOwner}</option>
                            </FormikSelect>
                        </div>
                        <ErrorMessage name="content_type" component="div" render={(msg) =>
                            <ValidationMsg errorMsg={msg} />
                        } />
                    </div>
                    <div className='2xl:col-span-4 lg:col-span-6 col-span-12'>
                        <FormLabel title={translations?.workingPeople} skeletonLoading={skeletonLoading} />
                        <div className="relative">
                            <FormikSelect customClass="!border-neutral-200 !text-darkGray !rounded-2xl !py-3 !text-sm !font-medium !bg-[95%]" selectProps={{ name: "working_people" }} skeletonLoading={skeletonLoading}>
                                <option value={"Just Me"}>{translations.justMe}</option>
                                <option value={"2-10"}>2-10</option>
                                <option value={"11-50"}>11-50</option>
                                <option value={"51-500"}>51-500</option>
                                <option value={"500+"}>500+</option>
                            </FormikSelect>
                        </div>
                        <ErrorMessage name="content_type" component="div" render={(msg) =>
                            <ValidationMsg errorMsg={msg} />
                        } />
                    </div>
                    <div className='2xl:col-span-8 col-span-12'>
                        <FormLabel customClass="capitalize" title={translations?.industries} skeletonLoading={skeletonLoading} />
                        <div className="relative">
                            <AsyncSelect
                                isMulti
                                name="industries"
                                defaultOptions={mergedCategoryOptions}
                                loadOptions={loadCategoryOptions}
                                className="basic-multi-select"
                                classNamePrefix="edit-custom-select"
                                placeholder="Select industries"
                                value={values.industries || []}
                                // value={
                                //     values.industries?.filter(option =>
                                //         categoryOptions.some(cat => cat.value === option.value)
                                //     ) || []
                                // }
                                onChange={(selectedOptions) => {
                                    setFieldValue('industries', selectedOptions);
                                }}
                            />
                        </div>
                        <ErrorMessage name="industries" component="div" render={() =>
                            <ValidationMsg errorMsg={errors?.industries} />
                        } />
                    </div>
                </>
            }

            <div className='col-span-12'>
                <FormLabel title={`${UserDetailData?.role == 'influencer' ? translations?.aboutYourself : translations?.aboutCompany}`} skeletonLoading={skeletonLoading} />
                <div className="relative !border-gray border rounded-xl pt-3 bg-white">
                    <FormikTextarea textareaProps={{ name: "about_me", placeholder: `${translations?.campaignRequirementsPlaceholder}...`, rows: 4 }} skeletonLoading={skeletonLoading} customClass="!border-0 pt-0 pr-12 resize-none" />
                </div>
            </div>

            {UserDetailData?.role == 'influencer' &&
                <>
                    <div className='2xl:col-span-6 col-span-12'>
                        <FormLabel title={translations?.categoryHeaderTitle} skeletonLoading={skeletonLoading} />
                        <div className="relative">
                            <AsyncSelect
                                isMulti
                                name="category_ids"
                                defaultOptions={mergedCategoryOptions}
                                loadOptions={loadCategoryOptions}
                                className="basic-multi-select"
                                classNamePrefix="edit-custom-select"
                                placeholder="Select Categories"
                                value={values.category_ids || []}
                                // value={
                                //     values.category_ids?.filter(option =>
                                //         categoryOptions.some(cat => cat.value === option.value)
                                //     ) || []
                                // }
                                onChange={(selectedOptions) => {
                                    setFieldValue('category_ids', selectedOptions);
                                }}
                            />
                        </div>
                        <ErrorMessage name="category_ids" component="div" render={() =>
                            <ValidationMsg errorMsg={errors?.category_ids} />
                        } />
                    </div>
                    <div className='2xl:col-span-6 col-span-12'>
                        <FormLabel title={translations?.keywords} skeletonLoading={skeletonLoading} />
                        <AsyncSelect
                            isMulti
                            defaultOptions={keywordOptions}
                            loadOptions={keywordOptions}
                            name="keywords"
                            className="basic-multi-select"
                            classNamePrefix="edit-custom-select"
                            placeholder="Search Keywords"
                            value={values.keywords || []}
                            onChange={(selectedOptions) => {
                                setFieldValue('keywords', selectedOptions);
                            }}
                        />
                        {/* <Select
                                isMulti
                                name="keywords"
                                options={keywordOptions}
                                className="basic-multi-select"
                                classNamePrefix="edit-custom-select"
                                placeholder="Select Keywords"
                                value={
                                    values.keywords?.filter(option =>
                                        keywordOptions?.some(keyword => keyword.value === option.value)
                                    ) || []
                                }
                                onChange={(selectedOptions) => {
                                    setFieldValue('keywords', selectedOptions);
                                }}
                            /> */}
                        {/* <FormikInput
                            inputProps={{
                                type: "text",
                                name: "keywords_input",
                                placeholder: translations?.keywordsPlaceholder,
                                value: currentKeyword,
                                onChange: (e) => setCurrentKeyword(e.target.value),
                                onKeyDown: (e) => {
                                    if (e.key === "Enter" && currentKeyword.trim() !== "") {
                                        e.preventDefault();
                                        if (!values.keywords.includes(currentKeyword.trim())) {
                                            setFieldValue("keywords", [...values.keywords, currentKeyword.trim()]);
                                        }
                                        setCurrentKeyword("");
                                    }
                                },
                            }}
                        />
                        <div className="flex flex-wrap gap-1 mt-2">
                            {values?.keywords?.map((keyword, index) => (
                                <span
                                    key={index}
                                    className="flex items-center bg-primary text-white px-3 py-1 rounded-md text-sm"
                                >
                                    {keyword}
                                    <button
                                        type="button"
                                        className="ml-2 text-white text-lg"
                                        onClick={() =>
                                            setFieldValue(
                                                "keywords",
                                                values?.keywords?.filter((_, i) => i !== index)
                                            )
                                        }
                                    >
                                        &times;
                                    </button>
                                </span>
                            ))}
                        </div> */}
                    </div>
                </>
            }

            {(loginUserDetails?.role == 'admin' && UserDetailData?.role == 'influencer') &&
                <div className="2xl:col-span-4 lg:col-span-6 col-span-12">
                    <FormLabel title={'Updated By Crone'} skeletonLoading={skeletonLoading} />
                    <div className="relative">
                        {skeletonLoading ? <SkeletonLoader height={54} rows={1} /> :
                            <div className="flex items-center gap-3">
                                <label htmlFor='offline_true' className="flex-1 relative cursor-pointer">
                                    <Field type="radio" id="offline_true" name="is_updated_by_cron" value={true}
                                        checked={values.is_updated_by_cron === true}
                                        onChange={() => setFieldValue("is_updated_by_cron", true)}
                                        className="hidden peer" />
                                    <span className='peer-checked:bg-gradient-to-br from-secondary to-primary peer-checked:text-white peer-checked:font-medium text-center border border-gray rounded-2xl w-full block px-2 py-3 text-sm bg-white'>{translations?.yes}</span>
                                </label>
                                <label htmlFor='offline_false' className="flex-1 relative cursor-pointer">
                                    <Field type="radio" id="offline_false" name="is_updated_by_cron" value={false}
                                        checked={values.is_updated_by_cron === false}
                                        onChange={() => setFieldValue("is_updated_by_cron", false)}
                                        className="hidden peer" />
                                    <span className='peer-checked:bg-gradient-to-br from-secondary to-primary peer-checked:text-white peer-checked:font-medium text-center border border-gray rounded-2xl w-full block px-2 py-3 text-sm bg-white'>{translations?.no}</span>
                                </label>
                            </div>
                        }
                    </div>
                </div>
            }

            {(loginUserDetails?.role == 'admin' && UserDetailData?.role == 'brand') &&
                <div className="2xl:col-span-4 lg:col-span-6 col-span-12">
                    <FormLabel title={translations?.offlinePaymentAllowed} skeletonLoading={skeletonLoading} />
                    <div className="relative">
                        {skeletonLoading ? <SkeletonLoader height={54} rows={1} /> :
                            <div className="flex items-center gap-3">
                                <label htmlFor='offline_forced' className="flex-1 relative cursor-pointer">
                                    <Field type="radio" id="offline_forced" name="offline_payment_allowed" value={"forced"}
                                        checked={values.offline_payment_allowed === "forced"}
                                        onChange={() => setFieldValue("offline_payment_allowed", "forced")}
                                        className="hidden peer" />
                                    <span className='peer-checked:bg-gradient-to-br from-secondary to-primary peer-checked:text-white peer-checked:font-medium text-center border border-gray rounded-2xl w-full block px-2 py-3 text-base'>{translations?.forced}</span>
                                </label>
                                <label htmlFor='offline_yes' className="flex-1 relative cursor-pointer">
                                    <Field type="radio" id="offline_yes" name="offline_payment_allowed" value={"yes"}
                                        checked={values.offline_payment_allowed === "yes"}
                                        onChange={() => setFieldValue("offline_payment_allowed", "yes")}
                                        className="hidden peer" />
                                    <span className='peer-checked:bg-gradient-to-br from-secondary to-primary peer-checked:text-white peer-checked:font-medium text-center border border-gray rounded-2xl w-full block px-2 py-3 text-base'>{translations?.yes}</span>
                                </label>
                                <label htmlFor='offline_no' className="flex-1 relative cursor-pointer">
                                    <Field type="radio" id="offline_no" name="offline_payment_allowed" value={"no"}
                                        checked={values.offline_payment_allowed === "no"}
                                        onChange={() => setFieldValue("offline_payment_allowed", "no")}
                                        className="hidden peer" />
                                    <span className='peer-checked:bg-gradient-to-br from-secondary to-primary peer-checked:text-white peer-checked:font-medium text-center border border-gray rounded-xl w-full block px-2 py-3 text-base'>{translations?.no}</span>
                                </label>
                            </div>
                        }
                    </div>
                </div>
            }
        </div>
    )
}

export default AdminUserEditForm
