import { useState, useEffect } from 'react';
import { Modal, Form, Input, Button, Alert, Segmented, Typography } from 'antd';
import { MailOutlined, LockOutlined, UserOutlined, CheckCircleOutlined } from '@ant-design/icons';
import { useAuthStore } from '@/stores/auth.store';
import axios from 'axios';

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

type AuthMode = 'signin' | 'register';

interface AuthModalProps {
  open: boolean;
  onCancel: () => void;
  onSuccess: () => void;
  title?: string;
  subtitle?: string;
}

export default function AuthModal({ open, onCancel, onSuccess, title, subtitle }: AuthModalProps) {
  const { login, register, isLoading, error, errorCode, registrationMessage, clearError } = useAuthStore();
  const [mode, setMode] = useState<AuthMode>('signin');
  const [loginForm] = Form.useForm();
  const [registerForm] = Form.useForm();
  const [resendLoading, setResendLoading] = useState(false);
  const [resendSent, setResendSent] = useState(false);

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

  const handleLogin = async (values: { email: string; password: string }) => {
    try {
      await login(values.email, values.password);
      loginForm.resetFields();
      onSuccess();
    } catch {
      // Error is set in store
    }
  };

  const handleRegister = async (values: { name: string; email: string; password: string }) => {
    try {
      const result = await register(values.name, values.email, values.password);
      if (result?.requiresVerification) {
        // Stay open to show verification message — don't call onSuccess
        registerForm.resetFields();
        return;
      }
      registerForm.resetFields();
      onSuccess();
    } catch {
      // Error is set in store
    }
  };

  const handleResendVerification = async () => {
    const email = loginForm.getFieldValue('email');
    if (!email) return;
    setResendLoading(true);
    try {
      await axios.post(`${API_URL}/api/auth/resend-verification`, { email });
      setResendSent(true);
    } catch {
      // Ignore — always show success for security
      setResendSent(true);
    } finally {
      setResendLoading(false);
    }
  };

  const handleCancel = () => {
    loginForm.resetFields();
    registerForm.resetFields();
    clearError();
    onCancel();
  };

  return (
    <Modal
      open={open}
      onCancel={handleCancel}
      footer={null}
      destroyOnHidden
      width={420}
    >
      {title && (
        <div style={{ textAlign: 'center', marginBottom: 4 }}>
          <Text strong style={{ fontSize: 18 }}>{title}</Text>
        </div>
      )}
      {subtitle && (
        <div style={{ textAlign: 'center', marginBottom: 16 }}>
          <Text type="secondary" style={{ fontSize: 13 }}>{subtitle}</Text>
        </div>
      )}

      <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 && (
        <Alert
          message={error}
          type="error"
          showIcon
          closable
          onClose={() => clearError()}
          description={
            errorCode === 'EMAIL_NOT_VERIFIED' ? (
              resendSent ? (
                <Text type="success" style={{ fontSize: 12 }}>Verification email sent! Check your inbox.</Text>
              ) : (
                <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: 0 }}>
            <Button type="primary" htmlType="submit" loading={isLoading} block>
              Sign In
            </Button>
          </Form.Item>
        </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"
            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="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 style={{ marginBottom: 0 }}>
            <Button type="primary" htmlType="submit" loading={isLoading} block>
              Create Account
            </Button>
          </Form.Item>
        </Form>
      )}
    </Modal>
  );
}
