'use client'

import Link from 'next/link'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { FaEye, FaEyeSlash } from 'react-icons/fa'
import { FaXmark } from 'react-icons/fa6'
import AuthSkeleton from '@/components/Skeletons/AuthSkeleton'
import Toast from '@/components/Toast'

function cx(...classes: Array<string | false | null | undefined>) {
    return classes.filter(Boolean).join(' ')
}

function isValidUserId(id: string) {
    const s = id.trim()
    if (s.length < 6 || s.length > 12) return false
    return /^[A-Za-z0-9]+$/.test(s)
}

function isValidEmail(email: string) {
    const s = email.trim()
    if (!s.includes('@')) return false
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s)
}

function countPasswordKinds(pw: string) {
    const hasLetter = /[A-Za-z]/.test(pw)
    const hasDigit = /\d/.test(pw)
    const hasSpecial = /[^A-Za-z0-9]/.test(pw)
    return Number(hasLetter) + Number(hasDigit) + Number(hasSpecial)
}

function hasTripleSame(pw: string) {
    return /(.)\1\1/.test(pw)
}

function hasSequentialRun(pw: string) {
    const s = pw
    for (let i = 0; i + 2 < s.length; i++) {
        const a = s.charCodeAt(i)
        const b = s.charCodeAt(i + 1)
        const c = s.charCodeAt(i + 2)
        if (b === a + 1 && c === b + 1) return true
        if (b === a - 1 && c === b - 1) return true
    }
    return false
}

function validatePassword(pw: string, userId: string) {
    const s = pw
    const lengthOk = s.length >= 10 && s.length <= 15
    const comboOk = countPasswordKinds(s) >= 2
    const noTriple = !hasTripleSame(s) && !hasSequentialRun(s)
    const noSpaceAmp = !/\s/.test(s) && !s.includes('&')
    const noId = userId.trim().length >= 3 ? !s.toLowerCase().includes(userId.trim().toLowerCase()) : true
    const ok = lengthOk && comboOk && noTriple && noSpaceAmp && noId
    return { ok, lengthOk, comboOk, noTriple, noSpaceAmp, noId }
}

const EMAIL_DOMAINS = [
    'gmail.com',
    'yahoo.com',
    'yahoo.com.tw',
    'hotmail.com',
    'outlook.com',
    'icloud.com',
    'proton.me',
    'protonmail.com',
    'qq.com',
    '163.com',
]

export default function RegisterPageClient() {
    // Translation
    const { t } = useTranslation()

    // State
    const [isLoading, setIsLoading] = useState(true)
    const [isSubmitting, setIsSubmitting] = useState(false)
    const [submitError, setSubmitError] = useState<string | null>(null)
    const [showSuccessToast, setShowSuccessToast] = useState(false)
    const [uid, setUid] = useState('')
    const [pw, setPw] = useState('')
    const [pw2, setPw2] = useState('')
    const [pwShow, setPwShow] = useState(false)
    const [email, setEmail] = useState('')
    const [agreeTerms, setAgreeTerms] = useState(false)
    const [uidTouched, setUidTouched] = useState(false)
    const [pwTouched, setPwTouched] = useState(false)
    const [pw2Touched, setPw2Touched] = useState(false)
    const [emailTouched, setEmailTouched] = useState(false)
    const [emailSuggestOpen, setEmailSuggestOpen] = useState(false)
    const [emailSuggest, setEmailSuggest] = useState<string[]>([])

    // Memo
    const pass = useMemo(() => validatePassword(pw, uid), [pw, uid])
    const uidOk = useMemo(() => isValidUserId(uid), [uid])
    const emailOk = useMemo(() => isValidEmail(email), [email])
    const pw2Ok = pw2.length > 0 && pw2 === pw
    const formOk = uidOk && pass.ok && pw2Ok && emailOk && agreeTerms

    // Refs
    const emailWrapRef = useRef<HTMLDivElement | null>(null)

    const updateEmailSuggest = useCallback((v: string) => {
        const s = v.trim()
        const at = s.indexOf('@')
        if (at < 0) {
            setEmailSuggestOpen(false)
            setEmailSuggest([])
            return
        }
        const left = s.slice(0, at)
        const right = s.slice(at + 1).toLowerCase()
        if (!left) {
            setEmailSuggestOpen(false)
            setEmailSuggest([])
            return
        }
        const list = EMAIL_DOMAINS.filter((d) => d.startsWith(right)).map((d) => `${left}@${d}`)
        setEmailSuggest(list)
        setEmailSuggestOpen(list.length > 0 && right.length >= 0)
    }, [])

    useEffect(() => {
        const timer = setTimeout(() => {
            setIsLoading(false)
        }, 600)

        return () => clearTimeout(timer)
    }, [])

    useEffect(() => {
        const onDown = (e: MouseEvent) => {
            const t = e.target as Node | null
            if (!t) return
            if (emailWrapRef.current?.contains(t)) return
            setEmailSuggestOpen(false)
        }
        document.addEventListener('mousedown', onDown)
        return () => document.removeEventListener('mousedown', onDown)
    }, [])

    if (isLoading) {
        return <AuthSkeleton type="register" />
    }

    return (
        <div className="w-full">
            <div className="mx-auto w-full max-w-[560px]">
                <div className="w-full rounded-2xl bg-white dark:bg-[#0c0d0e] shadow-2xl border border-gray-200 dark:border-gray-800">
                    <div className="px-6 py-6">
                        <div className="flex items-center justify-between">
                            <div className="text-xl font-semibold text-gray-900 dark:text-white">{t('auth.register.title')}</div>
                            <div className="flex items-center gap-2">
                                <Link
                                    href="/login"
                                    className="h-9 px-3 rounded-lg text-sm font-semibold inline-flex items-center justify-center transition-colors text-[#525661] dark:text-gray-300 hover:bg-[rgba(145,150,161,0.1)]"
                                >
                                    {t('auth.login.title')}
                                </Link>
                                <Link
                                    href="/register"
                                    className={cx(
                                        'h-9 px-3 rounded-lg text-sm font-semibold inline-flex items-center justify-center transition-colors',
                                        'bg-[#eeeff1] dark:bg-[#1a1c21] text-gray-900 dark:text-white'
                                    )}
                                >
                                    {t('auth.register.title')}
                                </Link>
                            </div>
                        </div>

                        <form
                            autoComplete="off"
                            className="mt-6 space-y-5"
                            onSubmit={async (e) => {
                                e.preventDefault()
                                setSubmitError(null)

                                if (!formOk) {
                                    setSubmitError(t('auth.register.errors.formInvalid'))
                                    return
                                }

                                setIsSubmitting(true)
                                try {
                                    const res = await fetch('/api/auth/register', {
                                        method: 'POST',
                                        headers: {
                                            'Content-Type': 'application/json',
                                        },
                                        body: JSON.stringify({
                                            account: uid.trim(),
                                            password: pw,
                                            email: email.trim(),
                                        }),
                                    })

                                    const data = await res.json()

                                    if (!res.ok || !data.ok) {
                                        setSubmitError(data.message || t('auth.register.errors.submitFailed'))
                                        return
                                    }

                                    setShowSuccessToast(true)
                                } catch (error) {
                                    console.error('Register error:', error)
                                    setSubmitError(t('auth.register.errors.submitFailed'))
                                } finally {
                                    setIsSubmitting(false)
                                }
                            }}
                        >
                            <div>
                                <div className="text-sm text-gray-500 dark:text-gray-400">{t('auth.register.account')}</div>
                                <div
                                    className={cx(
                                        'mt-2 flex items-center h-[50px] px-[14px] rounded-lg border transition-colors',
                                        uidTouched && !uidOk ? 'border-[#ef565f]' : 'border-[#d5d7dc] dark:border-gray-700',
                                        'focus-within:border-[#acb0b9] dark:focus-within:border-gray-500'
                                    )}
                                >
                                    <input
                                        value={uid}
                                        onChange={(e) => setUid(e.target.value)}
                                        onBlur={() => setUidTouched(true)}
                                        name="gp_register_uid"
                                        autoComplete="off"
                                        autoCapitalize="none"
                                        autoCorrect="off"
                                        spellCheck={false}
                                        readOnly
                                        onFocus={(e) => {
                                            e.currentTarget.readOnly = false
                                        }}
                                        placeholder={t('auth.register.accountPlaceholder')}
                                        className="w-full h-full bg-transparent text-[16px] text-gray-900 dark:text-white outline-none pr-3"
                                        maxLength={12}
                                        minLength={6}
                                    />
                                    {uid.length > 0 && (
                                        <button
                                            type="button"
                                            tabIndex={-1}
                                            className="w-5 h-5 rounded-full bg-[#E2E4E9] dark:bg-[#2f3137] text-[#525661] dark:text-[#D5D7DC] text-xs flex items-center justify-center"
                                            onClick={() => setUid('')}
                                            aria-label={t('auth.register.clear')}
                                        >
                                            <FaXmark className="w-3 h-3" />
                                        </button>
                                    )}
                                </div>
                                {uidTouched && !uidOk && (
                                    <div className="mt-2 text-sm text-[#ef565f]">{t('auth.register.errors.accountInvalid')}</div>
                                )}
                            </div>

                            <div>
                                <div className="text-sm text-gray-500 dark:text-gray-400">{t('auth.register.password')}</div>
                                <div
                                    className={cx(
                                        'mt-2 flex items-center h-[50px] px-[14px] rounded-lg border transition-colors',
                                        pwTouched && !pass.ok ? 'border-[#ef565f]' : 'border-[#d5d7dc] dark:border-gray-700',
                                        'focus-within:border-[#acb0b9] dark:focus-within:border-gray-500'
                                    )}
                                >
                                    <input
                                        value={pw}
                                        onChange={(e) => setPw(e.target.value)}
                                        onBlur={() => setPwTouched(true)}
                                        name="gp_register_password"
                                        autoComplete="new-password"
                                        autoCapitalize="none"
                                        autoCorrect="off"
                                        spellCheck={false}
                                        readOnly
                                        onFocus={(e) => {
                                            e.currentTarget.readOnly = false
                                        }}
                                        placeholder={t('auth.register.passwordPlaceholder')}
                                        type={pwShow ? 'text' : 'password'}
                                        className="w-full h-full bg-transparent text-[16px] text-gray-900 dark:text-white outline-none pr-3"
                                        maxLength={15}
                                        minLength={10}
                                    />
                                    {pw.length > 0 && (
                                        <button
                                            type="button"
                                            tabIndex={-1}
                                            className="w-5 h-5 rounded-full bg-[#E2E4E9] dark:bg-[#2f3137] text-[#525661] dark:text-[#D5D7DC] text-xs flex items-center justify-center"
                                            onClick={() => setPw('')}
                                            aria-label={t('auth.register.clear')}
                                        >
                                            <FaXmark className="w-3 h-3" />
                                        </button>
                                    )}
                                    <button
                                        type="button"
                                        tabIndex={-1}
                                        className="ml-2 w-7 h-7 rounded-lg hover:bg-[rgba(145,150,161,0.1)] active:bg-[rgba(23,25,28,0.3)] flex items-center justify-center text-sm text-gray-700 dark:text-gray-200"
                                        onClick={() => setPwShow((v) => !v)}
                                        aria-label={pwShow ? t('auth.register.hidePassword') : t('auth.register.showPassword')}
                                    >
                                        {pwShow ? <FaEye className="w-4 h-4" /> : <FaEyeSlash className="w-4 h-4" />}
                                    </button>
                                </div>

                                {pwTouched && !pass.ok && (
                                    <div className="mt-2 text-sm text-[#ef565f]">
                                        {t('auth.register.errors.passwordInvalid')}
                                    </div>
                                )}
                            </div>

                            <div>
                                <div className="text-sm text-gray-500 dark:text-gray-400">{t('auth.register.confirmPassword')}</div>
                                <div
                                    className={cx(
                                        'mt-2 flex items-center h-[50px] px-[14px] rounded-lg border transition-colors',
                                        pw2Touched && !pw2Ok ? 'border-[#ef565f]' : 'border-[#d5d7dc] dark:border-gray-700',
                                        'focus-within:border-[#acb0b9] dark:focus-within:border-gray-500'
                                    )}
                                >
                                    <input
                                        value={pw2}
                                        onChange={(e) => setPw2(e.target.value)}
                                        onBlur={() => setPw2Touched(true)}
                                        name="gp_register_password_confirm"
                                        autoComplete="new-password"
                                        autoCapitalize="none"
                                        autoCorrect="off"
                                        spellCheck={false}
                                        readOnly
                                        onFocus={(e) => {
                                            e.currentTarget.readOnly = false
                                        }}
                                        placeholder={t('auth.register.confirmPasswordPlaceholder')}
                                        type={pwShow ? 'text' : 'password'}
                                        className="w-full h-full bg-transparent text-[16px] text-gray-900 dark:text-white outline-none pr-3"
                                        maxLength={15}
                                        minLength={10}
                                    />
                                    {pw2.length > 0 && (
                                        <button
                                            type="button"
                                            tabIndex={-1}
                                            className="w-5 h-5 rounded-full bg-[#E2E4E9] dark:bg-[#2f3137] text-[#525661] dark:text-[#D5D7DC] text-xs flex items-center justify-center"
                                            onClick={() => setPw2('')}
                                            aria-label={t('auth.register.clear')}
                                        >
                                            <FaXmark className="w-3 h-3" />
                                        </button>
                                    )}
                                </div>
                                {pw2Touched && !pw2Ok && (
                                    <div className="mt-2 text-sm text-[#ef565f]">{t('auth.register.errors.passwordMismatch')}</div>
                                )}
                            </div>

                            <div>
                                <div className="text-sm text-gray-500 dark:text-gray-400">{t('auth.register.email')}</div>
                                <div className="relative" ref={emailWrapRef}>
                                    <div
                                        className={cx(
                                            'mt-2 flex items-center h-[50px] px-[14px] rounded-lg border transition-colors',
                                            emailTouched && !emailOk ? 'border-[#ef565f]' : 'border-[#d5d7dc] dark:border-gray-700',
                                            'focus-within:border-[#acb0b9] dark:focus-within:border-gray-500'
                                        )}
                                    >
                                        <input
                                            value={email}
                                            onChange={(e) => {
                                                const v = e.target.value
                                                setEmail(v)
                                                updateEmailSuggest(v)
                                            }}
                                            onBlur={() => setEmailTouched(true)}
                                            name="gp_register_email"
                                            autoComplete="off"
                                            autoCapitalize="none"
                                            autoCorrect="off"
                                            spellCheck={false}
                                            readOnly
                                            onFocus={(e) => {
                                                e.currentTarget.readOnly = false
                                                updateEmailSuggest(email)
                                            }}
                                            placeholder={t('auth.register.emailPlaceholder')}
                                            className="w-full h-full bg-transparent text-[16px] text-gray-900 dark:text-white outline-none pr-3"
                                        />
                                        {email.length > 0 && (
                                            <button
                                                type="button"
                                                tabIndex={-1}
                                                className="w-5 h-5 rounded-full bg-[#E2E4E9] dark:bg-[#2f3137] text-[#525661] dark:text-[#D5D7DC] text-xs flex items-center justify-center"
                                                onClick={() => {
                                                    setEmail('')
                                                    setEmailSuggestOpen(false)
                                                    setEmailSuggest([])
                                                }}
                                                aria-label={t('auth.register.clear')}
                                            >
                                                <FaXmark className="w-3 h-3" />
                                            </button>
                                        )}
                                    </div>

                                    {emailSuggestOpen && emailSuggest.length > 0 && (
                                        <div className="absolute left-0 right-0 top-full mt-2 z-[50] overflow-hidden rounded-lg border border-[#acb0b9] dark:border-gray-700 bg-white dark:bg-[#0c0d0e] shadow-lg">
                                            {emailSuggest.slice(0, 6).map((s) => (
                                                <button
                                                    key={s}
                                                    type="button"
                                                    className="w-full text-left px-3 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-[#1a1c21]"
                                                    onMouseDown={(e) => e.preventDefault()}
                                                    onClick={() => {
                                                        setEmail(s)
                                                        setEmailSuggestOpen(false)
                                                    }}
                                                >
                                                    {s}
                                                </button>
                                            ))}
                                        </div>
                                    )}
                                </div>
                                {emailTouched && !emailOk && (
                                    <div className="mt-2 text-sm text-[#ef565f]">{t('auth.register.errors.emailInvalid')}</div>
                                )}
                            </div>

                            <div className="pt-1">
                                <label className="relative flex items-center gap-3 cursor-pointer select-none">
                                    <input
                                        type="checkbox"
                                        checked={agreeTerms}
                                        onChange={(e) => setAgreeTerms(e.target.checked)}
                                        className="peer sr-only"
                                    />
                                    <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded border-2 border-[#d5d7dc] dark:border-gray-600 transition-colors peer-checked:border-black peer-checked:bg-black dark:peer-checked:border-white dark:peer-checked:bg-white" />
                                    <span className="absolute left-0 flex h-5 w-5 items-center justify-center pointer-events-none opacity-0 transition-opacity peer-checked:opacity-100">
                                        <svg className="h-3 w-3 text-white dark:text-black" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
                                            <path d="M5 13l4 4L19 7" />
                                        </svg>
                                    </span>
                                    <span className="text-sm text-gray-700 dark:text-gray-200">{t('auth.register.agreeTerms')}</span>
                                </label>
                            </div>

                            {submitError && (
                                <div className="pt-2">
                                    <div className="text-sm text-[#ef565f] bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg px-4 py-3">
                                        {submitError}
                                    </div>
                                </div>
                            )}

                            <div className="pt-2">
                                <button
                                    type="submit"
                                    disabled={!formOk || isSubmitting}
                                    className={cx(
                                        'w-full h-[52px] rounded-xl text-[16px] font-medium transition-colors',
                                        formOk && !isSubmitting
                                            ? 'border border-[#d5d7dc] dark:border-gray-700 hover:bg-[rgba(145,150,161,0.1)] active:bg-[rgba(23,25,28,0.3)] text-gray-900 dark:text-white'
                                            : 'bg-[#f1f2f4] dark:bg-[#232529] text-[rgba(23,25,28,0.3)] dark:text-white/30 pointer-events-none'
                                    )}
                                >
                                    {isSubmitting ? t('auth.register.submitting') : t('auth.register.submit')}
                                </button>

                                <div className="mt-3 text-sm text-right">
                                    <Link
                                        href="/login"
                                        className="text-[#525661] dark:text-gray-300 hover:text-gray-900 dark:hover:text-white underline underline-offset-4"
                                    >
                                        {t('auth.register.alreadyHaveAccount')}
                                    </Link>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            {showSuccessToast && (
                <Toast
                    id="register-success"
                    message={t('auth.register.success')}
                    type="success"
                    duration={2000}
                    onClose={() => {
                        window.location.href = '/login?registered=1'
                    }}
                />
            )}
        </div>
    )
}


