"use client"

import { useState, useEffect } from 'react'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Lock, Eye, EyeOff } from 'lucide-react'
import { ADMIN } from '@/lib/agent-brand'

interface PasswordProtectionProps {
  children: React.ReactNode
  requiredPassword?: string
}

const DEFAULT_PASSWORD = "cassman1."

export function PasswordProtection({ 
  children, 
  requiredPassword = DEFAULT_PASSWORD 
}: PasswordProtectionProps) {
  const [isAuthenticated, setIsAuthenticated] = useState(false)
  const [password, setPassword] = useState('')
  const [showPassword, setShowPassword] = useState(false)
  const [error, setError] = useState('')
  const [isLoading, setIsLoading] = useState(true)
  const [failedAttempts, setFailedAttempts] = useState(0)
  const [isLocked, setIsLocked] = useState(false)

  useEffect(() => {
    const isAuth = sessionStorage.getItem('panel_authenticated') === 'true'
    setIsAuthenticated(isAuth)
    setIsLoading(false)
  }, [])

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    setError('')

    if (isLocked) {
      setError('Too many failed attempts. Please wait before trying again.')
      return
    }

    if (password === requiredPassword) {
      setIsAuthenticated(true)
      sessionStorage.setItem('panel_authenticated', 'true')
      setFailedAttempts(0)
    } else {
      const newFailedAttempts = failedAttempts + 1
      setFailedAttempts(newFailedAttempts)
      setError(`Incorrect password. (${newFailedAttempts}/3)`)
      setPassword('')

      if (newFailedAttempts >= 3) {
        setIsLocked(true)
        setError('Locked for 30 seconds.')
        setTimeout(() => {
          setIsLocked(false)
          setFailedAttempts(0)
          setError('')
        }, 30000)
      }
    }
  }

  if (isLoading) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-[#f5f4f1]">
        <div className="h-8 w-8 animate-spin rounded-full border-2 border-stone-300 border-t-stone-800" />
      </div>
    )
  }

  if (!isAuthenticated) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-[#f5f4f1] p-6">
        <div className="w-full max-w-sm rounded-2xl border border-stone-200 bg-white p-8 shadow-sm">
          <div className="mb-6 flex justify-center">
            <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-stone-900">
              <Lock className="h-5 w-5 text-white" />
            </div>
          </div>
          <h1 className="text-center text-xl font-semibold text-stone-900">{ADMIN.title}</h1>
          <p className="mt-2 text-center text-sm text-stone-500">
            Enter your access code to continue
          </p>
          <form onSubmit={handleSubmit} className="mt-6 space-y-4">
            <div className="relative">
              <Input
                type={showPassword ? 'text' : 'password'}
                placeholder="Access code"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="h-11 border-stone-300 bg-stone-50 pr-10"
                autoFocus
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-stone-400 hover:text-stone-600"
              >
                {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>
            {error ? (
              <p className="rounded-lg bg-red-50 px-3 py-2 text-center text-sm text-red-700">{error}</p>
            ) : null}
            <Button
              type="submit"
              className="h-11 w-full bg-stone-900 text-white hover:bg-stone-800"
              disabled={!password.trim() || isLocked}
            >
              {isLocked ? 'Locked' : 'Sign in'}
            </Button>
          </form>
        </div>
      </div>
    )
  }

  return <>{children}</>
}
