import { Input } from "../common/input"
import { DatepickerComponent } from "../common/datepicker"
import { Controller, SubmitHandler, useForm } from "react-hook-form"
import { CitiesType, ComboBoxItems, ProvinceType, UpdateUserInterface } from "../../types"
import { yupResolver } from "@hookform/resolvers/yup"
import { UpdateUserSchema } from "../../schema"
import { ErrorComponent } from "../common/error"
import { ComboBox } from "../common/combo-box"
import { ResetPasswordBox } from "./reset-password-box"
import { useEffect, useState } from "react"
import { getProvincesList } from "../../services/api/province"
import { useMutation, useQuery } from "@tanstack/react-query"
import { getCitiesList } from "../../services/api/cities"
import { useUserStore } from "../../store/user"
import { ButtonComponent } from "../common/button"
import { updateUSerInformations } from "../../services/api/user"
import toast from "react-hot-toast"
import { handleError } from "../../utility/error-handle"
import { ImageUpload } from "../common/upload"

export const MyAccountPage = () => {
    const [selectedImage, setSelectedImage] = useState<any>(null);
    const { user, updateUser } = useUserStore()
    const { mutate, isPending } = useMutation({
        mutationFn: updateUSerInformations,
        mutationKey: ["update-user"]
    })
    const { handleSubmit, formState: { errors }, control, watch, reset } = useForm<UpdateUserInterface>({
        resolver: yupResolver(UpdateUserSchema),
    })
    const provinceName: any = watch("province_name");
    const [provinceData, setProvinceData] = useState<ComboBoxItems[] | []>([])
    const [citiesData, setCitiesData] = useState<ComboBoxItems[] | []>([])
    const { data: provinces } = useQuery({
        queryFn: getProvincesList,
        queryKey: ["province"]
    })
    const { data: cities } = useQuery({
        queryFn: getCitiesList,
        queryKey: ["cities"]
    })

    const handleUpdateUser: SubmitHandler<UpdateUserInterface> = async (data) => {
        let formData = new FormData()
        formData.append("first_name", data?.first_name)
        formData.append("last_name", data?.last_name)
        formData.append("province_name", data?.province_name?.name)
        formData.append("city_name", data?.city_name?.name)
        formData.append("shopName", data?.shopName)
        formData.append("birthDate", data?.birthDate)
        formData.append("address", data?.address)
        formData.append("cell_number", data?.cell_number)
        formData.append("image", selectedImage)
        await mutate({ formData, id: user?.id }, {
            onSuccess: (res: any) => {
                toast?.success("اطلاعات کاربر با موفقیت بروز رسانی شد")
                updateUser(res?.data?.user)
            },
            onError: (err: any) => handleError(err)
        })
    }

    useEffect(() => {
        const tempArray: ComboBoxItems[] = [...provinceData]
        provinces?.data?.data?.map((province: ProvinceType) => tempArray.push({
            id: province?.ProvinceID,
            name: province?.ProvinceName
        }))
        setProvinceData(tempArray)
    }, [provinces])

    useEffect(() => {
        const tempCities: any = []
        const newCities = cities?.data?.data?.filter((city: CitiesType) => city?.ProvinceName?.toLocaleLowerCase()?.includes(provinceName?.name?.toLowerCase()))
        newCities?.map((city: CitiesType) => tempCities?.push({
            id: city?.CityID,
            name: city?.CityName
        }))
        setCitiesData(tempCities)
    }, [provinceName]);


    useEffect(() => {
        reset({
            address: user?.address,
            birthDate: user?.birthDate,
            city_name: { id: 1, name: user?.city_name },
            province_name: { id: 1, name: user?.province_name },
            mobile_number: user?.mobile_number,
            first_name: user?.first_name,
            last_name: user?.last_name,
            national_code: user?.national_code,
            shopName: user?.shopName,
            cell_number: user?.cell_number,
        })
    }, [reset])
    return (
        <div className="w-full h-full flex flex-col gap-10 bg-auth-form rounded-[40px] p-[30px]">
            <form onSubmit={handleSubmit(handleUpdateUser)} className="w-full h-full flex flex-col gap-10 bg-auth-form rounded-[40px]">
                <div className="flex flex-col gap-5 xl:gap-0 xl:flex-row xl:gap-x-10 xl:justify-between items-start">
                    <div className="flex flex-col gap-y-5 w-full xl:max-w-fit">
                        <p className="font-medium text-xl text-primary-text-color">اطلاعات اولیه</p>
                        <p className="font-normal text-base text-secondary-text-color text-wrap xl:max-w-xs">
                            لورم ایپسوم متن ساختگی با تولید سادگی نامفهوم از صنعت چاپ و با استفاده از طراحان گرافیک است چاپگرها و متون
                        </p>
                    </div>
                    <div className="flex flex-col gap-10 w-full">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-[18px]">
                            <Controller name="mobile_number" control={control} render={({ field }) => (
                                <div>
                                    <Input placeholder={user?.mobile_number ? user?.mobile_number : "شماره تماس"} type="number" disabled field={field} />
                                    <ErrorComponent show={errors.mobile_number} message={errors.mobile_number?.message} />
                                </div>
                            )} />
                            <Controller name="shopName" control={control} render={({ field }) => (
                                <div>
                                    <Input placeholder={user?.shopName ? user?.shopName : "نام شرکت"} field={field} />
                                    <ErrorComponent show={errors.shopName} message={errors.shopName?.message} />
                                </div>
                            )} />
                            <Controller name="first_name" control={control} render={({ field }) => (
                                <div>
                                    <Input placeholder={user?.first_name ? user?.first_name : "نام"} field={field} />
                                    <ErrorComponent show={errors.first_name} message={errors.first_name?.message} />
                                </div>
                            )} />
                            <Controller name="last_name" control={control} render={({ field }) => (
                                <div>
                                    <Input placeholder={user?.last_name ? user?.last_name : "نام خانوادگی"} field={field} />
                                    <ErrorComponent show={errors.last_name} message={errors.last_name?.message} />
                                </div>
                            )} />
                            <Controller name="province_name" control={control} render={({ field }) => (
                                <div>
                                    <ComboBox field={field} data={provinceData} placeholder={user?.province_name} />
                                    <ErrorComponent show={errors.province_name} message={errors.province_name?.message} />
                                </div>
                            )} />
                            <Controller name="city_name" control={control} render={({ field }) => (
                                <div>
                                    <ComboBox field={field} data={citiesData} placeholder={user?.city_name} />
                                    <ErrorComponent show={errors.city_name} message={errors.city_name?.message} />
                                </div>
                            )} />
                            <ImageUpload setSelectedImage={setSelectedImage} selectedImage={selectedImage} />
                        </div>
                        <div className="divide-y-2 border" />
                    </div>
                </div>
                <div className="flex flex-col gap-5 xl:gap-0 xl:flex-row xl:gap-x-10 xl:justify-between items-start">
                    <div className="flex flex-col gap-y-5 w-full xl:max-w-fit">
                        <p className="font-medium text-xl text-primary-text-color">اطلاعات تکمیلی</p>
                        <p className="font-normal text-base text-secondary-text-color text-wrap xl:max-w-xs">
                            لورم ایپسوم متن ساختگی با تولید سادگی نامفهوم از صنعت چاپ و با استفاده از طراحان گرافیک است چاپگرها و متون
                        </p>
                    </div>
                    <div className="flex flex-col gap-10 w-full">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-[18px]">
                            <Controller name="address" control={control} render={({ field }) => (
                                <div>
                                    <Input placeholder={user?.address ? user?.address : "آدرس"} field={field} />
                                    <ErrorComponent show={errors.address} message={errors.address?.message} />
                                </div>
                            )} />
                            <Controller name="national_code" control={control} render={({ field }) => (
                                <div>
                                    <Input placeholder={user?.national_code} type="number" field={field} disabled />
                                    <ErrorComponent show={errors.national_code} message={errors.national_code?.message} />
                                </div>
                            )} />
                            <Controller name="cell_number" control={control} render={({ field }) => (
                                <div>
                                    <Input placeholder={user?.cell_number} type="number" field={field} />
                                    <ErrorComponent show={errors.cell_number} message={errors.cell_number?.message} />
                                </div>
                            )} />
                            <Controller name="birthDate" control={control} render={({ field }) => (
                                <div className="flex flex-col gap-y-9">
                                    <DatepickerComponent field={field} placeholder={user?.birthDate} />
                                    <ErrorComponent show={errors.birthDate} message={errors.birthDate?.message} />
                                </div>
                            )} />
                        </div>
                        <div className="divide-y-2 border" />
                    </div>
                </div>
                <div className="flex w-full min-w-max lg:justify-end mt-10">
                    <ButtonComponent type="submit" title="ذخیره" pending={isPending} className="w-full lg:max-w-fit lg:min-w-72" />
                </div>
            </form>
            <ResetPasswordBox />
        </div >
    )
}