import { useEffect } from 'react';

import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';

import useLanguage from '@/locale/useLanguage';

import { Alert, Button, Card, Form, Space, Typography } from 'antd';
import { LockOutlined, ThunderboltOutlined } from '@ant-design/icons';

import { login } from '@/redux/auth/actions';
import { selectAuth } from '@/redux/auth/selectors';
import LoginForm from '@/forms/LoginForm';
import Loading from '@/components/Loading';
import AuthModule from '@/modules/AuthModule';
import { DEMO_LOGIN_EMAIL, DEMO_LOGIN_PASSWORD, DEMO_MODE } from '@/demo/config';

const LoginPage = () => {
  const translate = useLanguage();
  const { isLoading, isSuccess, errorMessage } = useSelector(selectAuth);
  const navigate = useNavigate();
  const [form] = Form.useForm();

  const dispatch = useDispatch();
  const hasDemoCredentials = Boolean(DEMO_LOGIN_EMAIL && DEMO_LOGIN_PASSWORD);
  const onFinish = (values) => {
    dispatch(login({ loginData: values }));
  };

  useEffect(() => {
    if (isSuccess) navigate('/');
  }, [isSuccess, navigate]);

  const fillDemoCredentials = () => {
    form.setFieldsValue({
      remember: true,
      email: DEMO_LOGIN_EMAIL,
      password: DEMO_LOGIN_PASSWORD,
    });
  };

  const FormContainer = () => {
    return (
      <Loading isLoading={isLoading}>
        <Space direction="vertical" size={18} style={{ width: '100%' }}>
          <div>
            <Typography.Title level={4} style={{ marginBottom: 8 }}>
              Welcome back
            </Typography.Title>
            <Typography.Paragraph type="secondary" style={{ marginBottom: 0 }}>
              Sign in to continue into your tenant workspace, approvals, customer activity, and operational dashboards.
            </Typography.Paragraph>
          </div>

          {errorMessage ? <Alert type="error" showIcon message={errorMessage} /> : null}

          {DEMO_MODE ? (
            <Card size="small" style={{ background: '#f6ffed', borderColor: '#b7eb8f' }}>
              <Space direction="vertical" size={10} style={{ width: '100%' }}>
                <Space align="start">
                  <ThunderboltOutlined style={{ color: '#389e0d', marginTop: 4 }} />
                  <div>
                    <Typography.Text strong>Demo mode is enabled</Typography.Text>
                    <div>
                      <Typography.Text type="secondary">
                        {hasDemoCredentials
                          ? 'Use the configured demo account or prefill the form in one click.'
                          : 'Demo mode is enabled, but demo credentials have not been configured.'}
                      </Typography.Text>
                    </div>
                  </div>
                </Space>
                <Button onClick={fillDemoCredentials} disabled={!hasDemoCredentials}>
                  Use demo credentials
                </Button>
              </Space>
            </Card>
          ) : (
            <Alert
              type="info"
              showIcon
              message="Use the email and password assigned to your account."
              description="If your access was just created, your workspace admin may need to send or reset your temporary password first."
            />
          )}

          <Form
            form={form}
            layout="vertical"
            name="normal_login"
            className="login-form"
            initialValues={{
              remember: true,
              ...(DEMO_MODE ? { email: DEMO_LOGIN_EMAIL, password: DEMO_LOGIN_PASSWORD } : {}),
            }}
            onFinish={onFinish}
          >
            <LoginForm />
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                className="login-form-button"
                loading={isLoading}
                size="large"
                icon={<LockOutlined />}
              >
                {translate('Log in')}
              </Button>
            </Form.Item>
          </Form>
        </Space>
      </Loading>
    );
  };

  return <AuthModule authContent={<FormContainer />} AUTH_TITLE="Sign in" />;
};

export default LoginPage;
