import {LockOutlined} from "@ant-design/icons";
import {Input} from "antd";
import {useCountDown} from "ahooks";
import {useState} from "react";

import InputContainer from "@/components/form/input-container.tsx";
import {clsx} from "clsx";
import {sendSmsCode} from "@/service/api/user.ts";

type Props = {
	onChange?: (code: string) => void;
	phone?:string;
}

export function useSmsCode() {
	const [targetDate, setTargetDate] = useState<number>();
	const [sending, setSending] = useState<boolean>();
	const [countdown] = useCountDown({
		targetDate,
		onEnd: () => {
			setTargetDate(undefined)
		},
	});
	const sendCode = (phone?:string,interval = 60) => {
		if (countdown > 0 || sending || !phone) return;
		setSending(true)
		sendSmsCode(phone).then(()=>{
			setTargetDate(Date.now() + interval * 1000)
		}).finally(()=>{
			setSending(false)
		})
	}
	return {
		sendCode,
		countdown,
		sending,
	}
}

export default function SmsCode(props:Props) {

	const [targetDate, setTargetDate] = useState<number>();
	const [sending, setSending] = useState<boolean>();
	const [countdown] = useCountDown({
		targetDate,
		onEnd: () => {
			setTargetDate(undefined)
		},
	});
	const handleSendCode = () => {
		if (countdown > 0 || sending || !props.phone) return;
		setSending(true)
		setTimeout(() => {
			setTargetDate(Date.now() + 10 * 1000)
			setSending(false)
		}, 500)
	}
	return (<InputContainer
		prefix={<LockOutlined/>}
		suffix={<span className={clsx(`text-nowrap text-sm ${countdown > 0 || sending || !props.phone ? 'text-gray-400 cursor-not-allowed':'text-blue-500 cursor-pointer'}`)} onClick={handleSendCode}>
			{sending ? '发送中...' : (countdown > 0 ? `${Math.ceil(countdown/1000)} s` : '获取验证码')}
		</span>}>
		<Input style={{borderRadius: 20}} size={'large'} variant={'borderless'}
		       placeholder="请输入验证码" />
	</InputContainer>)
}