import React, { useState, useMemo, useRef, useEffect } from 'react';
import { PaperSize, StyleOption } from '../types';
import { Check, Type, Printer, Search, Heart } from 'lucide-react';
import { motion } from 'motion/react';
import { getPreviewCss } from '../services/templateRenderer';

interface StyleSelectorProps {
  templates: StyleOption[];
  categories: string[];
  selectedStyle: string | null;
  onSelectStyle: (id: string) => void;
  selectedPaperSize: PaperSize;
  onSelectPaperSize: (size: PaperSize) => void;
  onGenerate: () => void;
  isLoading?: boolean;
  error?: string | null;
}

const SAMPLE_CONTENT = `
  <h1>The Art of Typography</h1>
  <p>Typography is the art and technique of arranging type to make written language <strong>legible</strong>, <em>readable</em>, and <u>appealing</u> when displayed. The arrangement involves selecting typefaces, point sizes, line lengths, and letter-spacing.</p>
  
  <h2>1. Visual Hierarchy</h2>
  <p>Visual hierarchy enables the reader to understand the importance of different sections. By using size, weight, and color, we guide the eye through the document in a logical flow.</p>
  
  <h3>Key Principles</h3>
  <p>Effective typography follows timeless principles. Each element serves a purpose, creating harmony between form and function.</p>
  
  <h4>Micro-Typography</h4>
  <p>The smallest details matter most. Kerning, tracking, and leading work together to create <code>readable</code> text that flows naturally.</p>
  
  <blockquote>
    "Design is not just what it looks like and feels like. Design is how it works." — Steve Jobs
  </blockquote>
  
  <h2>2. Essential Elements</h2>
  
  <h3>Unordered Principles</h3>
  <ul>
    <li><strong>Typeface:</strong> The personality of your document</li>
    <li><strong>Contrast:</strong> Distinguishing elements effectively</li>
    <li><strong>Consistency:</strong> Maintaining a coherent structure</li>
    <li><strong>Whitespace:</strong> Breathing room for the eyes</li>
  </ul>
  
  <h3>Process Steps</h3>
  <ol>
    <li>Analyze your content and audience</li>
    <li>Choose appropriate typefaces</li>
    <li>Establish hierarchy and rhythm</li>
    <li>Test and refine the layout</li>
  </ol>
  
  <hr>
  
  <h2>3. Technical Implementation</h2>
  <p>When implementing typography in code, precision is essential. Here's a basic example:</p>
  
  <pre>function applyTypography(element) {
  element.style.fontFamily = 'Georgia, serif';
  element.style.lineHeight = '1.6';
  element.style.letterSpacing = '0.02em';
}</pre>
  
  <h3>Font Properties Comparison</h3>
  <table>
    <tr>
      <th>Property</th>
      <th>Serif</th>
      <th>Sans-Serif</th>
    </tr>
    <tr>
      <td>Readability</td>
      <td>High (print)</td>
      <td>High (screen)</td>
    </tr>
    <tr>
      <td>Personality</td>
      <td>Classic</td>
      <td>Modern</td>
    </tr>
    <tr>
      <td>Use Case</td>
      <td>Body text</td>
      <td>Headings</td>
    </tr>
  </table>
  
  <p>Good typography is invisible. It should not distract the reader but enhance the experience. Visit <a href="https://typography.com">typography.com</a> to learn more about professional typesetting.</p>
  
  <h5>Advanced Techniques</h5>
  <p>Mastering typography requires understanding both the rules and when to break them creatively.</p>
  
  <h6>Final Thoughts</h6>
  <p>Typography transforms ordinary text into extraordinary communication. Every choice matters.</p>
`;

export const StyleSelector: React.FC<StyleSelectorProps> = ({
  templates,
  categories,
  selectedStyle,
  onSelectStyle,
  selectedPaperSize,
  onSelectPaperSize,
  onGenerate,
  isLoading,
  error
}) => {
  const [activeCategory, setActiveCategory] = useState<string>('All');
  const [searchQuery, setSearchQuery] = useState('');
  const [favorites, setFavorites] = useState<string[]>(() => {
    try {
      const saved = localStorage.getItem('favoriteTemplates');
      return saved ? JSON.parse(saved) : [];
    } catch (e) {
      console.error('Failed to parse favorites', e);
      return [];
    }
  });

  const iframeRef = useRef<HTMLIFrameElement>(null);

  // Persist favorites
  useEffect(() => {
    localStorage.setItem('favoriteTemplates', JSON.stringify(favorites));
  }, [favorites]);

  const toggleFavorite = (e: React.MouseEvent, id: string) => {
    e.stopPropagation();
    setFavorites(prev =>
      prev.includes(id) ? prev.filter(fid => fid !== id) : [...prev, id]
    );
  };

  const filteredStyles = useMemo(() => {
    let styles = templates;

    // Filter by category
    if (activeCategory === 'fav') {
      styles = styles.filter(style => favorites.includes(style.id));
    } else if (activeCategory !== 'All') {
      styles = templates.filter(style => style.category === activeCategory);
    }

    // Filter by search
    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase();
      styles = styles.filter(style =>
        style.name.toLowerCase().includes(query) ||
        style.description.toLowerCase().includes(query) ||
        style.category.toLowerCase().includes(query)
      );
    }

    // Always sort alphabetically by name
    return [...styles].sort((a, b) => a.name.localeCompare(b.name));
  }, [templates, activeCategory, searchQuery, favorites]);

  const currentStyleObj = useMemo(() =>
    templates.find(s => s.id === selectedStyle),
    [templates, selectedStyle]);

  // Track blob URL for cleanup
  const blobUrlRef = useRef<string | null>(null);

  // Update preview when style changes
  useEffect(() => {
    if (!iframeRef.current || !currentStyleObj) return;

    // Cleanup old blob URL
    if (blobUrlRef.current) {
      URL.revokeObjectURL(blobUrlRef.current);
      blobUrlRef.current = null;
    }

    // Get CSS from template
    const templateCss = getPreviewCss(currentStyleObj);

    // DEBUG: Specific markdown constructs for StyleSelector
    console.log('=== STYLESELECTOR DEBUG (h3, strong, table, ul/ol, li) ===');
    console.log('h3:', JSON.stringify(currentStyleObj.elements?.h3));
    console.log('strong:', JSON.stringify(currentStyleObj.elements?.strong));
    console.log('table:', JSON.stringify(currentStyleObj.elements?.table));
    console.log('th:', JSON.stringify(currentStyleObj.elements?.th));
    console.log('td:', JSON.stringify(currentStyleObj.elements?.td));
    console.log('ul:', JSON.stringify(currentStyleObj.elements?.ul));
    console.log('ol:', JSON.stringify(currentStyleObj.elements?.ol));
    console.log('li:', JSON.stringify(currentStyleObj.elements?.li));
    console.log('=== END STYLESELECTOR DEBUG ===');

    const html = `
      <!DOCTYPE html>
      <html>
      <head>
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="${currentStyleObj.googleFontsImport}" rel="stylesheet">
        <style>
          /* Reset */
          * { box-sizing: border-box; }
          html, body { margin: 0; padding: 0; }
          
          /* App background (dark) */
          body {
            background-color: #18181b;
            padding: 40px;
            min-height: 100vh;
          }
          
          /* Template CSS - includes .page styles */
          ${templateCss}
          
          /* Page dimensions (not included in template) */
          .page {
            width: ${selectedPaperSize === 'A4' ? '210mm' : '8.5in'};
            min-height: ${selectedPaperSize === 'A4' ? '297mm' : '11in'};
            margin: 0 auto;
            padding: 25mm;
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.5);
          }
          
          /* Scrollbar */
          ::-webkit-scrollbar { width: 8px; }
          ::-webkit-scrollbar-track { background: transparent; }
          ::-webkit-scrollbar-thumb { background: #71717a; border-radius: 4px; }
        </style>
      </head>
      <body>
        <div class="page">
          ${SAMPLE_CONTENT}
        </div>
      </body>
      </html>
    `;

    // Create blob URL for CSP compliance
    const blob = new Blob([html], { type: 'text/html' });
    const blobUrl = URL.createObjectURL(blob);
    blobUrlRef.current = blobUrl;
    iframeRef.current.src = blobUrl;

    // Cleanup on unmount
    return () => {
      if (blobUrlRef.current) {
        URL.revokeObjectURL(blobUrlRef.current);
        blobUrlRef.current = null;
      }
    };
  }, [currentStyleObj, selectedPaperSize]);

  if (isLoading) {
    return (
      <div className="w-full h-full flex items-center justify-center">
        <motion.div className="text-center" initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
          <motion.div className="w-12 h-12 border-4 border-indigo-500/30 border-t-indigo-500 rounded-full mx-auto mb-4" animate={{ rotate: 360 }} transition={{ duration: 1, repeat: Infinity, ease: "linear" }} />
          <p className="text-zinc-400">Loading templates...</p>
        </motion.div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="w-full h-full flex flex-col items-center justify-center p-8 text-center">
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="max-w-md">
          <div className="w-16 h-16 bg-red-500/10 rounded-full flex items-center justify-center mx-auto mb-4">
            <span className="text-2xl">⚠️</span>
          </div>
          <h3 className="text-xl font-semibold text-white mb-2">Template Error</h3>
          <p className="text-zinc-400 mb-6">{error}</p>
        </motion.div>
      </div>
    );
  }

  return (
    <div className="w-full h-full min-h-[600px] flex flex-col gap-6 max-w-[1600px] mx-auto">

      {/* Top Controls */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 px-1">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-indigo-500/10 rounded-lg text-indigo-400">
            <Type size={24} />
          </div>
          <div>
            <h2 className="text-2xl font-bold text-zinc-100">Select Typography Style</h2>
            <p className="text-zinc-400 text-sm">Browse {templates.length} professional templates</p>
          </div>
        </div>

        <div className="flex items-center gap-4 bg-zinc-900/50 p-1.5 rounded-xl border border-zinc-800/50">
          <div className="flex items-center gap-2 text-zinc-400 px-3">
            <Printer size={16} />
            <span className="text-xs font-semibold uppercase tracking-wider">Format</span>
          </div>
          <div className="flex gap-1">
            {(['Letter', 'A4'] as PaperSize[]).map((size) => (
              <button
                key={size}
                onClick={() => onSelectPaperSize(size)}
                className={`px-3 py-1.5 rounded-lg text-xs font-bold transition-all ${selectedPaperSize === size
                  ? 'bg-zinc-700 text-white shadow-sm'
                  : 'text-zinc-500 hover:text-zinc-300 hover:bg-zinc-800'
                  }`}
              >
                {size}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Main Split Layout */}
      <div className="flex-1 grid grid-cols-1 lg:grid-cols-12 gap-6 min-h-0">

        {/* LEFT COLUMN: Style List */}
        <div className="lg:col-span-4 flex flex-col gap-4 min-h-0 bg-zinc-900/30 rounded-2xl border border-zinc-800/50 overflow-hidden">

          {/* Category Filter Tabs */}
          <div className="flex flex-col border-b border-zinc-800/50 bg-zinc-900/20">
            <div className="p-4 overflow-x-auto no-scrollbar pb-2">
              <div className="flex gap-2">
                <button
                  onClick={() => setActiveCategory('fav')}
                  className={`px-3 py-1.5 rounded-full text-xs font-semibold whitespace-nowrap transition-all flex items-center gap-1.5 ${activeCategory === 'fav'
                    ? 'bg-rose-500 text-white shadow-lg shadow-rose-500/20'
                    : 'bg-zinc-800 text-zinc-400 hover:bg-zinc-700 hover:text-zinc-200'
                    }`}
                >
                  <Heart size={12} className={activeCategory === 'fav' ? 'fill-current' : ''} />
                  fav
                </button>
                <div className="w-px h-6 bg-zinc-800 mx-1 self-center" />
                <button
                  onClick={() => setActiveCategory('All')}
                  className={`px-3 py-1.5 rounded-full text-xs font-semibold whitespace-nowrap transition-all ${activeCategory === 'All'
                    ? 'bg-white text-black'
                    : 'bg-zinc-800 text-zinc-400 hover:bg-zinc-700 hover:text-zinc-200'
                    }`}
                >
                  All
                </button>
                {categories.map(cat => (
                  <button
                    key={cat}
                    onClick={() => setActiveCategory(cat)}
                    className={`px-3 py-1.5 rounded-full text-xs font-semibold whitespace-nowrap transition-all ${activeCategory === cat
                      ? 'bg-indigo-500 text-white shadow-lg shadow-indigo-500/20'
                      : 'bg-zinc-800 text-zinc-400 hover:bg-zinc-700 hover:text-zinc-200'
                      }`}
                  >
                    {cat}
                  </button>
                ))}
              </div>
            </div>

            {/* Search Input */}
            <div className="px-4 pb-4">
              <div className="relative group">
                <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-500 group-focus-within:text-indigo-400 transition-colors" />
                <input
                  type="text"
                  placeholder="Search templates..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full bg-zinc-900 border border-zinc-700 rounded-xl py-2 pl-9 pr-4 text-sm text-zinc-200 placeholder:text-zinc-600 focus:outline-none focus:border-indigo-500/50 focus:ring-1 focus:ring-indigo-500/50 transition-all"
                />
              </div>
            </div>
          </div>

          {/* Scrollable List */}
          <div className="flex-1 overflow-y-auto p-4 space-y-3 custom-scrollbar">
            {filteredStyles.length === 0 ? (
              <div className="text-center py-8 text-zinc-500">
                <p className="text-sm">No templates found</p>
              </div>
            ) : filteredStyles.map((style) => (
              <div
                key={style.id}
                onClick={() => onSelectStyle(style.id)}
                className={`p-4 rounded-xl border transition-all cursor-pointer group relative
                  ${selectedStyle === style.id
                    ? 'border-indigo-500 bg-indigo-500/10 shadow-[0_0_15px_rgba(99,102,241,0.15)]'
                    : 'border-zinc-800 bg-zinc-900/40 hover:border-zinc-700 hover:bg-zinc-800'}`}
              >
                <div className="flex justify-between items-start mb-1 gap-2">
                  <h3 className={`font-bold text-sm ${selectedStyle === style.id ? 'text-white' : 'text-zinc-300'}`}>
                    {style.name}
                  </h3>
                  <div className="flex items-center gap-2 shrink-0">
                    <button
                      onClick={(e) => toggleFavorite(e, style.id)}
                      className={`p-1.5 rounded-full transition-all ${favorites.includes(style.id)
                          ? 'text-rose-400 bg-rose-500/10 hover:bg-rose-500/20'
                          : 'text-zinc-600 hover:text-zinc-400 hover:bg-zinc-700/50'
                        }`}
                    >
                      <Heart size={14} className={favorites.includes(style.id) ? 'fill-current' : ''} />
                    </button>
                    {selectedStyle === style.id && (
                      <div className="bg-indigo-500 rounded-full p-0.5">
                        <Check size={12} className="text-white" />
                      </div>
                    )}
                  </div>
                </div>
                <p className="text-xs text-zinc-500 line-clamp-2 leading-relaxed mb-2">{style.description}</p>
                <div className="flex items-center gap-2">
                  <span className={`text-[10px] uppercase font-mono tracking-wider px-1.5 py-0.5 rounded
                    ${selectedStyle === style.id ? 'bg-indigo-500/20 text-indigo-300' : 'bg-zinc-800 text-zinc-500'}`}>
                    {style.category}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* RIGHT COLUMN: Preview Window */}
        <div className="lg:col-span-8 flex flex-col min-h-0 bg-zinc-950 rounded-2xl border border-zinc-800 shadow-2xl relative overflow-hidden">

          {/* Preview Header */}
          <div className="h-12 border-b border-zinc-800 bg-zinc-900/50 flex items-center px-4 justify-between">
            <div className="flex items-center gap-2">
              <div className="flex gap-1.5">
                <div className="w-3 h-3 rounded-full bg-red-500/20 border border-red-500/50"></div>
                <div className="w-3 h-3 rounded-full bg-amber-500/20 border border-amber-500/50"></div>
                <div className="w-3 h-3 rounded-full bg-emerald-500/20 border border-emerald-500/50"></div>
              </div>
              <div className="h-4 w-px bg-zinc-800 mx-2"></div>
              <span className="text-xs text-zinc-500 font-medium">Live Preview</span>
            </div>
            {currentStyleObj && (
              <span className="text-xs text-indigo-400 font-mono">{currentStyleObj.name}</span>
            )}
          </div>

          {/* Iframe Container */}
          <div className="flex-1 relative bg-zinc-900/50">
            {selectedStyle ? (
              <iframe
                ref={iframeRef}
                className="w-full h-full border-0 block"
                title="Style Preview"
              />
            ) : (
              <div className="absolute inset-0 flex flex-col items-center justify-center text-zinc-600">
                <Search size={48} className="mb-4 opacity-20" />
                <p className="text-lg font-medium">Select a style to preview</p>
                <p className="text-sm">Choose from the list on the left</p>
              </div>
            )}
          </div>

          {/* Bottom Action Bar */}
          <div className="p-4 border-t border-zinc-800 bg-zinc-900/50 flex justify-end items-center gap-4">
            <button
              onClick={onGenerate}
              disabled={!selectedStyle}
              className="flex items-center gap-2 px-6 py-3 bg-indigo-600 hover:bg-indigo-500 text-white font-bold rounded-xl transition-all shadow-lg hover:shadow-indigo-500/25 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <span>Apply Style & Convert</span>
              <Printer size={18} />
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};
