'use client';

import { useState, useEffect, Suspense } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useAuth } from '@/lib/auth-context';
import { Button } from '@/components/ui/button';
import { invitationsApi, InvitationInfo } from '@/lib/api';

function RegisterForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const inviteToken = searchParams.get('invite_token');
  const { register, acceptedProjects, clearAcceptedProjects, justRegisteredName, user } = useAuth();
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [inviteInfo, setInviteInfo] = useState<InvitationInfo | null>(null);
  const [inviteLoading, setInviteLoading] = useState(false);
  const [justJoined, setJustJoined] = useState(false);

  // Verify invite token if present — auto-fill email
  useEffect(() => {
    if (inviteToken) {
      setInviteLoading(true);
      invitationsApi.verify(inviteToken)
        .then(({ invitation }) => {
          setInviteInfo(invitation);
          setEmail(invitation.email);
        })
        .catch(() => { /* invalid token, not critical */ })
        .finally(() => setInviteLoading(false));
    }
  }, [inviteToken]);

  useEffect(() => {
    if (acceptedProjects.length > 0 && !justJoined) {
      setJustJoined(true);
    }
  }, [acceptedProjects, justJoined]);

  // Redirect if already logged in
  useEffect(() => {
    if (user) {
      if (inviteToken) {
        router.push(`/invite/${inviteToken}`);
      } else {
        router.push('/projects');
      }
    }
  }, [user, inviteToken, router]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    if (password.length < 6) {
      setError('Password must be at least 6 characters');
      return;
    }
    setLoading(true);
    try {
      await register(email, name, password, inviteToken ?? undefined);
      if (inviteToken) {
        router.push(`/invite/${inviteToken}`);
      } else {
        router.push('/projects');
      }
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Registration failed');
    } finally {
      setLoading(false);
    }
  };

  const handleGoToProject = (projectId: string) => {
    clearAcceptedProjects();
    router.push(`/projects/${projectId}`);
  };

  return (
    <div className="min-h-screen flex items-center justify-center relative overflow-hidden"
         style={{ background: 'var(--bg)' }}>

      {/* Ambient blobs */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className="absolute top-20 right-20 w-[500px] h-[500px] rounded-full opacity-[0.06]"
             style={{ background: 'radial-gradient(circle, #6366F1 0%, transparent 70%)' }} />
        <div className="absolute -bottom-32 left-20 w-[400px] h-[400px] rounded-full opacity-[0.04]"
             style={{ background: 'radial-gradient(circle, #818CF8 0%, transparent 70%)' }}
        />
        <div className="absolute inset-0 opacity-[0.025]"
             style={{
               backgroundImage: 'linear-gradient(rgba(255,255,255,0.5) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.5) 1px, transparent 1px)',
               backgroundSize: '48px 48px',
             }} />
      </div>

      {/* Logo */}
      <div className="absolute top-8 left-1/2 -translate-x-1/2 flex items-center gap-2.5 animate-fade-in">
        <div className="w-9 h-9 rounded-xl flex items-center justify-center"
             style={{ background: '#6366F1', boxShadow: '0 0 24px rgba(99,102,241,0.5)' }}>
          <svg className="w-5 h-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
            <path strokeLinecap="round" strokeLinejoin="round" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
        </div>
        <span className="text-lg font-semibold tracking-tight" style={{ color: 'var(--text)' }}>VidReview</span>
      </div>

      {/* Card */}
      <div className="relative w-full max-w-[400px] mx-6 animate-scale-in">
        <div className="rounded-2xl p-8"
             style={{
               background: 'rgba(22,24,34,0.90)',
               backdropFilter: 'blur(20px)',
               border: '1px solid rgba(255,255,255,0.08)',
               boxShadow: 'var(--shadow-modal)',
             }}>

          {/* Invite banner */}
          {inviteLoading ? (
            <div className="mb-5 rounded-lg px-4 py-3 text-sm animate-fade-in"
                 style={{ background: 'rgba(99,102,241,0.08)', border: '1px solid rgba(99,102,241,0.20)', color: '#A5B4FC' }}>
              <div className="flex items-center gap-2">
                <div className="w-3.5 h-3.5 rounded-full animate-spin"
                     style={{ borderColor: '#6366F1', borderTopColor: 'transparent', borderWidth: 1.5 }} />
                Verifying invitation…
              </div>
            </div>
          ) : inviteInfo ? (
            <div className="mb-5 rounded-lg px-4 py-3 text-sm animate-scale-in"
                 style={{ background: 'rgba(99,102,241,0.08)', border: '1px solid rgba(99,102,241,0.20)', color: '#A5B4FC' }}>
              <div className="flex items-start gap-2.5">
                <svg className="w-4 h-4 mt-0.5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 5.25a3 3 0 013 3m3 0a6 6 0 01-7.029 5.912c-.563-.097-1.159.026-1.563.43L10.5 17.25H8.25v2.25H6v2.25H2.25v-2.818c0-.597.237-1.17.659-1.591l6.499-6.499c.404-.404.527-1 .43-1.563A6 6 0 1121.75 8.25z" />
                </svg>
                <div>
                  <p className="font-medium">You're invited to join</p>
                  <p className="font-semibold mt-0.5">{inviteInfo.projectName}</p>
                  <span className="badge badge-brand text-[10px] mt-1.5 capitalize">{inviteInfo.role.toLowerCase()}</span>
                </div>
              </div>
            </div>
          ) : null}

          {/* Accepted projects notification */}
          {justJoined && (
            <div className="mb-5 rounded-lg px-4 py-3 text-sm animate-scale-in"
                 style={{ background: 'rgba(34,197,94,0.12)', border: '1px solid rgba(34,197,94,0.25)', color: '#86EFAC' }}>
              {justRegisteredName && (
                <p className="font-medium mb-1">Welcome, {justRegisteredName}!</p>
              )}
              {acceptedProjects.length > 0 ? (
                <>
                  <p className="font-medium mb-2">You're now a member of:</p>
                  {acceptedProjects.map(p => (
                    <button
                      key={p.projectId}
                      onClick={() => handleGoToProject(p.projectId)}
                      className="block text-left hover:underline"
                      style={{ color: '#86EFAC' }}
                    >
                      → {p.projectName}
                    </button>
                  ))}
                </>
              ) : (
                <p>Your account is ready. Redirecting…</p>
              )}
            </div>
          )}

          {error && (
            <div className="mb-5 rounded-lg px-4 py-3 text-sm flex items-start gap-2.5 animate-scale-in"
                 style={{ background: 'rgba(239,68,68,0.12)', border: '1px solid rgba(239,68,68,0.25)', color: '#FCA5A5' }}>
              <svg className="w-4 h-4 mt-0.5 shrink-0 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                      d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              {error}
            </div>
          )}

          <div className="mb-7">
            <h1 className="text-xl font-semibold tracking-tight" style={{ color: 'var(--text)' }}>
              {inviteInfo ? 'Create your account' : 'Create workspace'}
            </h1>
            <p className="text-sm mt-1" style={{ color: 'var(--text-muted)' }}>
              {inviteInfo ? 'Join your team in seconds' : 'Set up your team in under a minute'}
            </p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label htmlFor="name" className="block text-sm font-medium mb-1.5" style={{ color: 'var(--text)' }}>
                Full name
              </label>
              <input
                id="name"
                type="text"
                className="input"
                value={name}
                onChange={e => setName(e.target.value)}
                placeholder="Jane Editor"
                required
                autoComplete="name"
              />
            </div>

            <div>
              <label htmlFor="email" className="block text-sm font-medium mb-1.5" style={{ color: 'var(--text)' }}>
                Email address
              </label>
              <input
                id="email"
                type="email"
                className="input"
                value={email}
                onChange={e => setEmail(e.target.value)}
                placeholder="you@company.com"
                required
                autoComplete="email"
              />
            </div>

            <div>
              <label htmlFor="password" className="block text-sm font-medium mb-1.5" style={{ color: 'var(--text)' }}>
                Password
              </label>
              <input
                id="password"
                type="password"
                className="input"
                value={password}
                onChange={e => setPassword(e.target.value)}
                placeholder="At least 6 characters"
                required
                autoComplete="new-password"
              />
              <p className="text-xs mt-1.5" style={{ color: 'var(--text-subtle)' }}>
                Use 8+ characters with a mix of letters and numbers
              </p>
            </div>

            <Button
              type="submit"
              loading={loading}
              className="btn btn-primary btn-lg w-full mt-2"
            >
              {loading ? 'Creating account…' : 'Create account'}
            </Button>
          </form>

          <p className="text-center text-sm mt-5" style={{ color: 'var(--text-muted)' }}>
            Already have an account?{' '}
            <a href="/login"
               className="font-medium transition-colors hover:underline"
               style={{ color: '#818CF8' }}>
              Sign in
            </a>
          </p>
        </div>
      </div>
    </div>
  );
}

export default function RegisterPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen flex items-center justify-center" style={{ background: 'var(--bg)' }}>
        <div className="flex items-center gap-3" style={{ color: 'var(--text-muted)' }}>
          <div className="w-5 h-5 rounded-full animate-spin"
               style={{ borderColor: '#6366F1', borderTopColor: 'transparent' }} />
          <span className="text-sm">Loading…</span>
        </div>
      </div>
    }>
      <RegisterForm />
    </Suspense>
  );
}
