'use client';

import { AuthCard } from '../../components/auth/AuthCard';
import Link from 'next/link';
import React, { useState } from 'react';
import { apiRequest } from '../../lib/api';
import { Icon } from '../../components/ui/Icon';
import { Form, Input, Button, Alert } from 'antd';

export default function ForgotPasswordPage() {
  const [loading, setLoading] = useState(false);
  const [successMsg, setSuccessMsg] = useState<string | null>(null);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);

  const handleSubmit = async (values: { email: string }) => {
    setLoading(true);
    setErrorMsg(null);
    setSuccessMsg(null);
    try {
      const res = await apiRequest<{ message: string }>('/auth/forgot-password', {
        method: 'POST',
        body: JSON.stringify({ email: values.email }),
      });
      setSuccessMsg(res.message);
    } catch (err: unknown) {
      const e = err as Error;
      setErrorMsg(e.message || 'Failed to request password reset link.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <AuthCard title="Reset your password" subtitle="Enter your work email and we'll send you a link to set a new password.">
      {successMsg && <Alert title="Check your inbox" description={successMsg} type="success" showIcon className="mb-4" />}

      {errorMsg && <Alert title={errorMsg} type="error" showIcon className="mb-4" closable={{ onClose: () => setErrorMsg(null) }} />}

      {!successMsg && (
        <Form layout="vertical" size="large" onFinish={handleSubmit}>
          <Form.Item
            label="Work email"
            name="email"
            rules={[
              { required: true, message: 'Please enter your email' },
              { type: 'email', message: 'Enter a valid email' },
            ]}
          >
            <Input placeholder="name@company.com" prefix={<Icon name="mail" size={16} className="text-muted mr-1" />} />
          </Form.Item>

          <Button type="primary" htmlType="submit" block loading={loading} className="mt-2">
            Send reset link
          </Button>
        </Form>
      )}

      <div className="text-center mt-5">
        <Link href="/login" className="text-xs text-primary hover:underline font-medium flex items-center justify-center gap-1">
          &larr; Back to sign in
        </Link>
      </div>
    </AuthCard>
  );
}
