'use client';
import React, { useEffect, useRef, useState } from 'react';
import QRCodeStyling, { Options } from 'qr-code-styling';

export interface ExtendedOptions extends Options {
  frameOptions?: {
    enabled: boolean;
    text: string;
    bgColor: string;
    textColor: string;
  };
}

interface LivePreviewProps {
  options: ExtendedOptions;
}

export default function LivePreview({ options }: LivePreviewProps) {
  const ref = useRef<HTMLDivElement>(null);
  const [qrCode] = useState<QRCodeStyling>(new QRCodeStyling(options));

  useEffect(() => {
    if (ref.current) {
      ref.current.innerHTML = '';
      qrCode.append(ref.current);
    }
  }, [qrCode, ref]);

  useEffect(() => {
    if (!qrCode) return;
    const { frameOptions, ...pureOptions } = options;
    qrCode.update(pureOptions);
  }, [qrCode, options]);

  const frame = options.frameOptions;

  return (
    <div className="flex justify-center items-center p-8 bg-gray-50 rounded-xl border border-gray-200 min-h-[400px]">
      <div 
        id="qr-preview-container" 
        className={`relative ${frame?.enabled ? 'p-4 pb-8 rounded-2xl shadow-lg flex flex-col items-center justify-center gap-3' : 'shadow-lg rounded-xl overflow-hidden'}`}
        style={frame?.enabled ? { backgroundColor: frame.bgColor || '#4f46e5' } : { backgroundColor: '#ffffff' }}
      >
        {frame?.enabled && (
          <div className="font-bold text-center text-lg uppercase tracking-wider w-full" style={{ color: frame.textColor || '#ffffff' }}>
            {frame.text || 'SCAN ME'}
          </div>
        )}
        <div ref={ref} className="bg-white rounded-lg overflow-hidden flex items-center justify-center p-2" />
      </div>
    </div>
  );
}
