"use client";
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { useForm } from "react-hook-form";
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from "zod";
import { useTranslations } from "next-intl";
import { Input } from "@/components/ui/input";
import CustomBreadcrumb from "@/app/ui/shared/CustomBreadcrumb";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import PasswordInput from "../../ui/form/PassowrdInput";
import CustomPhoneInput from "../../ui/shared/CustomPhoneInput";
import { Checkbox } from "@/components/ui/checkbox";
import CountrySelect from "../../ui/shared/CountrySelect";
import postData from "@/api/post-data";
import getCountryId from "@/api/countries/getCountryId";
import SubmitButton from "../../ui/shared/SubmitButton";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { useRouter } from "next/navigation";
import Link from "next/link";
import clsx from "clsx";
import { useSettings } from "@/stores/settings";
import { useEffect, useState } from "react";
import ReCAPTCHA from "react-google-recaptcha";



export default function SignUp() {
   const t = useTranslations("sign-up");
   const error = useTranslations("form-errors");
   const label = useTranslations("form-labels");
   const router = useRouter();
   const [captcha, setCaptcha] = useState();
   const [captchaError, setCaptchaError] = useState(false);
   const [captchaState, setCaptchaState] = useState(0);

   const { settings } = useSettings();
   useEffect(() => {
      setCaptchaState(settings?.site_settings?.captcha_enabled)
   }, [settings?.site_settings?.captcha_enabled])
   const form = useForm({
      resolver: zodResolver(z.object({
         name: z.string({ message: error('required') }).min(3, { message: error('min3') }).max({ message: error('max32') }),
         lastname: z.string({ message: error('required') }).min(3, { message: error('min3') }).max({ message: error('max32') }),
         email: z.string({ message: error('required') }).email({ message: error('email') }),
         phone: z.string({ errorMap: () => ({ message: error('mobile') }) }).min(10).max(16),
         country_id: z.string({ errorMap: () => ({ message: error('required') }) }).min(1),
         gender: z.string({ errorMap: () => ({ message: error('required') }) }).min(1),
         accpet_terms: z.boolean().refine((value) => value),
         password: z.string({ message: error('required') }).min(6, { message: error('min6') }).max({ message: error('max64') }),
         password_confirmation: z.string({ message: error('required') }).min(6, { message: error('min6') }).max({ message: error('max64') })
      }).refine((data) => data.password === data.password_confirmation, {
         message: error('confirm-password'),
         path: ['password_confirmation']
      }))
   });
   const { formState: { isSubmitting, isSubmitted }, setError } = form; // Get form helpers
   async function onSubmit(values) {
      if (!captcha && captchaState == 1) {
         setCaptchaError(true); // Show error if captcha is not filled
         return; // Prevent form submission
      }
      // delete values.password_confirmation; // Remove password_confirmation from data
      values.country_id = await getCountryId(values.country_id);
      const formData = new FormData();
      for (const [key, value] of Object.entries(values)) { // Replace data to FormData().
         formData.append(key, value);
      }
      // Registry Api
      const { error, data, message, status } = await postData({
         endPoint: '/user/register/affiliate',
         body: formData
      });

      if (error) {
         if (message === 'Register invalid') {
            for (const [key, value] of Object.entries(data)) {
               setError(key, {
                  type: "server",
                  message: value
               }, { shouldFocus: true })
            }
            return;
         }
         toastError(message);

         return;
      }

      toastSuccess(message);
      router.push('/sign-in');
   }

   return (
      <>
         <CustomBreadcrumb />
         <section className="max-md:mx-4 mt-12 mb-20 rounded-lg p-4 md:p-8 shadow-lg md:w-1/2 mx-auto">
            <div className="space-y-2 mb-12">
               <h1 className="font-bold text-xl text-center md:text-2xl lg:text-3xl text-dark">{t('title')}</h1>
            </div>
            <Form {...form}>
               <form method="post" onSubmit={form.handleSubmit(onSubmit)} className='space-y-4'>
                  <FormField
                     name='name'
                     control={form.control}
                     render={({ field }) => (
                        <FormItem>
                           <FormControl>
                              <Input className="focus-visible:ring-main" placeholder={label('first-name')} {...field} />
                           </FormControl>
                           <FormMessage />
                        </FormItem>
                     )}
                  />
                  <FormField
                     name='lastname'
                     control={form.control}
                     render={({ field }) => (
                        <FormItem>
                           <FormControl>
                              <Input className="focus-visible:ring-main" placeholder={label('last-name')} {...field} />
                           </FormControl>
                           <FormMessage />
                        </FormItem>
                     )}
                  />
                  <FormField
                     name='email'
                     control={form.control}
                     render={({ field }) => (
                        <FormItem>
                           <FormControl>
                              <Input className="focus-visible:ring-main" placeholder={label('email')} {...field} />
                           </FormControl>
                           <FormMessage />
                        </FormItem>
                     )}
                  />
                  <FormField
                     name='country_id'
                     control={form.control}
                     render={({ field }) => (
                        <FormItem>
                           <FormControl>
                              <CountrySelect
                                 value={field.value}
                                 onChange={field.onChange}
                                 placeholder={label('country')}
                                 className="focus:border-main focus:border-2"
                              />
                           </FormControl>
                           <FormMessage />
                        </FormItem>
                     )} />
                  <FormField
                     name='phone'
                     control={form.control}
                     render={({ field }) => (
                        <FormItem>
                           <FormControl>
                              <CustomPhoneInput
                                 value={field.value}
                                 valueOnChange={field.onChange}
                                 placeholder={label('mobile')}
                                 className={'flex gap-2'}
                              />
                           </FormControl>
                           <FormMessage />
                        </FormItem>
                     )}
                  />
                  <FormField
                     name="gender"
                     control={form.control}
                     render={({ field }) => (
                        <FormItem className="flex items-end gap-4 space-y-0">
                           <FormLabel>{label('gender')}</FormLabel>
                           <FormControl>
                              <RadioGroup
                                 onValueChange={field.onChange}
                                 defaultValue={field.value}
                                 className="flex gap-2 items-center"
                              >
                                 <FormItem className="flex items-center gap-3">
                                    <FormLabel>{label('male')}</FormLabel>
                                    <FormControl>
                                       <RadioGroupItem value="male" />
                                    </FormControl>
                                 </FormItem>
                                 <FormItem className="flex items-center gap-3">
                                    <FormLabel>{label('female')}</FormLabel>
                                    <FormControl>
                                       <RadioGroupItem value="female" />
                                    </FormControl>
                                 </FormItem>
                              </RadioGroup>
                           </FormControl>
                           <FormMessage />
                        </FormItem>
                     )}
                  />
                  <FormField
                     name='password'
                     control={form.control}
                     render={({ field }) => (
                        <FormItem>
                           <FormControl>
                              <PasswordInput field={field} placeholder={label('password')} />
                           </FormControl>
                           <FormMessage />
                        </FormItem>
                     )}
                  />
                  <FormField
                     name='password_confirmation'
                     control={form.control}
                     render={({ field }) => (
                        <FormItem>
                           <FormControl>
                              <PasswordInput field={field} placeholder={label('confirm-password')} />
                           </FormControl>
                           <FormMessage />
                        </FormItem>
                     )}
                  />
                  <FormField
                     name='accpet_terms'
                     control={form.control}
                     render={({ field }) => (
                        <FormItem className="flex text-sm items-end gap-2">
                           <FormLabel>
                              <Link href="/terms-and-conditions" className={clsx('text-main underline', {
                                 'text-red-500': isSubmitted && !field.value
                              })}>
                                 {label('privacy')}
                              </Link>
                           </FormLabel>
                           <FormControl>
                              <Checkbox
                                 checked={field.value}
                                 onCheckedChange={field.onChange}
                                 className="border-btnColor text-btnColor"
                              />
                           </FormControl>
                        </FormItem>
                     )}
                  />
                  {/* RECAPTCHA */}
                  {captchaState == 1 && (<ReCAPTCHA
                     sitekey={process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY}
                     onChange={(value) => {
                        setCaptcha(value);
                        setCaptchaError(false); // Clear error if captcha is filled
                     }}
                  />
                  )}
                  {captchaError && <p className="text-red-500 text-sm">
                     {error('captchaerror')}</p>}

                  <SubmitButton text={label('create-account')} loading={isSubmitting} />
                  <FormDescription className="text-center">
                     {t('have-account')} <Link href="/sign-in" className="text-main underline">{t('sign-in')}</Link>
                  </FormDescription>
               </form>
            </Form>
         </section>
      </>
   );
}