import { useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { useAuthStore } from '@/store/authStore'
import { inviteApi } from '@/api/invite'
import { BrandLogo } from '@/components/common/BrandLogo'
import { PasswordInput } from '@/components/common/PasswordInput'
import { cn } from '@/lib/utils'

export function RegisterPage() {
  const navigate = useNavigate()
  const { register, isLoading, error, clearError } = useAuthStore()

  const [inviteCode, setInviteCode] = useState('')
  const [inviteCodeStatus, setInviteCodeStatus] = useState<'idle' | 'checking' | 'valid' | 'invalid'>('idle')
  const [inviteCodeMessage, setInviteCodeMessage] = useState('')
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [localError, setLocalError] = useState('')

  const validateInviteCode = async (code: string) => {
    if (!code.trim()) {
      setInviteCodeStatus('idle')
      setInviteCodeMessage('')
      return
    }

    setInviteCodeStatus('checking')
    try {
      const result = await inviteApi.validateCode(code.trim())
      setInviteCodeStatus(result.valid ? 'valid' : 'invalid')
      setInviteCodeMessage(result.message)
    } catch {
      setInviteCodeStatus('invalid')
      setInviteCodeMessage('Failed to validate invite code')
    }
  }

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

    // Only validate invite code if one was entered
    if (inviteCode.trim() && inviteCodeStatus === 'invalid') {
      setLocalError('Please enter a valid invite code')
      return
    }

    if (!name || !email || !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 {
      // Only include invite_code if provided
      const userData = inviteCode.trim()
        ? { email, password, name, invite_code: inviteCode.trim() }
        : { email, password, name }
      await register(userData)
      navigate('/', { replace: true })
    } catch {
      // Error is set in the store
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-black px-4">
      {/* Subtle radial overlay */}
      <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-8">
        <div className="text-center">
          <div className="mb-4 flex justify-center sm:mb-6">
            <div className="w-16 h-16 rounded-2xl bg-white flex items-center justify-center sm:w-20 sm:h-20">
              <BrandLogo size="lg" className="h-10 w-10 invert sm:h-12 sm:w-12" />
            </div>
          </div>
          <h1 className="text-3xl font-bold font-heading text-foreground tracking-tight">
            ResolutionFlow
          </h1>
          <p className="mt-2 text-base font-medium text-muted-foreground sm:mt-3 sm:text-lg">
            Decision Tree Platform
          </p>
          <p className="mt-1 text-sm text-muted-foreground sm:mt-2">
            Create your account
          </p>
        </div>

        <form onSubmit={handleSubmit} className="mt-8 space-y-6">
          <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>
              <label htmlFor="inviteCode" className="block text-sm font-medium text-foreground">
                Invite code
              </label>
              <input
                id="inviteCode"
                name="inviteCode"
                type="text"
                value={inviteCode}
                onChange={(e) => {
                  setInviteCode(e.target.value.toUpperCase())
                  setInviteCodeStatus('idle')
                }}
                onBlur={(e) => validateInviteCode(e.target.value)}
                className={cn(
                  'mt-1 block w-full rounded-xl border bg-card px-3 py-2 font-mono tracking-wider',
                  'text-foreground placeholder:text-muted-foreground',
                  'focus:outline-none focus:ring-1',
                  inviteCodeStatus === 'valid' && 'border-emerald-400/50 focus:border-emerald-400 focus:ring-emerald-400/30',
                  inviteCodeStatus === 'invalid' && 'border-red-400/50 focus:border-red-400 focus:ring-red-400/30',
                  inviteCodeStatus === 'idle' && 'border-border focus:border-primary focus:ring-primary/20',
                  inviteCodeStatus === 'checking' && 'border-border focus:border-primary focus:ring-primary/20'
                )}
                placeholder="ABCD1234"
              />
              {inviteCodeStatus === 'checking' && (
                <p className="mt-1 text-xs text-muted-foreground">Validating...</p>
              )}
              {inviteCodeStatus === 'valid' && (
                <p className="mt-1 text-xs text-emerald-400">{inviteCodeMessage}</p>
              )}
              {inviteCodeStatus === 'invalid' && (
                <p className="mt-1 text-xs text-red-400">{inviteCodeMessage}</p>
              )}
            </div>

            <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-none focus:ring-1 focus:ring-primary/20'
                )}
                placeholder="John Smith"
              />
            </div>

            <div>
              <label htmlFor="email" className="block text-sm font-medium text-foreground">
                Email address
              </label>
              <input
                id="email"
                name="email"
                type="email"
                autoComplete="email"
                required
                value={email}
                onChange={(e) => setEmail(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-none focus:ring-1 focus:ring-primary/20'
                )}
                placeholder="you@example.com"
              />
            </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-none 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-none focus:ring-1 focus:ring-primary/20'
                )}
                placeholder="••••••••••"
              />
            </div>

            <button
              type="submit"
              disabled={isLoading}
              className={cn(
                'w-full rounded-xl px-4 py-2.5 text-sm font-semibold btn-press',
                'bg-gradient-brand text-white shadow-lg shadow-primary/20 hover:opacity-90',
                'focus:outline-none 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 ? 'Creating account...' : 'Create account'}
            </button>
          </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>
        </form>
      </div>
    </div>
  )
}

export default RegisterPage
