'use client';
import useGlobalStore from '@/config/use-global';
import { zodResolver } from '@hookform/resolvers/zod';
import { AiroButton } from '@workspace/airo-ui/components/AiroButton';
import { Button } from '@workspace/airo-ui/components/button';

import { useLoginDialog } from '@/app/auth/LoginDialogContext';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from '@workspace/airo-ui/components/form';
import { Input } from '@workspace/airo-ui/components/input';
import { Icon } from '@workspace/airo-ui/custom-components/icon';
import { useRouter } from 'next/navigation';
import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import SendCode from '../send-code';
import { TurnstileRef } from '../turnstile';

export default function RegisterForm({
  loading,
  onSubmit,
  initialValues,
  setInitialValues,
  onSwitchForm,
}: {
  loading?: boolean;
  onSubmit: (data: any) => void;
  initialValues: any;
  setInitialValues: Dispatch<SetStateAction<any>>;
  onSwitchForm: Dispatch<SetStateAction<'register' | 'reset' | 'login'>>;
}) {
  const { common } = useGlobalStore();
  const router = useRouter();

  const formSchema = z
    .object({
      email: z.string().email('请输入有效的电子邮件地址。'),
      password: z.string().min(1, '请输入密码'), // 必填提示
      repeat_password: z.string().min(1, '请重复输入密码'), // 必填
      code: z.string().min(1, '请输入验证码'), // 必填,
      invite: z.string().nullish(),
    })
    .superRefine(({ password, repeat_password }, ctx) => {
      if (password !== repeat_password) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          message: '两次密码输入不一致',
          path: ['repeat_password'],
        });
      }
    });

  const [inviteDefault, setInviteDefault] = useState('');
  const { openLoginDialog } = useLoginDialog();

  useEffect(() => {
    const invite = localStorage.getItem('invite') || '';
    setInviteDefault(invite);
  }, []);

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      ...initialValues,
      invite: inviteDefault,
    },
  });

  const turnstile = useRef<TurnstileRef>(null);
  const handleSubmit = form.handleSubmit((data) => {
    try {
      onSubmit(data);
    } catch (error) {
      turnstile.current?.reset();
    }
  });

  return (
    <>
      <div className={'h-[84px] text-2xl font-bold leading-[84px] text-white'}>线路优化</div>

      <Form {...form}>
        <form onSubmit={handleSubmit}>
          <div className='grid gap-5'>
            <FormField
              control={form.control}
              name='email'
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <Input
                      className={
                        'h-[46px] rounded-full bg-white shadow-[inset_0_0_7.6px_0_#00000040]'
                      }
                      placeholder='电子邮箱'
                      type='email'
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name='password'
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <Input
                      className={
                        'h-[46px] rounded-full bg-white shadow-[inset_0_0_7.6px_0_#00000040]'
                      }
                      placeholder='设置密码'
                      type='password'
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name='repeat_password'
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <Input
                      className={
                        'h-[46px] rounded-full bg-white shadow-[inset_0_0_7.6px_0_#00000040]'
                      }
                      disabled={loading}
                      placeholder='再次输入密码'
                      type='password'
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            {
              <FormField
                control={form.control}
                name='code'
                render={({ field }) => (
                  <FormItem>
                    <FormControl>
                      <div className='flex items-center gap-8'>
                        <Input
                          disabled={loading}
                          className={
                            'h-[46px] rounded-full bg-white shadow-[inset_0_0_7.6px_0_#00000040]'
                          }
                          placeholder='邮箱验证码'
                          type='text'
                          {...field}
                          value={field.value as string}
                        />
                        <SendCode
                          type='email'
                          form={form}
                          params={{
                            ...form.getValues(),
                            type: 1,
                          }}
                        />
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            }
            <FormField
              control={form.control}
              name='invite'
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <Input
                      className={
                        'h-[46px] rounded-full bg-white shadow-[inset_0_0_7.6px_0_#00000040]'
                      }
                      disabled={loading || !!inviteDefault}
                      placeholder={'邀请码（非必填）'}
                      {...field}
                      value={field.value || ''}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>

          <div className='text-right text-sm'>
            已有账户？&nbsp;
            <Button
              variant='link'
              type='button'
              className='p-0 text-[#225BA9]'
              onClick={() => {
                openLoginDialog();
              }}
            >
              登录
            </Button>
          </div>
          <div className='mt-6 flex justify-center'>
            <AiroButton
              type='submit'
              variant={'default'}
              disabled={loading}
              className='h-auto min-w-[157px] border-[3px] border-white bg-white/10 py-2 text-lg font-medium text-white transition hover:bg-white/25'
            >
              {loading && <Icon icon='mdi:loading' className='animate-spin' />}
              注册
            </AiroButton>
          </div>
        </form>
      </Form>
    </>
  );
}
