import { useEffect, useState } from 'react';
import { useSearchParams, Link } from 'react-router-dom';
import { Card, Typography, Spin, Result, Button, Form, Input, App } from 'antd';
import { MailOutlined, CheckCircleOutlined, CloseCircleOutlined, ClockCircleOutlined } from '@ant-design/icons';
import axios from 'axios';

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

type VerifyState = 'loading' | 'success-approved' | 'success-pending' | 'error' | 'expired';

export default function VerifyEmailPage() {
  const [searchParams] = useSearchParams();
  const { message } = App.useApp();
  const token = searchParams.get('token');
  const [state, setState] = useState<VerifyState>(token ? 'loading' : 'error');
  const [errorMessage, setErrorMessage] = useState('');
  const [resendLoading, setResendLoading] = useState(false);
  const [resendSent, setResendSent] = useState(false);

  useEffect(() => {
    if (!token) {
      setErrorMessage('No verification token provided');
      setState('error');
      return;
    }

    axios.post(`${API_URL}/api/auth/verify-email`, { token })
      .then(({ data }) => {
        setState(data.approved ? 'success-approved' : 'success-pending');
      })
      .catch((err) => {
        const msg = err.response?.data?.error?.message || 'Verification failed';
        setErrorMessage(msg);
        setState(msg.includes('expired') ? 'expired' : 'error');
      });
  }, [token]);

  const handleResend = async (values: { email: string }) => {
    setResendLoading(true);
    try {
      await axios.post(`${API_URL}/api/auth/resend-verification`, { email: values.email });
      setResendSent(true);
      message.success('If your email is registered, a new verification link has been sent.');
    } catch {
      message.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: 480 }}>
        {state === 'loading' && (
          <div style={{ textAlign: 'center', padding: 40 }}>
            <Spin size="large" />
            <Text style={{ display: 'block', marginTop: 16 }}>Verifying your email...</Text>
          </div>
        )}

        {state === 'success-approved' && (
          <Result
            icon={<CheckCircleOutlined style={{ color: '#52c41a' }} />}
            title="Email Verified!"
            subTitle="Your account is active. You can now log in."
            extra={
              <Link to="/login">
                <Button type="primary" size="large">Go to Login</Button>
              </Link>
            }
          />
        )}

        {state === 'success-pending' && (
          <Result
            icon={<ClockCircleOutlined style={{ color: '#faad14' }} />}
            title="Email Verified!"
            subTitle="Your account is now pending admin approval. You'll receive an email when your account has been approved."
            extra={
              <Link to="/login">
                <Button type="default">Back to Login</Button>
              </Link>
            }
          />
        )}

        {(state === 'error' || state === 'expired') && (
          <Result
            icon={<CloseCircleOutlined style={{ color: '#ff4d4f' }} />}
            title={state === 'expired' ? 'Link Expired' : 'Verification Failed'}
            subTitle={errorMessage || 'The verification link is invalid or has expired.'}
            extra={
              <>
                {!resendSent ? (
                  <div style={{ maxWidth: 320, margin: '0 auto' }}>
                    <Text type="secondary" style={{ display: 'block', marginBottom: 12 }}>
                      Enter your email to receive a new verification link:
                    </Text>
                    <Form onFinish={handleResend} layout="inline" style={{ justifyContent: 'center' }}>
                      <Form.Item
                        name="email"
                        rules={[{ required: true, type: 'email', message: 'Enter email' }]}
                        style={{ flex: 1 }}
                      >
                        <Input prefix={<MailOutlined />} placeholder="Email" />
                      </Form.Item>
                      <Form.Item>
                        <Button type="primary" htmlType="submit" loading={resendLoading}>Resend</Button>
                      </Form.Item>
                    </Form>
                  </div>
                ) : (
                  <Text type="success">Verification email sent! Check your inbox.</Text>
                )}
                <div style={{ marginTop: 16 }}>
                  <Link to="/login">
                    <Button type="link">Back to Login</Button>
                  </Link>
                </div>
              </>
            }
          />
        )}
      </Card>
    </div>
  );
}
