'use client';

import { useState, useEffect, Suspense } from 'react';
import { useSearchParams } from 'next/navigation';

import Link from '@mui/material/Link';
import Alert from '@mui/material/Alert';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import CircularProgress from '@mui/material/CircularProgress';

import { paths } from 'src/routes/paths';
import { RouterLink } from 'src/routes/components';

import { verifyEmail } from 'src/auth/context/jwt';

// ----------------------------------------------------------------------

function VerifyEmailContent() {
  const searchParams = useSearchParams();
  const token = searchParams.get('token');

  const [status, setStatus] = useState('loading'); // 'loading' | 'success' | 'error'
  const [message, setMessage] = useState('');

  useEffect(() => {
    if (!token) {
      setStatus('error');
      setMessage('Verification link is missing. Please check your email or request a new one.');
      return;
    }

    let cancelled = false;

    verifyEmail({ token })
      .then((res) => {
        if (cancelled) return;
        if (res?.success) {
          setStatus('success');
          setMessage('Email successfully verified. You can now sign in.');
        } else {
          setStatus('error');
          setMessage(res?.message || 'Failed to verify email.');
        }
      })
      .catch((err) => {
        if (cancelled) return;
        setStatus('error');
        const msg = err?.response?.data?.message || err?.response?.data?.detail || 'Invalid or expired link. Please request a new verification email.';
        setMessage(msg);
      });

    return () => {
      cancelled = true;
    };
  }, [token]);

  return (
    <>
      <Stack spacing={1.5} sx={{ mb: 5 }}>
        <Typography variant="h5">Email verification</Typography>
      </Stack>

      {status === 'loading' && (
        <Stack alignItems="center" sx={{ py: 4 }}>
          <CircularProgress />
          <Typography variant="body2" sx={{ mt: 2, color: 'text.secondary' }}>
            Verifying your email...
          </Typography>
        </Stack>
      )}

      {status === 'success' && (
        <>
          <Alert severity="success" sx={{ mb: 3 }}>
            {message}
          </Alert>
          <Link component={RouterLink} href={paths.auth.jwt.signIn} variant="subtitle2">
            Sign in to your account
          </Link>
        </>
      )}

      {status === 'error' && (
        <>
          <Alert severity="error" sx={{ mb: 3 }}>
            {message}
          </Alert>
          <Stack spacing={1}>
            <Link component={RouterLink} href={paths.auth.jwt.signIn} variant="subtitle2">
              Back to sign in
            </Link>
            <Link component={RouterLink} href={paths.auth.jwt.signUp} variant="body2" color="text.secondary">
              Create a new account
            </Link>
          </Stack>
        </>
      )}
    </>
  );
}

// ----------------------------------------------------------------------

export function JwtVerifyEmailView() {
  return (
    <Suspense fallback={<Typography variant="body2">Loading...</Typography>}>
      <VerifyEmailContent />
    </Suspense>
  );
}
