import { useState, useEffect } from 'react';
import { copyToClipboard } from '../../lib/marketing-kit';

interface EmbedCodeModalProps {
  isOpen: boolean;
  onClose: () => void;
  eventId: string;
  eventSlug: string;
}

export default function EmbedCodeModal({ 
  isOpen, 
  onClose, 
  eventId, 
  eventSlug 
}: EmbedCodeModalProps) {
  const [embedType, setEmbedType] = useState<'basic' | 'custom'>('basic');
  const [width, setWidth] = useState(400);
  const [height, setHeight] = useState(600);
  const [theme, setTheme] = useState<'light' | 'dark'>('light');
  const [showHeader, setShowHeader] = useState(true);
  const [showDescription, setShowDescription] = useState(true);
  const [primaryColor, setPrimaryColor] = useState('#2563eb');
  const [copied, setCopied] = useState<string | null>(null);

  const baseUrl = 'https://portal.blackcanyontickets.com';
  const directLink = `${baseUrl}/e/${eventSlug}`;
  const embedUrl = `${baseUrl}/embed/${eventSlug}`;

  const generateEmbedCode = () => {
    const params = new URLSearchParams();
    
    if (embedType === 'custom') {
      params.append('theme', theme);
      params.append('header', showHeader.toString());
      params.append('description', showDescription.toString());
      params.append('color', primaryColor.replace('#', ''));
    }

    const paramString = params.toString();
    const finalUrl = paramString ? `${embedUrl}?${paramString}` : embedUrl;

    return `<iframe 
  src="${finalUrl}" 
  width="${width}" 
  height="${height}" 
  frameborder="0" 
  scrolling="no"
  title="Event Tickets">
</iframe>`;
  };

  const handleCopy = async (content: string, type: string) => {
    try {
      await copyToClipboard(content);
      setCopied(type);
      setTimeout(() => setCopied(null), 2000);
    } catch (error) {

    }
  };

  const previewUrl = embedType === 'custom' 
    ? `${embedUrl}?theme=${theme}&header=${showHeader}&description=${showDescription}&color=${primaryColor.replace('#', '')}`
    : embedUrl;

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center p-4 z-50">
      <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-2xl w-full max-w-sm sm:max-w-2xl lg:max-w-4xl max-h-[90vh] overflow-y-auto">
        <div className="p-6">
          <div className="flex justify-between items-center mb-6">
            <h2 className="text-2xl font-light text-white">Embed Event Widget</h2>
            <button
              onClick={onClose}
              className="text-white/60 hover:text-white transition-colors p-2 rounded-full hover:bg-white/10 touch-manipulation"
              aria-label="Close modal"
            >
              <svg className="w-5 h-5 sm:w-6 sm:h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>

          <div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
            {/* Configuration Panel */}
            <div className="space-y-6">
              <div>
                <h3 className="text-lg font-medium text-white mb-4">Direct Link</h3>
                <div className="bg-white/5 border border-white/20 rounded-lg p-4">
                  <div className="mb-2">
                    <label className="text-sm text-white/80">Event URL</label>
                  </div>
                  <div className="flex">
                    <input
                      type="text"
                      value={directLink}
                      readOnly
                      className="flex-1 px-3 py-2 bg-white/10 border border-white/20 rounded-l-lg text-white text-sm"
                    />
                    <button
                      onClick={() => handleCopy(directLink, 'link')}
                      className="px-4 py-2 rounded-r-lg transition-all duration-200 hover:shadow-lg hover:scale-105"
                      style={{
                        background: 'var(--glass-text-accent)',
                        color: 'white'
                      }}
                    >
                      {copied === 'link' ? '✓' : 'Copy'}
                    </button>
                  </div>
                </div>
              </div>

              <div>
                <h3 className="text-lg font-medium text-white mb-4">Embed Options</h3>
                
                <div className="space-y-4">
                  <div>
                    <label className="block text-sm text-white/80 mb-2">Embed Type</label>
                    <div className="flex space-x-4">
                      <label className="flex items-center">
                        <input
                          type="radio"
                          value="basic"
                          checked={embedType === 'basic'}
                          onChange={(e) => setEmbedType(e.target.value as 'basic' | 'custom')}
                          className="w-4 h-4 text-blue-600 bg-white/10 border-white/20"
                        />
                        <span className="ml-2 text-white text-sm">Basic</span>
                      </label>
                      <label className="flex items-center">
                        <input
                          type="radio"
                          value="custom"
                          checked={embedType === 'custom'}
                          onChange={(e) => setEmbedType(e.target.value as 'basic' | 'custom')}
                          className="w-4 h-4 text-blue-600 bg-white/10 border-white/20"
                        />
                        <span className="ml-2 text-white text-sm">Custom</span>
                      </label>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm text-white/80 mb-2">Width</label>
                      <input
                        type="number"
                        value={width}
                        onChange={(e) => setWidth(parseInt(e.target.value) || 400)}
                        className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white text-sm"
                        min="300"
                        max="800"
                      />
                    </div>
                    <div>
                      <label className="block text-sm text-white/80 mb-2">Height</label>
                      <input
                        type="number"
                        value={height}
                        onChange={(e) => setHeight(parseInt(e.target.value) || 600)}
                        className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white text-sm"
                        min="400"
                        max="1000"
                      />
                    </div>
                  </div>

                  {embedType === 'custom' && (
                    <div className="space-y-4">
                      <div>
                        <label className="block text-sm text-white/80 mb-2">Theme</label>
                        <select
                          value={theme}
                          onChange={(e) => setTheme(e.target.value as 'light' | 'dark')}
                          className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white text-sm"
                        >
                          <option value="light">Light</option>
                          <option value="dark">Dark</option>
                        </select>
                      </div>

                      <div>
                        <label className="block text-sm text-white/80 mb-2">Primary Color</label>
                        <input
                          type="color"
                          value={primaryColor}
                          onChange={(e) => setPrimaryColor(e.target.value)}
                          className="w-full h-10 bg-white/10 border border-white/20 rounded-lg"
                        />
                      </div>

                      <div className="space-y-2">
                        <label className="flex items-center">
                          <input
                            type="checkbox"
                            checked={showHeader}
                            onChange={(e) => setShowHeader(e.target.checked)}
                            className="w-4 h-4 text-blue-600 bg-white/10 border-white/20 rounded"
                          />
                          <span className="ml-2 text-white text-sm">Show Header</span>
                        </label>
                        <label className="flex items-center">
                          <input
                            type="checkbox"
                            checked={showDescription}
                            onChange={(e) => setShowDescription(e.target.checked)}
                            className="w-4 h-4 text-blue-600 bg-white/10 border-white/20 rounded"
                          />
                          <span className="ml-2 text-white text-sm">Show Description</span>
                        </label>
                      </div>
                    </div>
                  )}
                </div>
              </div>

              <div>
                <h3 className="text-lg font-medium text-white mb-4">Embed Code</h3>
                <div className="bg-white/5 border border-white/20 rounded-lg p-4">
                  <textarea
                    value={generateEmbedCode()}
                    readOnly
                    rows={6}
                    className="w-full bg-transparent text-white text-sm font-mono resize-none"
                  />
                  <div className="mt-3 flex justify-end">
                    <button
                      onClick={() => handleCopy(generateEmbedCode(), 'embed')}
                      className="px-4 py-2 rounded-lg transition-all duration-200 hover:shadow-lg hover:scale-105"
                      style={{
                        background: 'var(--glass-text-accent)',
                        color: 'white'
                      }}
                    >
                      {copied === 'embed' ? '✓ Copied' : 'Copy Code'}
                    </button>
                  </div>
                </div>
              </div>
            </div>

            {/* Preview Panel */}
            <div>
              <h3 className="text-lg font-medium text-white mb-4">Preview</h3>
              <div className="bg-white/5 border border-white/20 rounded-lg p-4">
                <div className="bg-white rounded-lg overflow-hidden">
                  <iframe
                    src={previewUrl}
                    width="100%"
                    height="400"
                    frameBorder="0"
                    scrolling="no"
                    title="Event Tickets Preview"
                    className="w-full"
                  />
                </div>
              </div>
            </div>
          </div>

          <div className="flex justify-end mt-6">
            <button
              onClick={onClose}
              className="px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white rounded-lg font-medium transition-all duration-200"
            >
              Done
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}