import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Card, message } from 'antd';
import { LockOutlined } from '@ant-design/icons';
import { useNavigate, useSearchParams, Link } from 'react-router-dom';
import api from '../../utils/api';
import { commonStyles } from '../../theme';

function ResetPassword() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [loading, setLoading] = useState(false);
  const [token, setToken] = useState('');

  useEffect(() => {
    const tokenFromUrl = searchParams.get('token');
    if (tokenFromUrl) {
      setToken(tokenFromUrl);
    } else {
      message.error('No reset token provided');
      navigate('/login');
    }
  }, [searchParams, navigate]);

  const onFinish = async (values) => {
    setLoading(true);
    try {
      await api.post('/auth/reset-password', {
        token: token,
        password: values.password,
        confirm_password: values.confirm_password
      });
      message.success('Password reset successfully');
      navigate('/login');
    } catch (error) {
      message.error('Failed to reset password: ' + (error.response?.data?.detail || 'Unknown error'));
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card title="Reset Password" style={{ maxWidth: 400, margin: '0 auto', ...commonStyles.cardGray }}>
      <p>Enter your new password below.</p>
      <Form
        name="reset-password"
        onFinish={onFinish}
        autoComplete="off"
        layout="vertical"
      >
        <Form.Item
          name="password"
          rules={[
            { required: true, message: 'Please input your password!' },
            { min: 6, message: 'Password must be at least 6 characters' }
          ]}
        >
          <Input.Password prefix={<LockOutlined />} placeholder="New Password" />
        </Form.Item>

        <Form.Item
          name="confirm_password"
          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('The two passwords do not match!'));
              },
            }),
          ]}
        >
          <Input.Password prefix={<LockOutlined />} placeholder="Confirm New Password" />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" loading={loading} block>
            Reset Password
          </Button>
        </Form.Item>

        <Form.Item>
          <Link to="/login">Back to Login</Link>
        </Form.Item>
      </Form>
    </Card>
  );
}

export default ResetPassword;