import { useState, useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Card, Form, Input, Button, Alert, Typography, Segmented, Modal, App } from 'antd';
import { MailOutlined, LockOutlined, UserOutlined, CheckCircleOutlined, GiftOutlined } from '@ant-design/icons';
import { useAuthStore } from '@/stores/auth.store';
import { useSettingsStore } from '@/stores/settings.store';
import { isAdmin } from '@/utils/roles';
import axios from 'axios';

const { Title, Text } = Typography;
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:4000';

type AuthMode = 'signin' | 'register';

export default function LoginPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { message: messageApi } = App.useApp();
  const {
    login, register, isAuthenticated, isLoading, error, errorCode,
    user, registrationMessage, clearError,
  } = useAuthStore();
  const { settings } = useSettingsStore();
  const [loginForm] = Form.useForm();
  const [registerForm] = Form.useForm();
  const [mode, setMode] = useState<AuthMode>('signin');
  const [forgotPasswordOpen, setForgotPasswordOpen] = useState(false);
  const [forgotEmail, setForgotEmail] = useState('');
  const [forgotLoading, setForgotLoading] = useState(false);
  const [forgotSent, setForgotSent] = useState(false);
  const [resendLoading, setResendLoading] = useState(false);

  const rawRedirect = searchParams.get('redirect');
  // Validate redirect is a safe relative path (prevents open redirect attacks)
  const redirectTo = rawRedirect && rawRedirect.startsWith('/') && !rawRedirect.startsWith('//') ? rawRedirect : null;
  const refCode = searchParams.get('ref') || '';
  const showRegister = settings?.enablePublicRegistration !== false;

  // Auto-switch to register mode when ref code is present
  useEffect(() => {
    if (refCode && showRegister) {
      setMode('register');
      registerForm.setFieldValue('inviteCode', refCode);
    }
  }, [refCode, showRegister]); // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    if (isAuthenticated && user) {
      if (redirectTo) {
        navigate(redirectTo, { replace: true });
      } else {
        navigate(isAdmin(user) ? '/app' : '/volunteer', { replace: true });
      }
    }
  }, [isAuthenticated, user, navigate, redirectTo]);

  // Clear errors when switching modes
  useEffect(() => {
    clearError();
  }, [mode]); // eslint-disable-line react-hooks/exhaustive-deps

  const handleLogin = async (values: { email: string; password: string }) => {
    try {
      await login(values.email, values.password);
      const updatedUser = useAuthStore.getState().user;
      if (redirectTo) {
        navigate(redirectTo, { replace: true });
      } else {
        navigate(isAdmin(updatedUser) ? '/app' : '/volunteer', { replace: true });
      }
    } catch {
      // Error is set in store
    }
  };

  const handleRegister = async (values: { name: string; email: string; password: string; inviteCode?: string }) => {
    try {
      const result = await register(values.name, values.email, values.password, values.inviteCode);
      if (result?.requiresVerification) {
        // Don't navigate — show the verification message
        return;
      }
      const updatedUser = useAuthStore.getState().user;
      if (redirectTo) {
        navigate(redirectTo, { replace: true });
      } else {
        navigate(isAdmin(updatedUser) ? '/app' : '/volunteer', { replace: true });
      }
    } catch {
      // Error is set in store
    }
  };

  const handleForgotPassword = async () => {
    if (!forgotEmail) return;
    setForgotLoading(true);
    try {
      await axios.post(`${API_URL}/api/auth/forgot-password`, { email: forgotEmail });
      setForgotSent(true);
    } catch {
      // Always show success for security (no user enumeration)
      setForgotSent(true);
    } finally {
      setForgotLoading(false);
    }
  };

  const handleResendVerification = async () => {
    const email = loginForm.getFieldValue('email');
    if (!email) {
      messageApi.warning('Please enter your email address first');
      return;
    }
    setResendLoading(true);
    try {
      await axios.post(`${API_URL}/api/auth/resend-verification`, { email });
      messageApi.success('If your email is registered, a new verification link has been sent.');
    } catch {
      messageApi.error('Failed to resend. Please try again later.');
    } finally {
      setResendLoading(false);
    }
  };

  return (
    <div
      style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        minHeight: '100vh',
        padding: 16,
        background: '#120b1a',
      }}
    >
      <Card style={{ width: '100%', maxWidth: 400 }}>
        <div style={{ textAlign: 'center', marginBottom: 24 }}>
          <Title level={3} style={{ marginBottom: 4 }}>
            {settings?.organizationName ?? 'Changemaker Lite'}
          </Title>
          <Text type="secondary">{settings?.loginSubtitle ?? 'Sign In'}</Text>
        </div>

        {showRegister && (
          <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 20 }}>
            <Segmented
              options={[
                { label: 'Sign In', value: 'signin' },
                { label: 'Register', value: 'register' },
              ]}
              value={mode}
              onChange={(val) => setMode(val as AuthMode)}
            />
          </div>
        )}

        {/* Registration success — verification required */}
        {registrationMessage && (
          <Alert
            message="Check Your Email"
            description={registrationMessage}
            type="success"
            showIcon
            icon={<CheckCircleOutlined />}
            closable
            onClose={() => clearError()}
            style={{ marginBottom: 16 }}
          />
        )}

        {/* Error display with contextual actions */}
        {error && (
          <Alert
            message={error}
            type="error"
            showIcon
            closable
            onClose={() => clearError()}
            description={
              errorCode === 'EMAIL_NOT_VERIFIED' ? (
                <Button
                  type="link"
                  size="small"
                  loading={resendLoading}
                  onClick={handleResendVerification}
                  style={{ padding: 0 }}
                >
                  Resend verification email
                </Button>
              ) : errorCode === 'ACCOUNT_PENDING' ? (
                <Text type="secondary" style={{ fontSize: 12 }}>
                  An admin will review your account shortly.
                </Text>
              ) : undefined
            }
            style={{ marginBottom: 16 }}
          />
        )}

        {mode === 'signin' ? (
          <Form form={loginForm} onFinish={handleLogin} layout="vertical" size="large">
            <Form.Item
              name="email"
              rules={[
                { required: true, message: 'Please enter your email' },
                { type: 'email', message: 'Please enter a valid email' },
              ]}
            >
              <Input prefix={<MailOutlined />} placeholder="Email" autoFocus />
            </Form.Item>

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

            <Form.Item style={{ marginBottom: 8 }}>
              <Button
                type="primary"
                htmlType="submit"
                loading={isLoading}
                block
              >
                Sign In
              </Button>
            </Form.Item>

            <div style={{ textAlign: 'center' }}>
              <Button
                type="link"
                size="small"
                onClick={() => {
                  setForgotEmail(loginForm.getFieldValue('email') || '');
                  setForgotSent(false);
                  setForgotPasswordOpen(true);
                }}
              >
                Forgot password?
              </Button>
            </div>
          </Form>
        ) : (
          <Form form={registerForm} onFinish={handleRegister} layout="vertical" size="large">
            <Form.Item
              name="name"
              rules={[{ required: true, message: 'Please enter your name' }]}
            >
              <Input prefix={<UserOutlined />} placeholder="Full Name" autoFocus />
            </Form.Item>

            <Form.Item
              name="email"
              rules={[
                { required: true, message: 'Please enter your email' },
                { type: 'email', message: 'Please enter a valid email' },
              ]}
            >
              <Input prefix={<MailOutlined />} placeholder="Email" />
            </Form.Item>

            <Form.Item
              name="password"
              extra="12+ characters with uppercase, lowercase, and a digit"
              rules={[
                { required: true, message: 'Please enter a password' },
                { min: 12, message: 'Password must be at least 12 characters' },
                {
                  pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/,
                  message: 'Must contain uppercase, lowercase, and a digit',
                },
              ]}
            >
              <Input.Password prefix={<LockOutlined />} placeholder="Password (12+ chars)" />
            </Form.Item>

            <Form.Item
              name="inviteCode"
              extra="Have an invite code? Enter it here"
            >
              <Input prefix={<GiftOutlined />} placeholder="Invite Code (optional)" />
            </Form.Item>

            <Form.Item
              name="confirmPassword"
              dependencies={['password']}
              rules={[
                { required: true, message: 'Please confirm your password' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('Passwords do not match'));
                  },
                }),
              ]}
            >
              <Input.Password prefix={<LockOutlined />} placeholder="Confirm Password" />
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                loading={isLoading}
                block
              >
                Create Account
              </Button>
            </Form.Item>
          </Form>
        )}
      </Card>

      {/* Forgot Password Modal */}
      <Modal
        title="Reset Password"
        open={forgotPasswordOpen}
        onCancel={() => setForgotPasswordOpen(false)}
        footer={null}
        width={400}
      >
        {forgotSent ? (
          <Alert
            message="Check Your Email"
            description="If an account exists with that email, a password reset link has been sent."
            type="success"
            showIcon
            style={{ marginBottom: 16 }}
          />
        ) : (
          <>
            <Text type="secondary" style={{ display: 'block', marginBottom: 16 }}>
              Enter your email address and we'll send you a link to reset your password.
            </Text>
            <Input
              prefix={<MailOutlined />}
              placeholder="Email address"
              value={forgotEmail}
              onChange={(e) => setForgotEmail(e.target.value)}
              onPressEnter={handleForgotPassword}
              style={{ marginBottom: 16 }}
            />
            <Button
              type="primary"
              block
              loading={forgotLoading}
              onClick={handleForgotPassword}
              disabled={!forgotEmail}
            >
              Send Reset Link
            </Button>
          </>
        )}
      </Modal>
    </div>
  );
}
