import { createFileRoute, Link } from '@tanstack/react-router';
import { z } from 'zod';
import { useEffect, useState } from 'react';
import { CheckCircle, XCircle, Loader2 } from 'lucide-react';
import { apiClient } from '@/infrastructure/http/ApiClient';
import { forceTokenRefresh } from '@/infrastructure/http/auth-refresh';
import { VERIFY_EMAIL } from '@archer/api-interface/endpoints/customer-api';

const verifyEmailSearchSchema = z.object({
  token: z.string(),
});

export const Route = createFileRoute('/auth/verify-email')({
  validateSearch: verifyEmailSearchSchema,
  component: VerifyEmailPage,
});

function VerifyEmailPage() {
  const { token } = Route.useSearch();
  const [status, setStatus] = useState<'loading' | 'success' | 'error'>('loading');
  const [message, setMessage] = useState('');

  useEffect(() => {
    async function verify() {
      try {
        const res = await apiClient.post<{ message?: string }>(VERIFY_EMAIL.path, { token });
        // Force a fresh token round-trip so the AuthenticatedUser snapshot
        // rebuilds from current DB state (emailVerified flips). Swallow the
        // refresh error: anonymous-browser verify (link clicked elsewhere)
        // has no refresh token; the success message still renders, the next
        // /auth/login hydrates correctly.
        try { await forceTokenRefresh(); } catch { /* anonymous verify */ }
        setStatus('success');
        setMessage(res.message || 'Email verified successfully.');
      } catch (err: any) {
        setStatus('error');
        setMessage(err?.response?.data?.message || 'Verification failed. The link may be expired or invalid.');
      }
    }
    verify();
  }, [token]);

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50 px-4">
      <div className="max-w-md w-full bg-white rounded-2xl shadow-lg p-8 text-center">
        {status === 'loading' && (
          <>
            <Loader2 className="w-12 h-12 text-blue-500 animate-spin mx-auto mb-4" />
            <h2 className="text-xl font-semibold text-gray-900 mb-2">Verifying your email...</h2>
            <p className="text-gray-500">Please wait a moment.</p>
          </>
        )}

        {status === 'success' && (
          <>
            <CheckCircle className="w-12 h-12 text-green-500 mx-auto mb-4" />
            <h2 className="text-xl font-semibold text-gray-900 mb-2">Email Verified</h2>
            <p className="text-gray-600 mb-6">{message}</p>
            <Link to="/dashboard" className="inline-block bg-blue-600 text-white px-6 py-2.5 rounded-lg font-medium hover:bg-blue-700 transition-colors">
              Go to Dashboard
            </Link>
          </>
        )}

        {status === 'error' && (
          <>
            <XCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
            <h2 className="text-xl font-semibold text-gray-900 mb-2">Verification Failed</h2>
            <p className="text-gray-600 mb-6">{message}</p>
            <Link to="/login" className="inline-block bg-blue-600 text-white px-6 py-2.5 rounded-lg font-medium hover:bg-blue-700 transition-colors">
              Go to Login
            </Link>
          </>
        )}
      </div>
    </div>
  );
}
