import { Link, useNavigate } from "react-router-dom"
import { ComboBox } from "../common/combo-box"
import { Input } from "../common/input"
import { Controller, SubmitHandler, useForm } from "react-hook-form"
import { CitiesType, ComboBoxItems, ProvinceType, RegisterInterface } from "../../types"
import { yupResolver } from "@hookform/resolvers/yup"
import { RegisterSchema } from "../../schema"
import { ErrorComponent } from "../common/error"
import { getProvincesList } from "../../services/api/province"
import { useMutation, useQuery } from "@tanstack/react-query"
import { useEffect, useState } from "react"
import { getCitiesList } from "../../services/api/cities"
import { registerMutation } from "../../services/api/auth"
import { ButtonComponent } from "../common/button"
import toast from "react-hot-toast"
import { handleError } from "../../utility/error-handle"

export const RegisterForm = () => {
    const [provinceData, setProvinceData] = useState<ComboBoxItems[] | []>([])
    const [citiesData, setCitiesData] = useState<ComboBoxItems[] | []>([])
    const navigate = useNavigate()
    const { mutate, isPending } = useMutation({
        mutationFn: registerMutation,
        mutationKey: ["register"]
    })
    const { data: provinces } = useQuery({
        queryFn: getProvincesList,
        queryKey: ["province"]
    })
    const { data: cities } = useQuery({
        queryFn: getCitiesList,
        queryKey: ["cities"]
    })

    const { handleSubmit, formState: { errors }, control, watch } = useForm<RegisterInterface>({
        resolver: yupResolver(RegisterSchema)
    })
    const provinceName: any = watch("province_name");
    const handleRegister: SubmitHandler<RegisterInterface> = async (data) => {
        mutate({
            ...data,
            province_name: data?.province_name?.name,
            city_name: data?.province_name?.name
        },
            {
                onSuccess: () => {
                    toast.success("با موفقیت ثبت نام شدید")
                    navigate("/auth/login")
                },
                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]);

    return (
        <form onSubmit={handleSubmit(handleRegister)}
            className="w-full sm:w-fit sm:min-w-[500px] max-h-screen overflow-y-auto xl:w-1/2 xl:p-0 xl:py-5 p-10 flex flex-col bg-auth-form items-center  gap-y-[42px] rounded-3x rounded-3xl">
            <img src="/svgs/logo/logo.svg" alt="logo" className="auth-logo-size" />
            <div className="flex flex-col w-full md:w-[400px]">
                <div className="flex flex-col gap-y-5">
                    <span className="font-medium text-lg md:text-2xl xl:text-3xl text-primary-text-color">حساب کاربری خود را ایجاد کنید</span>
                    <div className="flex flex-row gap-x-0.5 items-center">
                        <p className="text-secondary-text-color font-normal text-xs md:text-sm">از قبل یک حساب کاربری دارید؟</p>
                        <Link to="/auth/login">
                            <p className="text-primary-color font-bold text-xs md:text-sm cursor-pointer">وارد شوید</p>
                        </Link>
                    </div>
                </div>
                <div className="grid grid-cols-1 gap-y-5 mb-[42px] mt-9">
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-x-4 gap-y-5">
                        <Controller control={control} name="first_name" render={({ field }) => <div>
                            <Input type="text" placeholder="نام" field={field} />
                            <ErrorComponent show={errors.first_name} message={errors.first_name?.message} />
                        </div>} />
                        <Controller control={control} name="last_name" render={({ field }) => <div>
                            <Input type="text" placeholder="نام خانوادگی" field={field} />
                            <ErrorComponent show={errors.last_name} message={errors.last_name?.message} />
                        </div>} />
                    </div>
                    <Controller control={control} name="national_code" render={({ field }) => (<div>
                        <Input type="text" placeholder="کد ملی" field={field} />
                        <ErrorComponent show={errors.national_code} message={errors.national_code?.message} />
                    </div>)} />
                    <div className="flex flex-col lg:flex-row gap-y-5 gap-x-4">
                        <Controller control={control} name="province_name" render={({ field }) => <div>
                            <ComboBox field={field} data={provinceData} />
                            <ErrorComponent show={errors.province_name} message={errors.province_name?.message} />
                        </div>} />
                        <Controller control={control} name="city_name" render={({ field }) => <div>
                            <ComboBox field={field} data={citiesData} />
                            <ErrorComponent show={errors.city_name} message={errors.city_name?.message} />
                        </div>} />
                    </div>
                    <Controller control={control} name="shopName" render={({ field }) => (<div>
                        <Input type="text" placeholder="نام فروشگاه" field={field} />
                        <ErrorComponent show={errors.shopName} message={errors.shopName?.message} />
                    </div>)} />
                    <Controller control={control} name="mobile_number" render={({ field }) => <div>
                        <Input type="number" placeholder="شماره موبایل" field={field} />
                        <ErrorComponent show={errors.mobile_number} message={errors.mobile_number?.message} />
                    </div>} />
                    <Controller control={control} name="password" render={({ field }) => <div>
                        <Input type="password" placeholder="رمز عبور" field={field} />
                        <ErrorComponent show={errors.password} message={errors.password?.message} />
                    </div>} />
                    <Controller control={control} name="password_confirmation" render={({ field }) => <div>
                        <Input type="password" placeholder="تکرار رمز عبور" field={field} />
                        <ErrorComponent show={errors.password_confirmation} message={errors.password_confirmation?.message} />
                    </div>} />
                </div>
                <ButtonComponent title="ثبت نام" pending={isPending} type="submit" />
            </div>
        </form>
    )
}