'use client';

import { QrCode, X } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';

const ModalQrCode = ({ isOpen, onClose, onScan }) => {
  const inputRef = useRef(null);
  const [tempValue, setTempValue] = useState('');

  useEffect(() => {
    if (isOpen && inputRef.current) {
      inputRef.current.focus();
    }
  }, [isOpen]);

  const handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      onScan(tempValue);
      setTempValue('');
      onClose();
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-[99999] flex items-center justify-center">
      <div className="absolute inset-0 bg-black/50 backdrop-blur-sm" onClick={onClose} />

      <div className="relative bg-white rounded-xl shadow-2xl p-6 w-[400px] max-w-[90vw]">
        <button onClick={onClose} className="absolute top-4 right-4 p-1 rounded-full hover:bg-gray-100 transition-colors">
          <X className="size-5 text-gray-500" />
        </button>
        <div className="text-center mb-4">
          <h2 className="text-xl font-semibold text-gray-900 mb-2">QR Kodni Skanerlang</h2>
        </div>
        <input ref={inputRef} type="text" value={tempValue} onChange={(e) => setTempValue(e.target.value)} onKeyDown={handleKeyDown} className="absolute opacity-0 pointer-events-none" />
        <div className="relative flex items-center justify-center py-6">
          <QrCode className="size-40 text-[#3489e3]" />
          <div className="absolute z-10 w-44 h-[2px] bg-[#3489e3] animate-scan" />
        </div>
      </div>
      <style jsx>{`
        @keyframes scan {
          0% {
            top: 25%;
            opacity: 0.2;
          }
          50% {
            top: 75%;
            opacity: 1;
          }
          100% {
            top: 25%;
            opacity: 0.2;
          }
        }
        .animate-scan {
          animation: scan 2s infinite linear;
        }
      `}</style>
    </div>
  );
};

export default ModalQrCode;
