/**
 * Template Library
 * Phase 7: Layout & Template System
 * Component for browsing and selecting page templates
 */
import React, { useState } from 'react';
import { SearchIcon, FilterIcon, CheckIcon } from 'lucide-react';
import { Card } from '../../ui/card';
import Button from '../../ui/button/Button';

export interface TemplateOption {
  id: string;
  name: string;
  description: string;
  preview: string; // Preview image URL
  category: 'landing' | 'marketing' | 'blog' | 'business' | 'portfolio' | 'ecommerce';
  tags: string[];
  featured?: boolean;
}

interface TemplateLibraryProps {
  selectedTemplate?: string;
  onSelect: (templateId: string) => void;
  templates?: TemplateOption[];
  onPreview?: (templateId: string) => void;
}

const DEFAULT_TEMPLATES: TemplateOption[] = [
  {
    id: 'marketing-1',
    name: 'Modern Marketing',
    description: 'Clean, conversion-focused marketing template',
    preview: '',
    category: 'marketing',
    tags: ['modern', 'conversion', 'marketing'],
    featured: true,
  },
  {
    id: 'landing-1',
    name: 'Landing Page Pro',
    description: 'High-converting landing page template',
    preview: '',
    category: 'landing',
    tags: ['landing', 'conversion', 'hero'],
    featured: true,
  },
  {
    id: 'blog-1',
    name: 'Blog Classic',
    description: 'Traditional blog layout with sidebar',
    preview: '',
    category: 'blog',
    tags: ['blog', 'sidebar', 'content'],
  },
  {
    id: 'business-1',
    name: 'Business Professional',
    description: 'Corporate business template',
    preview: '',
    category: 'business',
    tags: ['corporate', 'professional', 'business'],
  },
  {
    id: 'portfolio-1',
    name: 'Portfolio Showcase',
    description: 'Portfolio template for creative work',
    preview: '',
    category: 'portfolio',
    tags: ['portfolio', 'showcase', 'creative'],
  },
  {
    id: 'ecommerce-1',
    name: 'Ecommerce Store',
    description: 'Full-featured e-commerce template',
    preview: '',
    category: 'ecommerce',
    tags: ['ecommerce', 'store', 'products'],
  },
];

export default function TemplateLibrary({
  selectedTemplate,
  onSelect,
  templates = DEFAULT_TEMPLATES,
  onPreview,
}: TemplateLibraryProps) {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string>('all');
  const [showFeaturedOnly, setShowFeaturedOnly] = useState(false);

  const categories = ['all', ...Array.from(new Set(templates.map((t) => t.category)))];

  const filteredTemplates = templates.filter((template) => {
    const matchesSearch = 
      template.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      template.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
      template.tags.some((tag) => tag.toLowerCase().includes(searchTerm.toLowerCase()));
    
    const matchesCategory = selectedCategory === 'all' || template.category === selectedCategory;
    const matchesFeatured = !showFeaturedOnly || template.featured;

    return matchesSearch && matchesCategory && matchesFeatured;
  });

  return (
    <div className="space-y-4">
      {/* Search and Filters */}
      <div className="flex flex-col md:flex-row gap-4">
        <div className="relative flex-1">
          <SearchIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
          <input
            type="text"
            placeholder="Search templates..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-3 py-2 border border-gray-300 dark:border-gray-700 rounded-md dark:bg-gray-800 dark:text-white"
          />
        </div>
        <div className="flex gap-2">
          <button
            type="button"
            onClick={() => setShowFeaturedOnly(!showFeaturedOnly)}
            className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
              showFeaturedOnly
                ? 'bg-brand-500 text-white'
                : 'bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700'
            }`}
          >
            <FilterIcon className="w-4 h-4 inline mr-2" />
            Featured Only
          </button>
        </div>
      </div>

      {/* Category Filter */}
      <div className="flex gap-2 flex-wrap">
        {categories.map((category) => (
          <button
            key={category}
            type="button"
            onClick={() => setSelectedCategory(category)}
            className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
              selectedCategory === category
                ? 'bg-brand-500 text-white'
                : 'bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700'
            }`}
          >
            {category.charAt(0).toUpperCase() + category.slice(1)}
          </button>
        ))}
      </div>

      {/* Template Grid */}
      {filteredTemplates.length === 0 ? (
        <Card className="p-12 text-center">
          <p className="text-gray-600 dark:text-gray-400">No templates found matching your criteria.</p>
        </Card>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filteredTemplates.map((template) => (
            <Card
              key={template.id}
              className={`p-4 transition-all hover:shadow-lg ${
                selectedTemplate === template.id
                  ? 'ring-2 ring-brand-500 border-brand-500'
                  : 'border-gray-200 dark:border-gray-700'
              }`}
            >
              <div className="relative mb-3">
                {template.preview ? (
                  <img
                    src={template.preview}
                    alt={template.name}
                    className="w-full h-40 object-cover rounded-md"
                  />
                ) : (
                  <div className="w-full h-40 bg-gradient-to-br from-gray-100 to-gray-200 dark:from-gray-800 dark:to-gray-900 rounded-md flex items-center justify-center">
                    <span className="text-gray-400 dark:text-gray-600 text-sm">{template.name}</span>
                  </div>
                )}
                {template.featured && (
                  <span className="absolute top-2 left-2 bg-yellow-500 text-white text-xs px-2 py-1 rounded">
                    Featured
                  </span>
                )}
                {selectedTemplate === template.id && (
                  <div className="absolute top-2 right-2 bg-brand-500 text-white rounded-full p-1">
                    <CheckIcon className="w-4 h-4" />
                  </div>
                )}
              </div>
              <h3 className="font-semibold text-gray-900 dark:text-white mb-1">{template.name}</h3>
              <p className="text-sm text-gray-600 dark:text-gray-400 mb-3">{template.description}</p>
              <div className="flex gap-2 flex-wrap mb-3">
                {template.tags.slice(0, 3).map((tag) => (
                  <span
                    key={tag}
                    className="text-xs px-2 py-1 bg-gray-100 dark:bg-gray-800 rounded text-gray-600 dark:text-gray-400"
                  >
                    {tag}
                  </span>
                ))}
              </div>
              <div className="flex gap-2">
                <Button
                  variant={selectedTemplate === template.id ? 'primary' : 'outline'}
                  size="sm"
                  onClick={() => onSelect(template.id)}
                  className="flex-1"
                >
                  {selectedTemplate === template.id ? 'Selected' : 'Select'}
                </Button>
                {onPreview && (
                  <Button variant="outline" size="sm" onClick={() => onPreview(template.id)}>
                    Preview
                  </Button>
                )}
              </div>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}

