'use client'

import { useMutation } from '@apollo/client'
import { MessageSquare, ArrowLeft, Clock, RefreshCw, Check } from 'lucide-react'
import { useState, useRef, KeyboardEvent, useEffect } from 'react'

import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { GlassInput } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useAuthContext } from '@/contexts/AuthContext'
import { SEND_SMS_CODE } from '@/graphql/mutations'

import { AuthLayout } from './auth-layout'

interface SmsStepProps {
  phone: string
  onNext: (code: string) => void
  onBack: () => void
}

export function SmsStep({ phone, onNext, onBack }: SmsStepProps) {
  const [code, setCode] = useState(['', '', '', ''])
  const [timeLeft, setTimeLeft] = useState(60)
  const [canResend, setCanResend] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const inputRefs = useRef<(HTMLInputElement | null)[]>([])

  const { verifySmsCode } = useAuthContext()
  const [sendSmsCode] = useMutation(SEND_SMS_CODE)

  // Автофокус на первое поле при загрузке
  useEffect(() => {
    if (inputRefs.current[0]) {
      inputRefs.current[0].focus()
    }
  }, [])

  // Таймер для повторной отправки
  useEffect(() => {
    if (timeLeft > 0) {
      const timer = setTimeout(() => setTimeLeft(timeLeft - 1), 1000)
      return () => clearTimeout(timer)
    } else {
      setCanResend(true)
    }
  }, [timeLeft])

  const handleInputChange = (index: number, value: string) => {
    if (value.length > 1) return // Разрешаем только одну цифру
    if (!/^\d*$/.test(value)) return // Разрешаем только цифры

    const newCode = [...code]
    newCode[index] = value
    setCode(newCode)
    setError(null)

    // Автоматически переключаемся на следующее поле
    if (value && index < 3) {
      inputRefs.current[index + 1]?.focus()
    }
  }

  const handleKeyDown = (index: number, e: KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Backspace' && !code[index] && index > 0) {
      inputRefs.current[index - 1]?.focus()
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    try {
      e.preventDefault()
      const fullCode = code.join('')
    
      if (fullCode.length === 4) {
        console.warn('🔑 SMS: Verifying code', fullCode)
        setIsLoading(true)
        setError(null)

        try {
          const cleanPhone = phone.replace(/\D/g, '')
          const formattedPhone = cleanPhone.startsWith('8') ? '7' + cleanPhone.slice(1) : cleanPhone
          
          const result = await verifySmsCode(formattedPhone, fullCode)

          if (result.success) {
            console.warn('🔑 SMS: Success, continuing to next step')
            onNext(fullCode)
          } else {
            setError('Неверный код. Проверьте SMS и попробуйте еще раз.')
            setCode(['', '', '', ''])
            inputRefs.current[0]?.focus()
          }
        } catch (error: unknown) {
          console.error('🔑 SMS: Verification error:', error)
          setError('Ошибка проверки кода. Попробуйте еще раз.')
          setCode(['', '', '', ''])
          inputRefs.current[0]?.focus()
        } finally {
          setIsLoading(false)
        }
      }
    } catch (globalError) {
      console.error('🔑 SMS: Global error:', globalError)
    }
  }

  const handleResend = async () => {
    setTimeLeft(60)
    setCanResend(false)
    setError(null)

    try {
      const cleanPhone = phone.replace(/\D/g, '')
      const formattedPhone = cleanPhone.startsWith('8') ? '7' + cleanPhone.slice(1) : cleanPhone

      await sendSmsCode({
        variables: { phone: formattedPhone },
      })
    } catch (error: unknown) {
      console.error('Error resending SMS:', error)
      setError('Ошибка отправки SMS. Попробуйте позже.')
    }
  }

  const isValidCode = code.every((digit) => digit !== '')

  return (
    <AuthLayout
      title="Введите код"
      description={`SMS-код отправлен на номер ${phone}`}
      currentStep={2}
      totalSteps={5}
      stepName="Подтверждение"
    >
      <div className="space-y-4">
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <Label className="text-white text-sm font-medium flex items-center gap-2">
                <MessageSquare className="h-4 w-4" />
                Код из SMS
              </Label>
              {isValidCode && (
                <Badge
                  variant="outline"
                  className="glass-secondary text-green-300 border-green-400/30 flex items-center gap-1"
                >
                  <Check className="h-3 w-3" />
                  Готово
                </Badge>
              )}
            </div>

            <div className="flex gap-3 justify-center">
              {code.map((digit, index) => (
                <GlassInput
                  key={index}
                  ref={(el) => {
                    inputRefs.current[index] = el
                  }}
                  type="text"
                  inputMode="numeric"
                  maxLength={1}
                  value={digit}
                  onChange={(e) => handleInputChange(index, e.target.value)}
                  onKeyDown={(e) => handleKeyDown(index, e)}
                  className={`w-12 h-12 text-center text-lg font-semibold ${error ? 'border-red-400/50' : ''}`}
                />
              ))}
            </div>

            {error && <p className="text-red-400 text-xs text-center">{error}</p>}
          </div>

          <div className="space-y-3">
            <Button
              type="submit"
              variant="glass"
              size="lg"
              className="w-full h-12"
              disabled={!isValidCode || isLoading}
            >
              {isLoading ? 'Проверка кода...' : 'Продолжить'}
            </Button>

            <Button type="button" variant="glass-secondary" onClick={onBack} className="w-full flex items-center gap-2">
              <ArrowLeft className="h-4 w-4" />
              Изменить номер телефона
            </Button>
          </div>

          <div className="text-center">
            {!canResend ? (
              <div className="flex items-center justify-center gap-2 text-white/60">
                <Clock className="h-4 w-4" />
                <span className="text-sm">Повторная отправка через {timeLeft}с</span>
              </div>
            ) : (
              <Button
                type="button"
                variant="ghost"
                onClick={handleResend}
                className="text-sm text-white/60 hover:text-white/80 underline hover:bg-transparent flex items-center gap-2"
              >
                <RefreshCw className="h-4 w-4" />
                Отправить код повторно
              </Button>
            )}
          </div>
        </form>
      </div>
    </AuthLayout>
  )
}
