import { useEffect, useMemo, useState } from 'react'
import { Link, useLocation, useNavigate } from 'react-router-dom'
import { inviteApi, type AccountInviteLookup } from '@/api/invite'
import { useAuthStore } from '@/store/authStore'
import { useAppConfig } from '@/hooks/useAppConfig'
import { BrandLogo } from '@/components/common/BrandLogo'
import { PasswordInput } from '@/components/common/PasswordInput'
import { PageMeta } from '@/components/common/PageMeta'
import { buildOAuthAuthorizeUrl } from './RegisterPage'
import { cn } from '@/lib/utils'
import { encodeOAuthState } from '@/lib/oauthState'

function randomCsrf(): string {
  const buf = new Uint8Array(16)
  if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
    crypto.getRandomValues(buf)
  } else {
    for (let i = 0; i < buf.length; i++) buf[i] = Math.floor(Math.random() * 256)
  }
  return Array.from(buf, (b) => b.toString(16).padStart(2, '0')).join('')
}

type LookupState =
  | { status: 'loading' }
  | { status: 'ok'; data: AccountInviteLookup }
  | { status: 'invalid' }
  | { status: 'missing-code' }

export function AcceptInvitePage() {
  const navigate = useNavigate()
  const location = useLocation()
  const { register, isLoading, error, clearError } = useAuthStore()
  const appConfig = useAppConfig()

  const code = useMemo(() => {
    const search = new URLSearchParams(location.search)
    return (search.get('code') || '').trim()
  }, [location.search])

  const [lookup, setLookup] = useState<LookupState>(
    code ? { status: 'loading' } : { status: 'missing-code' },
  )
  const [name, setName] = useState('')
  const [password, setPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [localError, setLocalError] = useState('')

  useEffect(() => {
    if (!code) {
      // eslint-disable-next-line react-hooks/set-state-in-effect -- route changes without a code should replace stale lookup state
      setLookup({ status: 'missing-code' })
      return
    }
    let cancelled = false
    setLookup({ status: 'loading' })
    void (async () => {
      try {
        const data = await inviteApi.lookupAccountInvite(code)
        if (cancelled) return
        setLookup({ status: 'ok', data })
      } catch {
        if (cancelled) return
        // Any error — 404, 410, network — collapses to the same "ask the
        // inviter to resend" UX. Anti-enumeration is enforced server-side.
        setLookup({ status: 'invalid' })
      }
    })()
    return () => {
      cancelled = true
    }
  }, [code])

  const googleAvailable = appConfig.oauth_providers.includes('google')
  const microsoftAvailable = appConfig.oauth_providers.includes('microsoft')

  const handleOAuth = (provider: 'google' | 'microsoft') => {
    if (lookup.status !== 'ok') return
    const csrf = randomCsrf()
    try {
      sessionStorage.setItem('rf-oauth-state', csrf)
    } catch {
      // ignore — non-fatal
    }
    const stateValue = encodeOAuthState({
      csrf,
      accountInviteCode: code,
      invitedEmail: lookup.data.invited_email,
    })
    const url = buildOAuthAuthorizeUrl(provider, stateValue)
    window.location.href = url
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setLocalError('')
    clearError()

    if (lookup.status !== 'ok') return

    if (!name || !password) {
      setLocalError('Please fill in all fields')
      return
    }
    if (password !== confirmPassword) {
      setLocalError('Passwords do not match')
      return
    }
    if (password.length < 10) {
      setLocalError('Password must be at least 10 characters')
      return
    }

    try {
      await register({
        email: lookup.data.invited_email,
        password,
        name,
        account_invite_code: code,
      })
      // Invitees skip the welcome wizard — they're joining an existing shop.
      // The `?welcome=teammate` marker is decoded by the dashboard in Task 41
      // to surface the "Welcome to {account_name}" toast and pre-checked
      // checklist items.
      navigate('/?welcome=teammate', { replace: true })
    } catch {
      // Error is set in the store
    }
  }

  return (
    <>
      <PageMeta
        title="Join your team on ResolutionFlow"
        description="Accept an invite to join an existing ResolutionFlow account"
      />
      <div className="flex min-h-screen items-center justify-center bg-black px-4">
        <div className="pointer-events-none fixed inset-0 bg-[radial-gradient(circle_at_50%_0%,rgba(100,100,120,0.03),transparent_50%)]" />

        <div className="relative w-full max-w-md space-y-6">
          <div className="text-center">
            <div className="mb-4 flex justify-center sm:mb-6">
              <BrandLogo size="lg" />
            </div>
            <h1 className="text-3xl font-bold font-heading text-foreground tracking-tight">
              ResolutionFlow
            </h1>
          </div>

          {lookup.status === 'loading' && (
            <div className="bg-card border border-border rounded-xl p-6 text-center">
              <p className="text-sm text-muted-foreground">Loading invite…</p>
            </div>
          )}

          {(lookup.status === 'invalid' || lookup.status === 'missing-code') && (
            <div className="bg-card border border-border rounded-xl p-6 space-y-3">
              <h2 className="text-lg font-semibold text-foreground">
                This invite is no longer valid
              </h2>
              <p className="text-sm text-muted-foreground">
                {lookup.status === 'missing-code'
                  ? 'The invite link is missing its code.'
                  : 'This invite has expired, been used, or been revoked.'}{' '}
                Ask the person who invited you to resend it.
              </p>
              <a
                href="mailto:?subject=Please%20resend%20my%20ResolutionFlow%20invite&body=Hi%2C%20could%20you%20resend%20my%20ResolutionFlow%20invite%3F%20The%20link%20I%20got%20is%20no%20longer%20valid.%20Thanks!"
                className={cn(
                  'inline-block rounded-xl px-4 py-2 text-sm font-semibold btn-press',
                  'bg-primary text-white hover:brightness-110',
                )}
              >
                Email your inviter
              </a>
              <p className="text-xs text-muted-foreground">
                Already have an account?{' '}
                <Link to="/login" className="font-medium text-foreground hover:underline">
                  Sign in
                </Link>
              </p>
            </div>
          )}

          {lookup.status === 'ok' && (
            <>
              <div className="text-center">
                <p className="text-base font-medium text-foreground">
                  Join <span className="font-semibold">{lookup.data.account_name}</span> on
                  ResolutionFlow
                </p>
                <p className="mt-1 text-sm text-muted-foreground">
                  {lookup.data.inviter_name} invited you as {lookup.data.role}.
                </p>
              </div>

              <div className="bg-card border border-border rounded-xl p-6 space-y-4">
                {(error || localError) && (
                  <div className="rounded-xl border border-red-400/20 bg-red-400/10 p-3 text-sm text-red-400">
                    {localError || error}
                  </div>
                )}

                <div>
                  <p className="block text-sm font-medium text-foreground">
                    Joining as
                  </p>
                  <p
                    className={cn(
                      'mt-1 block w-full rounded-xl border border-border bg-card px-3 py-2',
                      'text-foreground',
                    )}
                    data-testid="invited-email"
                  >
                    {lookup.data.invited_email}
                  </p>
                  <p className="mt-1 text-xs text-muted-foreground">
                    The invite is locked to this email address.
                  </p>
                </div>

                {(googleAvailable || microsoftAvailable) && (
                  <div className="space-y-3">
                    {googleAvailable && (
                      <button
                        type="button"
                        onClick={() => handleOAuth('google')}
                        data-testid="oauth-google"
                        className={cn(
                          'w-full rounded-xl px-4 py-2.5 text-sm font-semibold btn-press',
                          'bg-card border border-border text-foreground hover:bg-foreground/5',
                          'focus:outline-hidden focus:ring-2 focus:ring-primary/30',
                          'transition-all',
                        )}
                      >
                        Continue with Google
                      </button>
                    )}
                    {microsoftAvailable && (
                      <button
                        type="button"
                        onClick={() => handleOAuth('microsoft')}
                        data-testid="oauth-microsoft"
                        className={cn(
                          'w-full rounded-xl px-4 py-2.5 text-sm font-semibold btn-press',
                          'bg-card border border-border text-foreground hover:bg-foreground/5',
                          'focus:outline-hidden focus:ring-2 focus:ring-primary/30',
                          'transition-all',
                        )}
                      >
                        Continue with Microsoft
                      </button>
                    )}

                    <div className="relative my-2">
                      <div className="absolute inset-0 flex items-center">
                        <div className="w-full border-t border-border" />
                      </div>
                      <div className="relative flex justify-center text-xs uppercase tracking-wider">
                        <span className="bg-card px-2 text-muted-foreground">
                          or set a password
                        </span>
                      </div>
                    </div>
                  </div>
                )}

                <form onSubmit={handleSubmit} className="space-y-4">
                  <div>
                    <label
                      htmlFor="name"
                      className="block text-sm font-medium text-foreground"
                    >
                      Full name
                    </label>
                    <input
                      id="name"
                      name="name"
                      type="text"
                      autoComplete="name"
                      required
                      value={name}
                      onChange={(e) => setName(e.target.value)}
                      className={cn(
                        'mt-1 block w-full rounded-xl border border-border bg-card px-3 py-2',
                        'text-foreground placeholder:text-muted-foreground',
                        'focus:border-primary focus:outline-hidden focus:ring-1 focus:ring-primary/20',
                      )}
                      placeholder="Jane Doe"
                    />
                  </div>

                  <div>
                    <label
                      htmlFor="password"
                      className="block text-sm font-medium text-foreground"
                    >
                      Password
                    </label>
                    <PasswordInput
                      id="password"
                      name="password"
                      autoComplete="new-password"
                      required
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      className={cn(
                        'mt-1 block w-full rounded-xl border border-border bg-card px-3 py-2',
                        'text-foreground placeholder:text-muted-foreground',
                        'focus:border-primary focus:outline-hidden focus:ring-1 focus:ring-primary/20',
                      )}
                      placeholder="••••••••••"
                    />
                    <p className="mt-1 text-xs text-muted-foreground">
                      Must be at least 10 characters
                    </p>
                  </div>

                  <div>
                    <label
                      htmlFor="confirmPassword"
                      className="block text-sm font-medium text-foreground"
                    >
                      Confirm password
                    </label>
                    <PasswordInput
                      id="confirmPassword"
                      name="confirmPassword"
                      autoComplete="new-password"
                      required
                      value={confirmPassword}
                      onChange={(e) => setConfirmPassword(e.target.value)}
                      className={cn(
                        'mt-1 block w-full rounded-xl border border-border bg-card px-3 py-2',
                        'text-foreground placeholder:text-muted-foreground',
                        'focus:border-primary focus:outline-hidden focus:ring-1 focus:ring-primary/20',
                      )}
                      placeholder="••••••••••"
                    />
                  </div>

                  <button
                    type="submit"
                    data-testid="accept-submit"
                    disabled={isLoading}
                    className={cn(
                      'w-full rounded-xl px-4 py-2.5 text-sm font-semibold btn-press',
                      'bg-primary text-white hover:brightness-110',
                      'focus:outline-hidden focus:ring-2 focus:ring-primary/30 focus:ring-offset-2 focus:ring-offset-black',
                      'disabled:cursor-not-allowed disabled:opacity-50',
                      'transition-all',
                    )}
                  >
                    {isLoading ? 'Joining…' : `Join ${lookup.data.account_name}`}
                  </button>
                </form>
              </div>
            </>
          )}

          <p className="text-center text-sm text-muted-foreground">
            Already have an account?{' '}
            <Link to="/login" className="font-medium text-foreground hover:underline">
              Sign in
            </Link>
          </p>
        </div>
      </div>
    </>
  )
}

export default AcceptInvitePage
