import { useState, useCallback, CSSProperties } from 'react';
import { Form, Input, Button, Card, Typography, Divider, Checkbox, Alert, message } from 'antd';
import { MailOutlined, LockOutlined, GoogleOutlined, FacebookOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { UserManagementService } from '@/services/userManagement';
import { parseError } from '@/utils/errorHandler';
import { setToken } from '@/utils/tokenHelper';
import { useAuthStore } from '@/store/AuthStore';
import { ROUTES } from '@/constants/routes';

const { Title, Text, Link } = Typography;

interface LoginFormValues {
  email: string;
  password: string;
}

const LoginPage = () => {
  const [form] = Form.useForm<LoginFormValues>();
  const [messageApi, contextHolder] = message.useMessage();
  const navigate = useNavigate();
  const { login } = useAuthStore();

  const [loading, setLoading] = useState(false);
  const [loginError, setLoginError] = useState('');
  const [rememberMe, setRememberMe] = useState(false);

  const handleLogin = useCallback(async (values: LoginFormValues) => {
    setLoading(true);
    setLoginError('');

    try {
      const response = await UserManagementService.createLogin();
      
      if (response.data) {
        const token = (response.data as { token?: string }).token;
        if (token) {
          setToken(token);
        }
        
        login(response.data);
        messageApi.success('Welcome back! Redirecting...');
        
        setTimeout(() => {
          navigate(ROUTES.HOME);
        }, 500);
      }
    } catch (error) {
      const { message: errorMessage } = parseError(error);
      setLoginError(errorMessage || 'Invalid email or password. Please try again.');
      setLoading(false);
    }
  }, [login, messageApi, navigate]);

  const handleGoogleLogin = useCallback(async () => {
    setLoading(true);
    try {
      messageApi.info('Google sign-in is not yet implemented');
      setLoading(false);
    } catch (error) {
      const { message: errorMessage } = parseError(error);
      messageApi.error(errorMessage || 'Google sign-in failed. Please try again.');
      setLoading(false);
    }
  }, [messageApi]);

  const handleFacebookLogin = useCallback(async () => {
    setLoading(true);
    try {
      messageApi.info('Facebook sign-in is not yet implemented');
      setLoading(false);
    } catch (error) {
      const { message: errorMessage } = parseError(error);
      messageApi.error(errorMessage || 'Facebook sign-in failed. Please try again.');
      setLoading(false);
    }
  }, [messageApi]);

  const handleNavigateToRegister = useCallback(() => {
    navigate(ROUTES.REGISTER);
  }, [navigate]);

  const handleNavigateToForgotPassword = useCallback(() => {
    navigate(ROUTES.FORGOT_PASSWORD);
  }, [navigate]);

  const handleNavigateToHome = useCallback(() => {
    navigate(ROUTES.HOME);
  }, [navigate]);

  const handleToggleRememberMe = useCallback(() => {
    setRememberMe(prev => !prev);
  }, []);

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

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

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

  const cardHeaderStyle: CSSProperties = {
    textAlign: 'center',
    marginBottom: '32px'
  };

  const logoStyle: CSSProperties = {
    color: '#E3350D',
    marginBottom: '4px',
    cursor: 'pointer',
    fontWeight: 700
  };

  const subtitleStyle: CSSProperties = {
    fontSize: '16px'
  };

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

  const forgotPasswordLinkStyle: CSSProperties = {
    color: '#E3350D'
  };

  const loginButtonStyle: CSSProperties = {
    height: '48px',
    fontSize: '16px',
    fontWeight: 600,
    borderRadius: '8px'
  };

  const dividerStyle: CSSProperties = {
    margin: '24px 0',
    color: '#8c8c8c',
    fontSize: '14px'
  };

  const socialButtonsRowStyle: CSSProperties = {
    display: 'flex',
    gap: '12px'
  };

  const socialButtonStyle: CSSProperties = {
    height: '44px',
    flex: 1,
    borderRadius: '8px'
  };

  const registerSectionStyle: CSSProperties = {
    textAlign: 'center',
    marginTop: '24px'
  };

  const registerTextStyle: CSSProperties = {
    marginRight: '4px'
  };

  const registerLinkStyle: CSSProperties = {
    color: '#E3350D',
    fontWeight: 600
  };

  return (
    <div style={pageContainerStyle}>
      {contextHolder}
      <Card bordered={false} style={loginCardStyle}>
        <div style={cardHeaderStyle}>
          <Title level={2} style={logoStyle} onClick={handleNavigateToHome}>
            PokeResell
          </Title>
          <Text type="secondary" style={subtitleStyle}>
            Sign in to your account
          </Text>
        </div>

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

        <Form
          form={form}
          layout="vertical"
          size="large"
          requiredMark={false}
          onFinish={handleLogin}
        >
          <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 />}
              autoComplete="email"
              size="large"
            />
          </Form.Item>

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

          <div style={rememberForgotRowStyle}>
            <Checkbox checked={rememberMe} onChange={handleToggleRememberMe}>
              Remember me
            </Checkbox>
            <Link style={forgotPasswordLinkStyle} onClick={handleNavigateToForgotPassword}>
              Forgot password?
            </Link>
          </div>

          <Button
            type="primary"
            htmlType="submit"
            block
            size="large"
            loading={loading}
            style={loginButtonStyle}
          >
            Sign In
          </Button>
        </Form>

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

        <div style={socialButtonsRowStyle}>
          <Button
            block
            size="large"
            icon={<GoogleOutlined />}
            onClick={handleGoogleLogin}
            style={socialButtonStyle}
          >
            Google
          </Button>
          <Button
            block
            size="large"
            icon={<FacebookOutlined />}
            onClick={handleFacebookLogin}
            style={socialButtonStyle}
          >
            Facebook
          </Button>
        </div>

        <div style={registerSectionStyle}>
          <Text type="secondary" style={registerTextStyle}>
            Don't have an account?
          </Text>
          <Link strong style={registerLinkStyle} onClick={handleNavigateToRegister}>
            Sign Up
          </Link>
        </div>
      </Card>
    </div>
  );
};

export default LoginPage;