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

function ChangePassword() {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [userEmail, setUserEmail] = useState('');
  const [fetchingEmail, setFetchingEmail] = useState(true);

  useEffect(() => {
    const fetchUserEmail = async () => {
      try {
        const response = await api.get('/auth/me');
        setUserEmail(response.data.email);
      } catch (error) {
        message.error('Please log in to change your password');
        navigate('/login');
      } finally {
        setFetchingEmail(false);
      }
    };
    fetchUserEmail();
  }, [navigate]);

  const onFinish = async () => {
    setLoading(true);
    try {
      await api.post('/auth/forgot-password', { email: userEmail });
      message.success('Password reset link sent to your email');
      navigate('/');
    } catch (error) {
      message.error('Failed to send reset email: ' + (error.response?.data?.detail || 'Unknown error'));
    } finally {
      setLoading(false);
    }
  };

  if (fetchingEmail) {
    return (
      <Card title="Change Password" style={{ maxWidth: 400, margin: '0 auto', ...commonStyles.cardGray }}>
        <p>Loading...</p>
      </Card>
    );
  }

  return (
    <Card title="Change Password" style={{ maxWidth: 400, margin: '0 auto', ...commonStyles.cardGray }}>
      <p>We'll send a password reset link to your email address:</p>
      <Form
        name="change-password"
        onFinish={onFinish}
        autoComplete="off"
        layout="vertical"
      >
        <Form.Item>
          <Input
            prefix={<MailOutlined />}
            value={userEmail}
            disabled
            style={{ backgroundColor: '#f5f5f5' }}
          />
        </Form.Item>

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

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

export default ChangePassword;
