import { useState, useCallback, CSSProperties } from 'react';
import { Form, Input, Button, Card, Checkbox, Alert, Typography, Divider, message } from 'antd';
import { BookOutlined, MailOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { request } from '../api/client';
import { useAppContext } from '../store/AppContext';
import { ROUTES } from '../router/routes.constant';

interface UserResponse {
  id: string;
  email: string;
  first_name: string;
  last_name: string;
  phone?: string | null;
  address?: string | null;
  role: string;
  status: string;
  created_at: string;
  updated_at: string;
}

interface LoginFormValues {
  email: string;
  password: string;
  remember?: boolean;
}

export default function LoginPage() {
  const [messageApi, contextHolder] = message.useMessage();
  const [form] = Form.useForm<LoginFormValues>();
  const navigate = useNavigate();
  const { currentUser } = useAppContext();

  const [loginLoading, setLoginLoading] = useState<boolean>(false);
  const [loginError, setLoginError] = useState<string>('');
  const [rememberMe, setRememberMe] = useState<boolean>(false);

  const onRememberMeChange = useCallback((e: { target: { checked: boolean } }) => {
    setRememberMe(e.target.checked);
  }, []);

  const onLoginErrorClear = useCallback(() => {
    setLoginError('');
  }, []);

  const submitLogin = useCallback(async (values: LoginFormValues) => {
    setLoginLoading(true);
    setLoginError('');

    try {
      const result = await request<UserResponse>({
        method: 'POST',
        path: '/users/',
        body: {
          email: values.email,
          password: values.password
        }
      });

      messageApi.success('Login successful! Redirecting...');

      const userRole = result.data.role;
      if (userRole === 'ADMINISTRATOR') {
        navigate(ROUTES.ADMIN_DASHBOARD || '/admin');
      } else if (userRole === 'LIBRARIAN') {
        navigate(ROUTES.LIBRARIAN_DASHBOARD || '/librarian');
      } else if (userRole === 'MEMBER') {
        navigate(ROUTES.MEMBER_DASHBOARD || '/member');
      } else {
        navigate(ROUTES.HOME || '/');
      }
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : 'Invalid email or password. Please try again.';
      setLoginError(errorMessage);
      messageApi.error(errorMessage);
    } finally {
      setLoginLoading(false);
    }
  }, [messageApi, navigate]);

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

  const navigateToForgotPassword = useCallback(() => {
    navigate(ROUTES.FORGOT_PASSWORD || '/forgot-password');
  }, [navigate]);

  const mainContainerStyle: CSSProperties = {
    minHeight: '100vh',
    width: '100%',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    background: 'linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%)'
  };

  const loginCardStyle: CSSProperties = {
    width: '100%',
    maxWidth: '420px',
    padding: '24px',
    boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
  };

  const logoSectionStyle: CSSProperties = {
    textAlign: 'center',
    marginBottom: '24px'
  };

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

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

  return (
    <div style={mainContainerStyle}>
      {contextHolder}
      <Card bordered={true} style={loginCardStyle}>
        <div style={logoSectionStyle}>
          <BookOutlined style={{ fontSize: '48px', color: '#1677ff' }} />
          <Typography.Title level={3} style={{ marginBottom: '4px', marginTop: '12px' }}>
            Library Management System
          </Typography.Title>
          <Typography.Text type="secondary">Sign in to your account</Typography.Text>
        </div>

        {loginError && (
          <Alert
            type="error"
            showIcon
            closable
            message={loginError}
            onClose={onLoginErrorClear}
            style={{ marginBottom: '16px' }}
          />
        )}

        <Form
          form={form}
          layout="vertical"
          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
              prefix={<MailOutlined />}
              placeholder="Enter your email"
              autoComplete="email"
            />
          </Form.Item>

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

          <div style={rememberForgotRowStyle}>
            <Form.Item name="remember" valuePropName="checked" noStyle>
              <Checkbox checked={rememberMe} onChange={onRememberMeChange}>
                Remember me
              </Checkbox>
            </Form.Item>
            <Typography.Link onClick={navigateToForgotPassword}>
              Forgot password?
            </Typography.Link>
          </div>

          <Form.Item noStyle>
            <Button
              type="primary"
              htmlType="submit"
              block
              size="large"
              loading={loginLoading}
            >
              Sign In
            </Button>
          </Form.Item>
        </Form>

        <Divider plain />

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