import { memo } from 'react';

import { Button, Form, Input } from 'antd';
import { useTranslation } from 'react-i18next';

import { useResponsive } from '@/hooks/useSize';
import { userConfigModel } from '@/models/userConfigModel';
import { setToken } from '@/utils/authUtils';

import { useAction } from './useAction';

export interface LoginFormProps {
    onSuccess?: () => void;
}

const LoginForm = memo(({ onSuccess }: LoginFormProps) => {
    const { t } = useTranslation();
    const { isMobile } = useResponsive();
    const { setUserConfig } = userConfigModel.useModel();
    const [form] = Form.useForm();
    const { loading, errorMessage, errorKey, handleSubmit } = useAction({
        setToken,
        setUserConfig,
        onSuccess,
    });

    return (
        <Form
            form={form}
            layout="horizontal"
            labelCol={{ flex: '0 0 80px' }}
            className="flex flex-col"
            onFinish={(values) => handleSubmit(values.username, values.password)}
            autoComplete="on"
        >
            <Form.Item
                name="username"
                label={isMobile ? undefined : t('pages.pricing.payFlow.username')}
                rules={[{ required: true, message: t('pages.pricing.payFlow.loginRequired') }]}
            >
                <Input
                    placeholder={t('pages.pricing.payFlow.username')}
                    autoComplete="username"
                    className="bg-white/10 border-white/20 text-white"
                />
            </Form.Item>
            <Form.Item
                name="password"
                label={isMobile ? undefined : t('pages.pricing.payFlow.password')}
                rules={[{ required: true, message: t('pages.pricing.payFlow.loginRequired') }]}
            >
                <Input.Password
                    placeholder={t('pages.pricing.payFlow.password')}
                    autoComplete="current-password"
                    className="bg-white/10 border-white/20 text-white"
                />
            </Form.Item>
            {(errorMessage || errorKey) && (
                <p className="text-red-400 text-sm">
                    {errorMessage ?? t(`pages.pricing.payFlow.${errorKey}`)}
                </p>
            )}
            <Form.Item className="mt-5 mb-0">
                <Button
                    type="primary"
                    htmlType="submit"
                    loading={loading}
                    className="w-full bg-[#0EA5E9] border-none"
                >
                    {t('pages.pricing.payFlow.loginSubmit')}
                </Button>
            </Form.Item>
        </Form>
    );
});

LoginForm.displayName = 'LoginForm';

export default LoginForm;
