import { useState, useMemo, CSSProperties } from 'react';
import { Form, Input, Button, Card, Typography, Checkbox, Divider, Alert, Modal, message } from 'antd';
import { MailOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { UserService } from '@/services/user';
import { ROUTES } from '@/constants/routes';
import { parseError } from '@/utils/errorHandler';
import { setToken } from '@/utils/tokenHelper';

interface UserResponse {
  id: string;
  user_id: string;
  email: string;
  first_name: string;
  last_name: string;
  date_of_birth?: string | null;
  gender?: 'MALE' | 'FEMALE' | 'OTHER' | 'PREFER_NOT_TO_SAY' | null;
  is_active: boolean;
  role: 'ANONYMOUS' | 'REGISTERED_USER' | 'ADMINISTRATOR';
  last_login_at?: string | null;
  created_at: string;
  updated_at: string;
}

const LoginPage = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const navigate = useNavigate();
  const [loginForm] = Form.useForm();
  const [forgotPasswordForm] = Form.useForm();

  const [loginLoading, setLoginLoading] = useState<boolean>(false);
  const [failedAttempts, setFailedAttempts] = useState<number>(0);
  const [rateLimited, setRateLimited] = useState<boolean>(false);
  const [rateLimitExpiry, setRateLimitExpiry] = useState<Date | null>(null);
  const [loginError, setLoginError] = useState<string>('');
  const [forgotPasswordModalVisible, setForgotPasswordModalVisible] = useState<boolean>(false);
  const [forgotPasswordLoading, setForgotPasswordLoading] = useState<boolean>(false);
  const [forgotPasswordSuccess, setForgotPasswordSuccess] = useState<boolean>(false);
  const [forgotPasswordError, setForgotPasswordError] = useState<string>('');

  const rateLimitMessage = useMemo(() => {
    return rateLimited ? 'Too many failed attempts. Please try again in 15 minutes.' : '';
  }, [rateLimited]);

  const isLoginDisabled = useMemo(() => {
    return rateLimited || loginLoading;
  }, [rateLimited, loginLoading]);

  const openForgotPasswordModal = () => {
    setForgotPasswordModalVisible(true);
    setForgotPasswordSuccess(false);
    setForgotPasswordError('');
  };

  const closeForgotPasswordModal = () => {
    setForgotPasswordModalVisible(false);
    setForgotPasswordSuccess(false);
    setForgotPasswordError('');
    forgotPasswordForm.resetFields();
  };

  const incrementFailedAttempts = () => {
    const newAttempts = failedAttempts + 1;
    setFailedAttempts(newAttempts);
    if (newAttempts >= 5) {
      setRateLimited(true);
      setLoginError('Too many failed attempts. Please try again in 15 minutes.');
      const expiry = new Date();
      expiry.setMinutes(expiry.getMinutes() + 15);
      setRateLimitExpiry(expiry);
    } else {
      setLoginError('Invalid email or password. Please try again.');
    }
  };

  const clearLoginError = () => {
    setLoginError('');
  };

  const submitLogin = async () => {
    try {
      const values = await loginForm.validateFields();
      setLoginLoading(true);
      setLoginError('');

      const response = await UserService.list({ limit: 1, email: values.email });
      
      if (response.data && response.data.length > 0) {
        const user = response.data[0];
        setToken('mock-auth-token');
        messageApi.success('Login successful! Redirecting...');
        setTimeout(() => {
          navigate(ROUTES.HOME || '/');
        }, 500);
      } else {
        incrementFailedAttempts();
      }
    } catch (e) {
      const { message: errorMessage } = parseError(e);
      incrementFailedAttempts();
      messageApi.error(errorMessage);
    } finally {
      setLoginLoading(false);
    }
  };

  const submitForgotPassword = async () => {
    try {
      const values = await forgotPasswordForm.validateFields();
      setForgotPasswordLoading(true);
      setForgotPasswordError('');

      await UserService.list({ limit: 1, email: values.reset_email });
      
      setForgotPasswordSuccess(true);
      messageApi.success('If an account exists with this email, a password reset link has been sent.');
      forgotPasswordForm.resetFields();
    } catch (e) {
      const { message: errorMessage } = parseError(e);
      setForgotPasswordError(errorMessage);
      messageApi.error(errorMessage);
    } finally {
      setForgotPasswordLoading(false);
    }
  };

  const navigateToRegister = () => {
    navigate(ROUTES.REGISTER || '/register');
  };

  const navigateToCalculator = () => {
    navigate(ROUTES.HOME || '/');
  };

  const mainContainerStyle: CSSProperties = {
    minHeight: '100vh',
    height: '100%',
    width: '100%',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    background: 'linear-gradient(135deg, #f0f5ff 0%, #e6f0ff 100%)',
    padding: '24px'
  };

  const loginCardStyle: CSSProperties = {
    width: '100%',
    maxWidth: '420px',
    borderRadius: '8px',
    boxShadow: '0 4px 24px rgba(0,0,0,0.08)'
  };

  const cardHeaderSectionStyle: CSSProperties = {
    textAlign: 'center',
    marginBottom: '8px'
  };

  const appLogoIconStyle: CSSProperties = {
    marginBottom: '0',
    fontSize: '40px'
  };

  const appTitleStyle: CSSProperties = {
    marginBottom: '4px',
    marginTop: '0'
  };

  const loginSubtitleStyle: CSSProperties = {
    fontSize: '14px'
  };

  const loginErrorAlertStyle: CSSProperties = {
    marginBottom: '16px',
    display: loginError ? 'block' : 'none'
  };

  const rateLimitAlertStyle: CSSProperties = {
    marginBottom: '16px',
    display: rateLimited ? 'block' : 'none'
  };

  const rememberForgotRowStyle: CSSProperties = {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: '24px'
  };

  const forgotPasswordLinkStyle: CSSProperties = {
    fontSize: '14px'
  };

  const loginButtonStyle: CSSProperties = {
    height: '44px',
    fontWeight: '600'
  };

  const dividerStyle: CSSProperties = {
    margin: '16px 0'
  };

  const registerSectionStyle: CSSProperties = {
    textAlign: 'center'
  };

  const registerTextStyle: CSSProperties = {
    fontSize: '14px'
  };

  const registerLinkStyle: CSSProperties = {
    fontSize: '14px'
  };

  const calculatorSectionStyle: CSSProperties = {
    textAlign: 'center',
    marginTop: '8px'
  };

  const calculatorTextStyle: CSSProperties = {
    fontSize: '13px'
  };

  const calculatorLinkStyle: CSSProperties = {
    fontSize: '13px'
  };

  const calculatorTextSuffixStyle: CSSProperties = {
    fontSize: '13px'
  };

  const forgotPasswordDescriptionStyle: CSSProperties = {
    marginBottom: '16px'
  };

  const forgotPasswordSuccessAlertStyle: CSSProperties = {
    marginBottom: '16px',
    display: forgotPasswordSuccess ? 'block' : 'none'
  };

  const forgotPasswordErrorAlertStyle: CSSProperties = {
    marginBottom: '16px',
    display: forgotPasswordError ? 'block' : 'none'
  };

  const forgotPasswordButtonsStyle: CSSProperties = {
    display: 'flex',
    justifyContent: 'flex-end',
    gap: '8px'
  };

  return (
    <div style={mainContainerStyle}>
      {contextHolder}
      <Card bordered={true} style={loginCardStyle}>
        <div style={cardHeaderSectionStyle}>
          <Typography.Title level={3} style={appLogoIconStyle}>
            ⚖️
          </Typography.Title>
          <Typography.Title level={3} style={appTitleStyle}>
            BMI Calculator
          </Typography.Title>
          <Typography.Text type="secondary" style={loginSubtitleStyle}>
            Sign in to your account
          </Typography.Text>
        </div>

        <Alert
          type="error"
          showIcon
          closable
          message={loginError}
          style={loginErrorAlertStyle}
          onClose={clearLoginError}
        />

        <Alert
          type="warning"
          showIcon
          message={rateLimitMessage}
          style={rateLimitAlertStyle}
        />

        <Form
          form={loginForm}
          layout="vertical"
          name="login_form"
          autoComplete="on"
          size="large"
          onFinish={submitLogin}
        >
          <Form.Item
            label="Email"
            name="email"
            rules={[
              { required: true, message: 'Please enter your email address' },
              { type: 'email', message: 'Please enter a valid email address' }
            ]}
          >
            <Input
              placeholder="Enter your email"
              prefix={<MailOutlined />}
              allowClear
              autoComplete="email"
            />
          </Form.Item>

          <Form.Item
            label="Password"
            name="password"
            rules={[
              { required: true, message: 'Please enter your password' },
              { min: 8, message: 'Password must be at least 8 characters' }
            ]}
          >
            <Input.Password
              placeholder="Enter your password"
              prefix={<LockOutlined />}
              autoComplete="current-password"
            />
          </Form.Item>

          <div style={rememberForgotRowStyle}>
            <Form.Item name="remember" valuePropName="checked" noStyle>
              <Checkbox>Remember me</Checkbox>
            </Form.Item>
            <Typography.Link onClick={openForgotPasswordModal} style={forgotPasswordLinkStyle}>
              Forgot Password?
            </Typography.Link>
          </div>

          <Form.Item noStyle>
            <Button
              type="primary"
              htmlType="submit"
              block
              size="large"
              loading={loginLoading}
              disabled={isLoginDisabled}
              style={loginButtonStyle}
            >
              Login
            </Button>
          </Form.Item>
        </Form>

        <Divider plain style={dividerStyle}>
          or
        </Divider>

        <div style={registerSectionStyle}>
          <Typography.Text type="secondary" style={registerTextStyle}>
            Don't have an account?{' '}
          </Typography.Text>
          <Typography.Link onClick={navigateToRegister} strong style={registerLinkStyle}>
            Register now
          </Typography.Link>
        </div>

        <div style={calculatorSectionStyle}>
          <Typography.Text type="secondary" style={calculatorTextStyle}>
            Or use the{' '}
          </Typography.Text>
          <Typography.Link onClick={navigateToCalculator} style={calculatorLinkStyle}>
            BMI Calculator
          </Typography.Link>
          <Typography.Text type="secondary" style={calculatorTextSuffixStyle}>
            {' '}without signing in
          </Typography.Text>
        </div>
      </Card>

      <Modal
        title="Reset Password"
        open={forgotPasswordModalVisible}
        onCancel={closeForgotPasswordModal}
        footer={null}
        destroyOnClose
        width={420}
      >
        <Typography.Paragraph type="secondary" style={forgotPasswordDescriptionStyle}>
          Enter your email address and we'll send you a link to reset your password. The link will be valid for 1 hour.
        </Typography.Paragraph>

        <Alert
          type="success"
          showIcon
          message="Password reset email sent!"
          description="If an account exists with this email, you will receive a password reset link shortly. Please check your inbox and spam folder."
          style={forgotPasswordSuccessAlertStyle}
        />

        <Alert
          type="error"
          showIcon
          message={forgotPasswordError}
          style={forgotPasswordErrorAlertStyle}
        />

        <Form
          form={forgotPasswordForm}
          layout="vertical"
          name="forgot_password_form"
          onFinish={submitForgotPassword}
        >
          <Form.Item
            label="Email Address"
            name="reset_email"
            rules={[
              { required: true, message: 'Please enter your email address' },
              { type: 'email', message: 'Please enter a valid email address' }
            ]}
          >
            <Input
              placeholder="Enter your registered email"
              prefix={<MailOutlined />}
              allowClear
            />
          </Form.Item>

          <div style={forgotPasswordButtonsStyle}>
            <Button onClick={closeForgotPasswordModal}>
              Cancel
            </Button>
            <Button
              type="primary"
              htmlType="submit"
              loading={forgotPasswordLoading}
            >
              Send Reset Link
            </Button>
          </div>
        </Form>
      </Modal>
    </div>
  );
};

export default LoginPage;