"use client"

import { useState } from 'react'
import Link from 'next/link'
import { Button } from './ui/button'
import {
  ArrowRight,
  ArrowLeft,
  User,
  Mail,
  Lock,
  Eye,
  EyeOff,
  ShieldCheck,
  KeyRound,
  LucideIcon,
} from 'lucide-react'
import { useAuth } from '../contexts/AuthContext'
import { useRouter } from 'next/navigation'
import { useTranslations, useLocale } from 'next-intl'

type Step = 'form' | 'verify' | 'success'

export default function UCPRegister() {
  const t = useTranslations('register')
  const locale = useLocale()
  const { setUserFromRegistration } = useAuth()
  const router = useRouter()

  const [step, setStep] = useState<Step>('form')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const [username, setUsername] = useState('')
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [verificationCode, setVerificationCode] = useState('')
  const [showPassword, setShowPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)

  const sendVerificationCode = async () => {
    const response = await fetch('/api/auth/register/send-code', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username, email, password, confirmPassword }),
    })
    const data = await response.json()

    if (!response.ok) {
      throw new Error(data.error || t('errors.generic'))
    }

    return data
  }

  const handleSendCode = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    setError(null)

    try {
      await sendVerificationCode()
      setVerificationCode('')
      setStep('verify')
    } catch (err) {
      setError(err instanceof Error ? err.message : t('errors.network'))
    } finally {
      setLoading(false)
    }
  }

  const handleVerifyCode = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    setError(null)

    try {
      const response = await fetch('/api/auth/register/verify-code', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, code: verificationCode }),
      })
      const data = await response.json()

      if (!response.ok) {
        setError(data.error || t('errors.generic'))
        return
      }

      setUserFromRegistration(data.user)
      setStep('success')
      setTimeout(() => router.push('/dashboard'), 1500)
    } catch {
      setError(t('errors.network'))
    } finally {
      setLoading(false)
    }
  }

  const handleResendCode = async () => {
    setLoading(true)
    setError(null)

    try {
      await sendVerificationCode()
      setVerificationCode('')
    } catch (err) {
      setError(err instanceof Error ? err.message : t('errors.network'))
    } finally {
      setLoading(false)
    }
  }

  const subtitle =
    step === 'form'
      ? t('subtitle.form')
      : step === 'verify'
        ? t('subtitle.verify')
        : t('subtitle.success')

  return (
    <section className="min-h-screen relative overflow-hidden bg-gradient-to-b from-[#0b1220] via-[#0a1020] to-[#070b15]">
      <div
        className="absolute inset-0 bg-cover bg-center opacity-20"
        style={{ backgroundImage: 'url(/images/background2.webp)' }}
      />

      <div className="relative z-10 container mx-auto px-4 py-16 min-h-screen flex items-center justify-center">
        <div className="relative max-w-md w-full bg-[#0f1620]/70 backdrop-blur-sm rounded-2xl p-6 md:p-8 border border-[#0087FF]/20 shadow-xl">
          <div className="absolute top-4 right-4 inline-flex items-center gap-2 px-3 py-1 rounded-full bg-emerald-500/10 border border-emerald-400/30 text-emerald-300 text-xs">
            <ShieldCheck className="w-4 h-4" />
            <span>{t('secure')}</span>
          </div>

          <div className="text-center mb-8">
            <img src="/images/logo.webp" alt="UrbanGamers" className="w-14 h-14 mx-auto mb-3" />
            <h1 className="text-2xl font-bold text-white">{t('title')}</h1>
            <p className="text-gray-400 text-sm">{subtitle}</p>
          </div>

          {error && (
            <div className="mb-6 p-3 bg-red-500/10 border border-red-500/30 rounded-xl">
              <p className="text-red-400 text-sm text-center">{error}</p>
            </div>
          )}

          {step === 'form' && (
            <form onSubmit={handleSendCode} className="space-y-4">
              <Field
                id="username"
                label={t('username.label')}
                placeholder={t('username.placeholder')}
                value={username}
                onChange={setUsername}
                icon={User}
                autoComplete="username"
              />

              <Field
                id="email"
                label={t('email.label')}
                placeholder={t('email.placeholder')}
                value={email}
                onChange={setEmail}
                icon={Mail}
                type="email"
                autoComplete="email"
              />

              <PasswordField
                id="password"
                label={t('password.label')}
                placeholder={t('password.placeholder')}
                value={password}
                onChange={setPassword}
                show={showPassword}
                onToggle={() => setShowPassword(!showPassword)}
              />

              <PasswordField
                id="confirmPassword"
                label={t('confirmPassword.label')}
                placeholder={t('confirmPassword.placeholder')}
                value={confirmPassword}
                onChange={setConfirmPassword}
                show={showConfirmPassword}
                onToggle={() => setShowConfirmPassword(!showConfirmPassword)}
              />

              <SubmitButton
                loading={loading}
                label={t('continue')}
                loadingLabel={t('sendingCode')}
              />
            </form>
          )}

          {step === 'verify' && (
            <form onSubmit={handleVerifyCode} className="space-y-4">
              <p className="text-gray-400 text-sm text-center">
                {t('sentTo', { email })}
              </p>

              <Field
                id="verificationCode"
                label={t('code.label')}
                placeholder={t('code.placeholder')}
                value={verificationCode}
                onChange={setVerificationCode}
                icon={KeyRound}
                type="text"
                inputMode="numeric"
                maxLength={6}
                autoComplete="one-time-code"
                className="tracking-[0.35em] text-center pl-4"
              />

              <SubmitButton
                loading={loading}
                label={t('verify')}
                loadingLabel={t('verifying')}
              />

              <div className="flex items-center justify-between gap-3 pt-1">
                <button
                  type="button"
                  onClick={() => {
                    setError(null)
                    setStep('form')
                  }}
                  className="inline-flex items-center gap-2 text-sm text-gray-400 hover:text-white transition-colors"
                >
                  <ArrowLeft className="w-4 h-4" />
                  {t('back')}
                </button>

                <button
                  type="button"
                  onClick={handleResendCode}
                  disabled={loading}
                  className="text-sm text-[#8ab4ff] hover:text-white transition-colors disabled:opacity-50"
                >
                  {loading ? t('resending') : t('resendCode')}
                </button>
              </div>
            </form>
          )}

          {step === 'success' && (
            <div className="text-center py-6">
              <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-emerald-500/10 border border-emerald-400/30 flex items-center justify-center">
                <ShieldCheck className="w-8 h-8 text-emerald-300" />
              </div>
              <p className="text-white font-medium mb-2">{t('successTitle')}</p>
              <p className="text-gray-400 text-sm">{t('successMessage')}</p>
            </div>
          )}

          {step !== 'success' && (
            <p className="text-center text-gray-400 text-xs mt-6">
              {t.rich('hasAccount', {
                login: (chunks) => (
                  <Link href={`/${locale}/login`} className="text-[#8ab4ff] hover:text-white">
                    {chunks}
                  </Link>
                ),
              })}
            </p>
          )}
        </div>
      </div>
    </section>
  )
}

function Field({
  id,
  label,
  placeholder,
  value,
  onChange,
  icon: Icon,
  type = 'text',
  autoComplete,
  inputMode,
  maxLength,
  className = '',
}: {
  id: string
  label: string
  placeholder: string
  value: string
  onChange: (value: string) => void
  icon: LucideIcon
  type?: string
  autoComplete?: string
  inputMode?: React.HTMLAttributes<HTMLInputElement>['inputMode']
  maxLength?: number
  className?: string
}) {
  return (
    <div className="space-y-2">
      <label htmlFor={id} className="block text-sm font-medium text-gray-300">
        {label}
      </label>
      <div className="relative">
        <input
          type={type}
          id={id}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          className={`w-full px-4 py-3 pl-12 bg-[#0c1320]/80 border border-[#0087FF]/20 rounded-2xl text-white placeholder-gray-400 focus:outline-none focus:border-[#0087FF] focus:ring-0 ${className}`}
          placeholder={placeholder}
          required
          autoComplete={autoComplete}
          inputMode={inputMode}
          maxLength={maxLength}
        />
        <div className="absolute left-3 top-1/2 -translate-y-1/2 w-8 h-8 rounded-xl bg-[#0087FF]/10 flex items-center justify-center border border-[#0087FF]/20">
          <Icon className="w-4 h-4 text-[#8ab4ff]" />
        </div>
      </div>
    </div>
  )
}

function PasswordField({
  id,
  label,
  placeholder,
  value,
  onChange,
  show,
  onToggle,
}: {
  id: string
  label: string
  placeholder: string
  value: string
  onChange: (value: string) => void
  show: boolean
  onToggle: () => void
}) {
  return (
    <div className="space-y-2">
      <label htmlFor={id} className="block text-sm font-medium text-gray-300">
        {label}
      </label>
      <div className="relative">
        <input
          type={show ? 'text' : 'password'}
          id={id}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          className="w-full px-4 py-3 pr-12 pl-12 bg-[#0c1320]/80 border border-[#0087FF]/20 rounded-2xl text-white placeholder-gray-400 focus:outline-none focus:border-[#0087FF] focus:ring-0"
          placeholder={placeholder}
          required
          autoComplete="new-password"
        />
        <div className="absolute left-3 top-1/2 -translate-y-1/2 w-8 h-8 rounded-xl bg-[#0087FF]/10 flex items-center justify-center border border-[#0087FF]/20">
          <Lock className="w-4 h-4 text-[#8ab4ff]" />
        </div>
        <button
          type="button"
          onClick={onToggle}
          className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-white"
        >
          {show ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
        </button>
      </div>
    </div>
  )
}

function SubmitButton({
  loading,
  label,
  loadingLabel,
}: {
  loading: boolean
  label: string
  loadingLabel: string
}) {
  return (
    <Button
      type="submit"
      disabled={loading}
      className="w-full bg-gradient-to-r from-[#0087FF] to-[#8ab4ff] text-white hover:from-[#0066CC] hover:to-[#6a9eff] rounded-full px-4 py-3 text-sm font-semibold shadow-lg shadow-[#0087FF]/20"
    >
      {loading ? (
        <div className="flex items-center justify-center space-x-2">
          <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white" />
          <span>{loadingLabel}</span>
        </div>
      ) : (
        <div className="flex items-center justify-center space-x-2">
          <span className="font-medium">{label}</span>
          <ArrowRight className="w-5 h-5" />
        </div>
      )}
    </Button>
  )
}
