'use client';

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

interface ResetPasswordFormValues {
  newPassword: string;
  confirmPassword?: string;
}

function ResetPasswordContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const token = searchParams.get('token');

  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);

  const handleSubmit = async (values: ResetPasswordFormValues) => {
    if (!token) {
      setErrorMsg('Missing password reset token from URL.');
      return;
    }
    setLoading(true);
    setErrorMsg(null);
    try {
      await apiRequest('/auth/reset-password', {
        method: 'POST',
        body: JSON.stringify({
          token,
          newPassword: values.newPassword,
        }),
      });
      setSuccess(true);
    } catch (err: unknown) {
      const e = err as Error;
      setErrorMsg(e.message || 'Failed to reset password. Link may be expired.');
    } finally {
      setLoading(false);
    }
  };

  if (!token) {
    return (
      <div>
        <Result
          status="warning"
          title="Invalid Password Reset Link"
          subTitle="The reset link is missing a token or is malformed."
          extra={
            <Link href="/forgot-password">
              <Button type="primary">Request New Link</Button>
            </Link>
          }
        />
      </div>
    );
  }

  if (success) {
    return (
      <div>
        <Result
          status="success"
          title="Password changed"
          subTitle="Your password has been changed. You can now sign in with your new credentials."
          extra={
            <Button type="primary" onClick={() => router.push('/login')}>
              Sign in
            </Button>
          }
        />
      </div>
    );
  }

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

      <Form layout="vertical" size="large" onFinish={handleSubmit}>
        <Form.Item
          label="New password"
          name="newPassword"
          rules={[
            { required: true, message: 'Please enter a new password' },
            { min: 6, message: 'Password must be at least 6 characters' },
            { max: 72, message: 'Password must be at most 72 characters' },
          ]}
        >
          <Input.Password placeholder="••••••••" prefix={<Icon name="lock" size={16} className="text-muted mr-1" />} />
        </Form.Item>

        <Form.Item
          label="Confirm new password"
          name="confirmPassword"
          dependencies={['newPassword']}
          rules={[
            { required: true, message: 'Please confirm your new password' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('newPassword') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('The two passwords do not match!'));
              },
            }),
          ]}
        >
          <Input.Password placeholder="••••••••" prefix={<Icon name="lock" size={16} className="text-muted mr-1" />} />
        </Form.Item>

        <Button type="primary" htmlType="submit" block loading={loading} className="mt-2 font-medium">
          Set new password
        </Button>
      </Form>
    </div>
  );
}

export default function ResetPasswordPage() {
  return (
    <AuthCard title="Set a new password" subtitle="Choose a password with at least 6 characters. It replaces your old one and signs out your other devices.">
      <Suspense fallback={<Spin />}>
        <ResetPasswordContent />
      </Suspense>
    </AuthCard>
  );
}
