import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router';
import { toast } from 'sonner';
import { useMounted } from 'hooks/useMounted';
import { useForm } from 'hooks/useForm';
import { useClient } from 'hooks/useClient';

export const useResetPassword = () => {
  const isMounted = useMounted();
  const navigate = useNavigate();
  const client = useClient('/api/auth');
  const { state, formRef, isValid } = useForm<ResetPasswordFormState>({}, validateForm);

  const [verificationCode] = useState(() => new URL(window.location.href).searchParams.get('verificationCode') ?? '');
  const [tokenStatus, setTokenStatus] = useState<TokenStatus>('loading');
  const [isSubmitting, setIsSubmitting] = useState(false);

  const verifyToken = async () => {
    if (!verificationCode) return;
    try {
      const data = await client.post<{ ok: boolean }>('/verify-token', { verificationCode });
      setTokenStatus(data.ok ? 'valid' : 'invalid');
    } catch {
      setTokenStatus('invalid');
    }
  };

  useEffect(() => {
    if (!isMounted) return;
    if (!verificationCode) {
      setTokenStatus('invalid');
      return;
    }
    verifyToken();
  }, [isMounted]);

  const handleSubmit = async (ev: React.FormEvent) => {
    ev.preventDefault();
    if (!isValid || isSubmitting) return;

    setIsSubmitting(true);
    try {
      await client.post('/reset-password', {
        password: state.password,
        verificationCode,
      });
      toast.success('Password reset successfully. Please sign in.');
      navigate('/');
    } catch (ex) {
      const error = ex as { message?: string };
      toast.error(error.message || 'Failed to reset password. Please try again.');
    } finally {
      setIsSubmitting(false);
    }
  };

  return { formRef, isValid, tokenStatus, isSubmitting, handleSubmit };
};

type ResetPasswordFormState = {
  password?: string;
  confirmPassword?: string;
};

type TokenStatus = 'loading' | 'valid' | 'invalid';

const validateForm = (state: Partial<ResetPasswordFormState>) => {
  const { password, confirmPassword } = state;
  if (!password || !confirmPassword) return false;
  if (password !== confirmPassword) return false;
  return true;
};
