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

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

type ResetState = 'form' | 'loading' | 'success' | 'error';

export default function ResetPasswordPage() {
  const [searchParams] = useSearchParams();
  const token = searchParams.get('token');
  const [state, setState] = useState<ResetState>(token ? 'form' : 'error');
  const [errorMessage, setErrorMessage] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    if (!token) {
      setErrorMessage('No reset token provided. Please use the link from your email.');
    }
  }, [token]);

  const handleSubmit = async (values: { password: string }) => {
    if (!token) return;
    setSubmitting(true);
    try {
      await axios.post(`${API_URL}/api/auth/reset-password`, {
        token,
        password: values.password,
      });
      setState('success');
    } catch (err: unknown) {
      setErrorMessage(getErrorMessage(err, 'Failed to reset password'));
      setState('error');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div
      style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        minHeight: '100vh',
        padding: 16,
        background: '#120b1a',
      }}
    >
      <Card style={{ width: '100%', maxWidth: 420 }}>
        {state === 'form' && (
          <>
            <div style={{ textAlign: 'center', marginBottom: 24 }}>
              <Title level={3} style={{ marginBottom: 4 }}>Reset Password</Title>
              <Text type="secondary">Enter your new password below</Text>
            </div>

            <Form form={form} onFinish={handleSubmit} layout="vertical" size="large">
              <Form.Item
                name="password"
                rules={[
                  { required: true, message: 'Please enter a new 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="New Password (12+ chars)" autoFocus />
              </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={submitting} block>
                  Reset Password
                </Button>
              </Form.Item>
            </Form>
          </>
        )}

        {state === 'success' && (
          <Result
            icon={<CheckCircleOutlined style={{ color: '#52c41a' }} />}
            title="Password Reset!"
            subTitle="Your password has been updated. You can now log in with your new password."
            extra={
              <Link to="/login">
                <Button type="primary" size="large">Go to Login</Button>
              </Link>
            }
          />
        )}

        {state === 'error' && (
          <Result
            icon={<CloseCircleOutlined style={{ color: '#ff4d4f' }} />}
            title="Reset Failed"
            subTitle={errorMessage || 'The reset link is invalid or has expired.'}
            extra={
              <Link to="/login">
                <Button type="primary">Back to Login</Button>
              </Link>
            }
          />
        )}
      </Card>
    </div>
  );
}
