'use client';

import useGlobalStore from '@/config/use-global';
import { sendEmailCode, sendSmsCode } from '@/services/common/common';
import { AiroButton } from '@workspace/airo-ui/components/AiroButton';
import { useCountDown } from 'ahooks';
import { useTranslations } from 'next-intl';
import { useEffect, useState } from 'react';
import { UseFormReturn } from 'react-hook-form';
import { toast } from 'sonner';

interface SendCodeProps {
  type: 'email' | 'phone';
  params: {
    email?: string;
    type?: 1 | 2;
    telephone_area_code?: string;
    telephone?: string;
  };
  form: UseFormReturn<any>; // Add the new form prop
}
export default function SendCode({ type, params, form }: SendCodeProps) {
  const t = useTranslations('auth');
  const { common } = useGlobalStore();
  const { verify_code_interval } = common.verify_code;
  const [targetDate, setTargetDate] = useState<number>();

  useEffect(() => {
    const storedEndTime = localStorage.getItem(`verify_code_${type}`);
    if (storedEndTime) {
      const endTime = parseInt(storedEndTime);
      if (endTime > Date.now()) {
        setTargetDate(endTime);
      } else {
        localStorage.removeItem(`verify_code_${type}`);
      }
    }
  }, [type]);

  const [, { seconds }] = useCountDown({
    targetDate,
    onEnd: () => {
      setTargetDate(undefined);
      localStorage.removeItem(`verify_code_${type}`);
    },
  });

  const setCodeTimer = () => {
    const endTime = Date.now() + verify_code_interval * 1000;
    setTargetDate(endTime);
    toast.success(t('register.sendCode'));
    localStorage.setItem(`verify_code_${type}`, endTime.toString());
  };

  const getEmailCode = async () => {
    // Use form.getValues() to get the latest form data
    const latestValues = form.getValues();
    if (latestValues.email && params.type) {
      await sendEmailCode({
        email: latestValues.email,
        type: params.type,
      });
      setCodeTimer();
    }
  };

  const getPhoneCode = async () => {
    // Use form.getValues() to get the latest form data
    const latestValues = form.getValues();
    if (latestValues.telephone && latestValues.telephone_area_code && params.type) {
      await sendSmsCode({
        telephone: latestValues.telephone,
        telephone_area_code: latestValues.telephone_area_code,
        type: params.type,
      });
      setCodeTimer();
    }
  };

  const handleSendCode = async () => {
    if (type === 'email') {
      await getEmailCode();
    } else {
      await getPhoneCode();
    }
  };
  const disabled =
    seconds > 0 ||
    (type === 'email' ? !params.email : !params.telephone || !params.telephone_area_code);

  return (
    <AiroButton
      type='button'
      variant={'primary'}
      className={'h-[30px] w-[109px]'}
      onClick={handleSendCode}
      disabled={disabled}
    >
      {seconds > 0 ? `${seconds}s` : t('get')}
    </AiroButton>
  );
}
