import { useState, useRef, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Fingerprint } from 'lucide-react'

export default function BiometricEffect({ onUnlock }: { onUnlock: () => void }) {
  const [progress, setProgress] = useState(0)
  const [unlocked, setUnlocked] = useState(false)
  const intervalRef = useRef<any>(null)

  const handleStart = () => {
    if (unlocked) return
    if (intervalRef.current) clearInterval(intervalRef.current)
    intervalRef.current = setInterval(() => {
      setProgress(p => Math.min(p + 2, 100))
    }, 30) // takes about 1.5 seconds to fill
  }

  const handleStop = () => {
    if (unlocked) return
    if (intervalRef.current) clearInterval(intervalRef.current)
    setProgress(p => {
      if (p >= 100) return p
      return 0
    })
  }

  useEffect(() => {
    if (progress >= 100 && !unlocked) {
      if (intervalRef.current) clearInterval(intervalRef.current)
      setUnlocked(true)
      setTimeout(() => onUnlock(), 800)
    }
  }, [progress, unlocked, onUnlock])

  useEffect(() => {
    return () => { if (intervalRef.current) clearInterval(intervalRef.current) }
  }, [])

  return (
    <AnimatePresence>
      {!unlocked && (
        <motion.div 
          className="fixed inset-0 z-[100] bg-[#0a0f18] flex flex-col items-center justify-center"
          exit={{ opacity: 0 }}
        >
          <div className="relative">
            {/* The Fingerprint Button */}
            <motion.button
              onMouseDown={handleStart}
              onMouseUp={handleStop}
              onMouseLeave={handleStop}
              onTouchStart={handleStart}
              onTouchEnd={handleStop}
              className={`relative z-10 w-40 h-40 rounded-full flex items-center justify-center transition-all duration-300 ${
                progress > 0 ? 'text-cyan-400 scale-105' : 'text-slate-700'
              }`}
              style={{
                boxShadow: progress > 0 ? `0 0 ${progress}px rgba(34,211,238,0.4)` : 'none'
              }}
            >
              <Fingerprint className="w-20 h-20" />
            </motion.button>

            {/* Circular Progress SVG */}
            <svg className="absolute inset-0 w-40 h-40 pointer-events-none -rotate-90">
              <circle cx="80" cy="80" r="76" fill="none" stroke="currentColor" strokeWidth="2" className="text-slate-800" />
              <circle cx="80" cy="80" r="76" fill="none" stroke="currentColor" strokeWidth="2" className="text-cyan-400 transition-all duration-75"
                strokeDasharray={477}
                strokeDashoffset={477 - (477 * progress) / 100}
              />
            </svg>
            
            {/* Scanning Laser Line */}
            {progress > 0 && progress < 100 && (
              <motion.div 
                className="absolute left-0 right-0 h-[2px] bg-cyan-400 z-20 rounded-full pointer-events-none"
                style={{ top: '10%', boxShadow: '0 0 10px 2px rgba(34,211,238,0.8)' }}
                animate={{ top: ['10%', '90%', '10%'] }}
                transition={{ duration: 1, repeat: Infinity, ease: 'linear' }}
              />
            )}
          </div>
          
          <p className={`mt-10 font-mono text-sm tracking-[0.3em] uppercase transition-colors ${progress === 100 ? 'text-emerald-400' : 'text-slate-500'}`}>
            {progress > 0 ? (progress === 100 ? 'Access Granted' : 'Scanning...') : 'Hold to Authenticate'}
          </p>
        </motion.div>
      )}

      {/* Iris Wipe Effect */}
      {unlocked && (
        <motion.div 
          className="fixed inset-0 z-[110] pointer-events-none flex items-center justify-center overflow-hidden"
        >
          <motion.div 
             className="bg-cyan-400 mix-blend-screen"
             initial={{ clipPath: 'circle(100px at center)', width: '100vw', height: '100vh' }}
             animate={{ clipPath: 'circle(150% at center)', opacity: [1, 1, 0] }}
             transition={{ duration: 0.8, ease: "easeIn" }}
          />
        </motion.div>
      )}
    </AnimatePresence>
  )
}
