import {useState} from "react";
import {useNavigate, useSearchParams} from "react-router-dom";
import type {FormProps} from 'antd';
import {Button, Form, Input} from 'antd';
import {clsx} from "clsx";
import styles from './../style.module.scss'

import useAuth from "@/hooks/useAuth.ts";
import {useSmsCode} from "@/components/form/sms-code.tsx";
import {useTranslation} from "react-i18next";

type FieldType = {
	username?: string;
	password?: string;
};


export default function FormLogin() {
	const {t} = useTranslation()
	const [disabled, setDisabled] = useState(true)
	const [loading, setLoading] = useState(false)
	const [error, setError] = useState<string>()
	const {login} = useAuth();
	const navigate = useNavigate()
	const [params] = useSearchParams()
	const [phone, setPhone] = useState<string>()
	const {sending, countdown, sendCode} = useSmsCode()
	const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
		if(disabled || loading) return
		if (!values.username || !/^1\d{10}$/.test(values.username)) {
			setError(t("login.invalid_username_or_pwd"))
			return
		}
		setLoading(true)
		login(values.username, values.password!).then(() => {
			navigate(params.get('from') || '/')
		}).catch(e => {
			setError(e.message)
		}).finally(() => setLoading(false));
	};

	return (<div className="form">
		<div className={'text-center text-xl pb-6 pt-8'}>{t("login.welcome")}</div>
		<Form<FieldType>
			name="basic"
			style={{maxWidth: 600}}
			initialValues={{remember: true}}
			onFinish={onFinish}
			onValuesChange={(_, values) => {
				setError(undefined)
				setPhone(values.username)
				setDisabled(!values.username || !values.password)
			}}
			autoComplete="off"
		>
			<Form.Item<FieldType> name="username">
				<div className={styles.loginBox}>
					<Input size={'large'} variant={'borderless'} placeholder={t("login.username")}/>
				</div>
			</Form.Item>
			<Form.Item name="password">

				<div className={styles.loginBox}>
					<Input style={{borderRadius: 20}} size={'large'} variant={'borderless'}
					       placeholder={t("login.password")}/>
					<span
						className={clsx(`text-nowrap mr-1 text-sm ${countdown > 0 || sending || !phone ? 'text-gray-400 cursor-not-allowed' : 'text-blue-500 cursor-pointer'}`)}
						onClick={() => sendCode(phone)}>
						{sending ? `${t('login.code_sending')}...` : (countdown > 0 ? `${Math.ceil(countdown / 1000)} s` : t('login.send_sms_code'))}
					</span>
				</div>
			</Form.Item>


			<Form.Item className={"mt-16"}>

				<div className="absolute text-red-500 text-center inset-x-0" style={{top: -34}}>{error}</div>
				<Button loading={loading} type="primary" size={'large'} htmlType="submit"
				        block shape={'round'}>
					{loading ? t("login.loading") : t('login.text')}
				</Button>
			</Form.Item>
		</Form>
	</div>)
}