import React, { useState } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Steps,
  Typography,
  Alert,
  message,
  Result,
} from 'antd';
import {
  MailOutlined,
  SafetyOutlined,
  LockOutlined,
  EyeInvisibleOutlined,
  EyeTwoTone,
  ArrowLeftOutlined,
  ReloadOutlined,
} from '@ant-design/icons';

const { Title, Text, Link } = Typography;
const { Step } = Steps;

interface ResetPasswordFormValues {
  email: string;
  verificationCode: string;
  newPassword: string;
  confirmPassword: string;
}

export const ResetPasswordPage: React.FC = () => {
  const [form] = Form.useForm();
  const [currentStep, setCurrentStep] = useState(0);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [emailSent, setEmailSent] = useState(false);
  const [resetComplete, setResetComplete] = useState(false);

  const steps = [
    { title: 'Email', description: 'Enter your email' },
    { title: 'Verify', description: 'Enter code' },
    { title: 'Reset', description: 'New password' },
  ];

  const handleSendCode = async (values: { email: string }) => {
    setLoading(true);
    setError(null);

    try {
      await new Promise(resolve => setTimeout(resolve, 1500));
      setEmailSent(true);
      message.success('Verification code sent to your email');
      setCurrentStep(1);
    } catch (err) {
      setError('Failed to send verification code. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const handleVerifyCode = async (values: { verificationCode: string }) => {
    setLoading(true);
    setError(null);

    try {
      await new Promise(resolve => setTimeout(resolve, 1000));
      if (values.verificationCode.length !== 6) {
        setError('Invalid verification code');
        return;
      }
      setCurrentStep(2);
    } catch (err) {
      setError('Verification failed. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const handleResetPassword = async (values: ResetPasswordFormValues) => {
    setLoading(true);
    setError(null);

    try {
      await new Promise(resolve => setTimeout(resolve, 1500));
      setResetComplete(true);
      message.success('Password reset successful!');
    } catch (err) {
      setError('Failed to reset password. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  if (resetComplete) {
    return (
      <div style={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        padding: 24,
      }}>
        <Card style={{ maxWidth: 500, width: '100%', borderRadius: 16 }}>
          <Result
            status="success"
            title="Password Reset Complete!"
            subTitle="Your password has been successfully reset. You can now log in with your new password."
            extra={[
              <Button type="primary" size="large" href="/auth/login" key="login">
                Go to Login
              </Button>,
            ]}
          />
        </Card>
      </div>
    );
  }

  return (
    <div style={{
      minHeight: '100vh',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      padding: 24,
    }}>
      <Card
        style={{
          maxWidth: 500,
          width: '100%',
          borderRadius: 16,
          boxShadow: '0 20px 60px rgba(0,0,0,0.3)',
        }}
        bodyStyle={{ padding: 40 }}
      >
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <Title level={3}>Reset Password</Title>
          <Text type="secondary">Follow the steps to reset your password</Text>
        </div>

        <Steps current={currentStep} style={{ marginBottom: 32 }}>
          {steps.map(step => (
            <Step key={step.title} title={step.title} description={step.description} />
          ))}
        </Steps>

        {error && (
          <Alert
            message={error}
            type="error"
            showIcon
            style={{ marginBottom: 24 }}
            closable
            onClose={() => setError(null)}
          />
        )}

        {currentStep === 0 && (
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSendCode}
          >
            <Form.Item
              name="email"
              rules={[
                { required: true, message: 'Please enter your email' },
                { type: 'email', message: 'Please enter a valid email' },
              ]}
            >
              <Input
                prefix={<MailOutlined style={{ color: '#bfbfbf' }} />}
                placeholder="Enter your email address"
                size="large"
              />
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                size="large"
                block
                loading={loading}
              >
                Send Verification Code
              </Button>
            </Form.Item>

            <div style={{ textAlign: 'center' }}>
              <Link href="/auth/login">
                <ArrowLeftOutlined /> Back to Login
              </Link>
            </div>
          </Form>
        )}

        {currentStep === 1 && (
          <Form
            form={form}
            layout="vertical"
            onFinish={handleVerifyCode}
          >
            <Alert
              message="Check your email"
              description={`We've sent a 6-digit verification code to ${form.getFieldValue('email')}`}
              type="info"
              showIcon
              style={{ marginBottom: 24 }}
            />

            <Form.Item
              name="verificationCode"
              rules={[
                { required: true, message: 'Please enter verification code' },
                { len: 6, message: 'Code must be 6 digits' },
              ]}
            >
              <Input
                prefix={<SafetyOutlined style={{ color: '#bfbfbf' }} />}
                placeholder="Enter 6-digit code"
                size="large"
                maxLength={6}
              />
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                size="large"
                block
                loading={loading}
              >
                Verify Code
              </Button>
            </Form.Item>

            <div style={{ textAlign: 'center' }}>
              <Button type="link" onClick={() => setCurrentStep(0)} icon={<ReloadOutlined />}>
                Resend Code
              </Button>
            </div>
          </Form>
        )}

        {currentStep === 2 && (
          <Form
            form={form}
            layout="vertical"
            onFinish={handleResetPassword}
          >
            <Form.Item
              name="newPassword"
              rules={[
                { required: true, message: 'Please enter new password' },
                { min: 8, message: 'Password must be at least 8 characters' },
                { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, message: 'Must contain uppercase, lowercase and number' },
              ]}
            >
              <Input.Password
                prefix={<LockOutlined style={{ color: '#bfbfbf' }} />}
                placeholder="New Password"
                size="large"
                iconRender={visible => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
              />
            </Form.Item>

            <Form.Item
              name="confirmPassword"
              dependencies={['newPassword']}
              rules={[
                { required: true, message: 'Please confirm new password' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('newPassword') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('Passwords do not match'));
                  },
                }),
              ]}
            >
              <Input.Password
                prefix={<LockOutlined style={{ color: '#bfbfbf' }} />}
                placeholder="Confirm New Password"
                size="large"
                iconRender={visible => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
              />
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                size="large"
                block
                loading={loading}
              >
                Reset Password
              </Button>
            </Form.Item>
          </Form>
        )}
      </Card>
    </div>
  );
};

export default ResetPasswordPage;
