import { Input } from '@/components/ui/input'
import { useEffect, useRef, useState, KeyboardEvent, ClipboardEvent } from 'react'
import { cn } from '@/lib/utils'
import { ErrorClass } from '@/app/forms/Error'
import { Label } from '@radix-ui/react-label'

type SeedInputGroupProps = {
    error?: string
    value: string[]
    onChange: (seedWords: string[]) => void
    iseedLength?: number
}

export default function SeedInput({
    error,
    value,
    onChange,
    iseedLength = 12,
}: SeedInputGroupProps) {
    const [seedLength, setSeedLenght] = useState<number>(iseedLength);
    const [seedWords, setSeedWords] = useState<string[]>(() => value.length ? value : Array(seedLength).fill(''))
    const inputRefs = useRef<(HTMLInputElement | null)[]>([])

    useEffect(() => {
        inputRefs.current = inputRefs.current.slice(0, seedLength)
    }, [seedLength])

    const updateSeedWords = (words: string[]) => {
        setSeedWords(words)
        onChange(words)
    }

    const handleChange = (index: number, word: string) => {
        const updated = [...seedWords]
        updated[index] = word
        updateSeedWords(updated)
    }

    const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>, index: number) => {
        if (e.ctrlKey && e.key.toLowerCase() === 'a') {
            e.preventDefault()
            inputRefs.current.forEach(ref => ref?.select())
        } else if (e.ctrlKey && e.key.toLowerCase() === 'v') {
            // Do nothing here, wait for onPaste
        } else if (e.key === 'Delete') {
            updateSeedWords(Array(seedLength).fill(''))
        } else if (e.key === ' ' || e.key === 'Tab') {
            e.preventDefault()
            if (index < seedLength - 1) {
                inputRefs.current[index + 1]?.focus()
            }
        } else if (e.key === 'Backspace' && seedWords[index] === '') {
            if (index > 0) {
                inputRefs.current[index - 1]?.focus()
            }
        }
    }

    const handlePaste = async (e: ClipboardEvent<HTMLInputElement>) => {
        e.preventDefault()
        const text = e.clipboardData.getData('text/plain')
        const words = text.trim().split(/\s+/).slice(0, seedLength)
        console.log(words.length)
        if (words.length > 0) {
            updateSeedWords([
                ...words,
                ...Array(Math.max(seedLength - words.length, 0)).fill('')
            ])
            inputRefs.current[words.length-1]?.select()
        }
    }

    return (
        <div className='flex flex-col gap-1'>

            <div className="flex items-center justify-between">
                <Label className="font-semibold leading-5 py-1 text-[14px]">
                    Seed Phrase
                </Label>
                <select
                    value={seedWords.length}
                    onChange={(e) => {
                        const newLength = parseInt(e.target.value)
                        setSeedWords((prev) => {
                            const trimmed = prev.slice(0, newLength)
                            return [...trimmed, ...Array(Math.max(newLength - trimmed.length, 0)).fill('')]
                        })
                        setSeedLenght(newLength)
                    }}
                    className="bg-transparent border-none text-sm text-muted-foreground cursor-pointer outline-none px-2 py-1"
                >
                    <option className="bg-secondary text-foreground" value={12}>12 words</option>
                    <option className="bg-secondary text-foreground" value={24}>24 words</option>

                </select>
            </div>
            <div className='grid grid-cols-3 sm:grid-cols-4 md:grid-cols-3 gap-2'>
                {seedWords.map((word, index) => (
                    <Input
                        key={index}
                        placeholder={`${index + 1}.`}
                        value={word}
                        onChange={(e) => handleChange(index, e.target.value.trim())}
                        onKeyDown={(e) => handleKeyDown(e, index)}
                        onPaste={handlePaste}
                        ref={el => { inputRefs.current[index] = el }}
                        className={cn(
                            error ? `${ErrorClass} focus-visible:!ring-0 focus-visible:border-[rgb(240,97,109)]` : '',
                            'text-sm'
                        )}
                    />
                ))}
            </div>
        </div>
    )
}
