import { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import Layout from '../../components/Layout';
import { GlassSurface, Button } from '../../components/ui';

export default function AcceptInvite() {
  const router = useRouter();
  const { token } = router.query;
  
  const [loading, setLoading] = useState(true);
  const [result, setResult] = useState(null);
  const [error, setError] = useState(null);

  const handleAcceptInvitation = async () => {
    try {
      const response = await fetch('/api/invite/accept', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ token })
      });

      const data = await response.json();

      if (response.ok) {
        setResult(data);
      } else {
        setError(data.error || 'Failed to accept invitation');
      }
    } catch (err) {
      setError('Network error. Please try again.');
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    if (token) {
      // eslint-disable-next-line react-hooks/set-state-in-effect -- process invite token on mount
      handleAcceptInvitation();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps -- run once per invite token
  }, [token]);

;

  if (loading) {
    return (
      <Layout user={null}>
        <div className="min-h-screen flex items-center justify-center">
          <div className="text-center">
            <div
              className="motion-essential animate-spin rounded-full h-16 w-16 border-b-2 mx-auto mb-4"
              style={{ borderColor: 'var(--accent-ember)' }}
            />
            <h2
              className="text-xl font-semibold mb-2"
              style={{ color: 'var(--text-primary)' }}
            >
              Processing Invitation...
            </h2>
            <p style={{ color: 'var(--text-secondary)' }}>
              Please wait while we accept your invitation.
            </p>
          </div>
        </div>
      </Layout>
    );
  }

  return (
    <Layout user={null}>
      <div className="min-h-screen flex items-center justify-center px-4">
        <div className="max-w-md w-full">
          {result ? (
            <GlassSurface
              tint="mid"
              rim="subtle"
              elevation="pronounced"
              className="text-center p-8 rounded-2xl"
            >
              <div className="text-6xl mb-4" aria-hidden="true">🎉</div>
              <h2
                className="text-2xl font-bold mb-4"
                style={{ color: 'var(--text-primary)' }}
              >
                Invitation Accepted!
              </h2>
              <p className="mb-6" style={{ color: 'var(--text-secondary)' }}>
                You now have access to the list &quot;{result.collection.name}&quot;.
              </p>
              <div className="space-y-3">
                <Button
                  variant="primary"
                  size="lg"
                  onClick={() => router.push(`/collection/${result.collection.id}`)}
                  className="w-full"
                >
                  View List
                </Button>
                <Button
                  variant="secondary"
                  size="lg"
                  onClick={() => router.push('/collections')}
                  className="w-full"
                >
                  View All Lists
                </Button>
              </div>
            </GlassSurface>
          ) : (
            <GlassSurface
              tint="mid"
              rim="subtle"
              elevation="pronounced"
              className="text-center p-8 rounded-2xl"
            >
              <div className="text-6xl mb-4" aria-hidden="true">❌</div>
              <h2
                className="text-2xl font-bold mb-4"
                style={{ color: 'var(--text-primary)' }}
              >
                Invitation Error
              </h2>
              <p className="mb-6" style={{ color: 'var(--text-secondary)' }}>
                {error}
              </p>
              <div className="space-y-3">
                <Button
                  variant="primary"
                  size="lg"
                  onClick={() => router.push('/collections')}
                  className="w-full"
                >
                  Browse Lists
                </Button>
                <Button
                  variant="secondary"
                  size="lg"
                  onClick={() => router.push('/')}
                  className="w-full"
                >
                  Go Home
                </Button>
              </div>
            </GlassSurface>
          )}
        </div>
      </div>
    </Layout>
  );
}
