"use client";
import { InputForm } from '@/components/Form/inputForm';
import { Form, Formik, FormikHelpers, FormikProps } from 'formik';
import { signIn, useSession } from 'next-auth/react';
import React, { useEffect, useState } from 'react';
import { getTranslation } from '../../../../i18n';
import { useRouter } from 'next/navigation';
import { coloredToast } from '@/components/common/ComponetToast';
import Loading from '@/components/layouts/loading';
import { UserCreate, useLazyUserGetDataByIdQuery, useUserUpdateMutation } from '@/services/user';
import Upload from 'rc-upload';
import { checkedImage, convertBase64 } from '@/helpers/convertBase64';
import { truncate } from 'lodash';
import { LoadingForm } from '@/components/Form/loadingForm';
interface imgProps {
    image: string
    file: any
    isError: boolean
    upLoading: boolean
}
export interface FormValues extends UserCreate {

}
export const Profile = () => {
    const { t } = getTranslation();
    const router = useRouter();
    const session = useSession();
    const [uploadImageData, setUploadImageData] = useState<imgProps>({
        image: "",
        file: undefined,
        isError: false,
        upLoading: false

    });
    const [isLoading, setIsLoading] = useState(false);
    const [isShowPassword, setIsShowPassword] = useState(true);
    const [GetData, { currentData, isFetching }] = useLazyUserGetDataByIdQuery();

    useEffect(() => {
        session.data?.user.userInfo.id &&
            GetData({ id: String(session.data?.user.userInfo.id ?? "") }).then((data) => {
                if (data) {
                    setUploadImageData({
                        ...uploadImageData,
                        image: data.data?.info.photo ?? ""
                    })
                }
            })

    }, [session])
    const [UserUpdate, { isLoading: isLoadingUserUpdate }] = useUserUpdateMutation()

    const handleSubmit = async (values: FormValues, { setSubmitting, resetForm }: FormikHelpers<FormValues>) => {

        try {
            setIsLoading(true)
            var formData = new FormData();
            // Object.keys(values).forEach((key) => {
            //     formData.append(key, values[key] as any);
            // });
            formData.append('username', values.username);
            formData.append('email', values.email);
            formData.append('mobile', values.mobile);
            values.password &&
                formData.append('password', values.password);
            formData.append('country', values.country);
            uploadImageData.file &&
                formData.append('files', uploadImageData.file as any);
            formData.append('fullName', values.fullName);

            await UserUpdate({
                id: String(values.id),
                body: formData,

            }).unwrap();
            coloredToast('success', t("updated-successfully"))
            setIsLoading(false);

            resetForm();
        } catch (error: any) {
            setIsLoading(false);
            console.error('Failed to operation :', error);
            if (error && error.message) {
                return coloredToast('danger', t("error-signIn-message"))
            }
            coloredToast('danger', t("error-signIn-message"))
        }

    };
    if (isFetching) {
        return <LoadingForm />
    }


    return (
        <div className="md:col-span-1 m-6 w-full gap-4 flex-col justify-center items-center">
            <div className='flex gap-8 items-center'>
                <div className="w-[90px] h-[90px] bg-white rounded-[59px] border border-zinc-300 justify-center items-center gap-8 inline-flex">
                    {
                        !uploadImageData.isError ? <img className='w-full h-full rounded-full' src={`${uploadImageData.image}`}
                            onError={() => {
                                setUploadImageData({
                                    ...uploadImageData,
                                    isError: true
                                })
                            }}
                        /> :
                            <div className="w-10 h-10 relative">
                                <div className="w-[13.33px] h-[13.33px] left-[13.33px] top-[3.33px] absolute bg-black bg-opacity-90 rounded-full" />
                                <div className="w-[23.33px] h-[13.33px] left-[8.33px] top-[21.67px] absolute bg-black bg-opacity-90 rounded-full" />

                            </div>

                    }
                </div>
                <EditImageProfile setUploadImageData={setUploadImageData} uploadImageData={uploadImageData} />

                <button onClick={() => {
                    setUploadImageData({
                        ...uploadImageData,
                        image: "",
                        file: null,
                        isError: false,

                    })
                }} className="w-12 h-[18px] justify-start items-center gap-1 inline-flex">
                    <div className="w-4 h-4 relative" >
                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <g clip-path="url(#clip0_77_1022)">
                                <path d="M1.19995 4.0062H14.8M5.13275 3.9998V3.6334C5.13275 2.88189 5.43129 2.16115 5.96269 1.62975C6.4941 1.09834 7.21483 0.799805 7.96635 0.799805C8.71787 0.799805 9.43861 1.09834 9.97001 1.62975C10.5014 2.16115 10.8 2.88189 10.8 3.6334V3.9998M6.38235 7.1998V11.9998M9.62395 7.1998V11.9998M11.6 15.1998H4.39995C3.9756 15.1998 3.56864 15.0312 3.26858 14.7312C2.96852 14.4311 2.79995 14.0242 2.79995 13.5998V3.9998H13.2V13.5998C13.2 14.0242 13.0314 14.4311 12.7313 14.7312C12.4313 15.0312 12.0243 15.1998 11.6 15.1998Z" stroke="#F13434" stroke-width="1.28" stroke-linecap="round" stroke-linejoin="round" />
                            </g>
                            <defs>
                                <clipPath id="clip0_77_1022">
                                    <rect width="16" height="16" fill="white" />
                                </clipPath>
                            </defs>
                        </svg>

                    </div>
                    <div className="text-center text-red-500 text-xs font-normal font-['Alexandria'] leading-[18px]">حذف</div>

                </button>
            </div>

            <Formik<FormValues>
                initialValues={{
                    id: currentData?.info.id ?? "",
                    username: String(currentData?.info?.username ?? ""),
                    password: undefined,
                    fullName: String(currentData?.info?.fullName ?? ""),
                    email: String(currentData?.info?.email ?? ""),
                    country: String(currentData?.info?.country ?? ""),
                    mobile: String(currentData?.info?.mobile ?? ""),
                    files: undefined,
                    role: currentData?.info.role ?? "",
                    status: currentData?.info.status ? true : false,
                }}
                onSubmit={handleSubmit}

            >
                {(props: FormikProps<any>) => (
                    <Form className={'flex flex-col gap-4 mt-4'}>
                        <InputForm
                            className="text-black text-opacity-90 text-sm font-normal font-['Alexandria'] leading-[21px] h-[46px] bg-white rounded-[63px] border border-zinc-300"
                            formikProps={props}
                            name={'fullName'}
                            title={t('fullName')}
                            placeholder={t('enter-fullName')}

                        />
                        <InputForm
                            className="text-black text-opacity-90 text-sm font-normal font-['Alexandria'] leading-[21px] h-[46px] bg-white rounded-[63px] border border-zinc-300"
                            formikProps={props}
                            name={'username'}
                            title={t('username')}
                            placeholder={t('enter-username')}

                        />
                        <InputForm
                            className="text-black text-opacity-90 text-sm font-normal font-['Alexandria'] leading-[21px] h-[46px] bg-white rounded-[63px] border border-zinc-300"
                            formikProps={props}
                            name={'email'}
                            title={t('email')}
                            placeholder={t('enter-email')}

                        />
                        <InputForm
                            iconRight={
                                <button
                                    type="button"
                                    className="absolute inset-y-0 ltr:right-0 rtl:left-0 flex items-center px-3"
                                    onClick={() => {
                                        setIsShowPassword((isShowPassword) => !isShowPassword);
                                    }}
                                >
                                    {isShowPassword ? (
                                        <svg className="h-5 w-5 text-gray-500 dark:text-gray-400" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path
                                                d="M2.03555 12.3224C1.96647 12.1151 1.9664 11.8907 2.03536 11.6834C3.42373 7.50972 7.36079 4.5 12.0008 4.5C16.6387 4.5 20.5742 7.50692 21.9643 11.6776C22.0334 11.8849 22.0335 12.1093 21.9645 12.3166C20.5761 16.4903 16.6391 19.5 11.9991 19.5C7.3612 19.5 3.42564 16.4931 2.03555 12.3224Z"
                                                stroke="#0F172A"
                                                strokeWidth="1.5"
                                                strokeLinecap="round"
                                                strokeLinejoin="round"
                                            />
                                            <path
                                                d="M15 12C15 13.6569 13.6569 15 12 15C10.3431 15 9 13.6569 9 12C9 10.3431 10.3431 9 12 9C13.6569 9 15 10.3431 15 12Z"
                                                stroke="#0F172A"
                                                strokeWidth="1.5"
                                                strokeLinecap="round"
                                                strokeLinejoin="round"
                                            />
                                        </svg>
                                    ) : (
                                        <svg className="h-5 w-5 text-gray-500 dark:text-gray-400" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path
                                                d="M3.97993 8.22257C3.05683 9.31382 2.35242 10.596 1.93436 12.0015C3.22565 16.338 7.24311 19.5 11.9991 19.5C12.9917 19.5 13.9521 19.3623 14.8623 19.1049M6.22763 6.22763C7.88389 5.13558 9.86771 4.5 12 4.5C16.756 4.5 20.7734 7.66205 22.0647 11.9985C21.3528 14.3919 19.8106 16.4277 17.772 17.772M6.22763 6.22763L3 3M6.22763 6.22763L9.87868 9.87868M17.772 17.772L21 21M17.772 17.772L14.1213 14.1213M14.1213 14.1213C14.6642 13.5784 15 12.8284 15 12C15 10.3431 13.6569 9 12 9C11.1716 9 10.4216 9.33579 9.87868 9.87868M14.1213 14.1213L9.87868 9.87868"
                                                stroke="#0F172A"
                                                strokeWidth="1.5"
                                                strokeLinecap="round"
                                                strokeLinejoin="round"
                                            />
                                        </svg>
                                    )}
                                </button>


                            }
                            className="text-black text-opacity-90 text-sm font-normal font-['Alexandria'] leading-[21px] h-[46px] bg-white rounded-[63px] border border-zinc-300"
                            formikProps={props}
                            name={'password'}
                            title={t('password')}
                            placeholder={t('enter-password')}
                            props={{
                                type: isShowPassword ? 'password' : 'text'
                            }}

                        />
                        <InputForm
                            className="text-black text-opacity-90 text-sm font-normal font-['Alexandria'] leading-[21px] h-[46px] bg-white rounded-[63px] border border-zinc-300"
                            formikProps={props}
                            name={'country'}
                            title={t('country')}
                            placeholder={t('enter-country')}

                        />
                        <InputForm
                            className="text-black text-opacity-90 text-sm font-normal font-['Alexandria'] leading-[21px] h-[46px] bg-white rounded-[63px] border border-zinc-300"
                            formikProps={props}
                            name={'mobile'}
                            title={t('mobile')}
                            placeholder={t('enter-mobile')}

                        />

                        <button type="submit" className="h-[54px] px-[38px] py-[26px] bg-primary rounded-[96px] justify-center items-center gap-1.5 inline-flex">
                            {isLoading &&
                                <span className="animate-spin border-2 border-white border-l-transparent rounded-full w-5 h-5 ltr:mr-4 rtl:ml-4 inline-block align-middle"></span>
                            }
                            <div className="text-center text-white text-base font-medium font-['Alexandria'] leading-normal">{t("save")}</div>
                        </button>

                    </Form>)}
            </Formik>

        </div>

    )
}



export const EditImageProfile = ({ setUploadImageData, uploadImageData }: {
    uploadImageData: imgProps
    setUploadImageData: React.Dispatch<React.SetStateAction<imgProps>>
}) => {


    return (
        <Upload
            // multiple
            className={` rounded-[40px] hover:text-primary !w-fit border border-black border-opacity-90 hover:border-primary  `}
            type="drag"
            beforeUpload={async (file: any) => {
                const { type, size }: any = checkedImage(file);
                if (type & size) {
                    const base64: any = await convertBase64(file);
                    setUploadImageData({
                        ...uploadImageData,
                        upLoading: true
                    })
                    setTimeout(() => {
                        setUploadImageData({
                            file: file,
                            isError: false,
                            image: base64,
                            upLoading: false
                        })


                    }, 500);
                }
                return false;
            }}
            style={{ display: 'inline-block' }}
        >
            <div className="w-[90px] h-[30px] px-3 py-1.5 rounded-[40px]  justify-start items-start inline-flex">
                <div className="text-center   text-xs font-normal font-['Alexandria'] leading-[18px]">تغيير الصورة</div>
            </div>
        </Upload>

    )
}
