import { useState } from 'react';
import { TEMPLATES, TEMPLATE_CATEGORIES } from '../../constants/templates';
import '../../styles/TemplatesTab.css';

function getCategoryEmoji(category) {
  const emojis = {
    Sports: '⚽', Music: '🎸', Quotes: '💬', Animals: '🐱',
    Abstract: '🌈', Vintage: '🏅', Nature: '🏔️', Tech: '💻',
  };
  return emojis[category] || '🎨';
}

export function TemplatesTab({ onAddTemplate, onSlotImageUpload }) {
  const [selectedTemplateId, setSelectedTemplateId] = useState(null);
  const [uploadSlotId, setUploadSlotId] = useState(null);

  const templates = [
    { id: 'freeform', name: 'Freeform', description: 'No template - design freely', thumbnail: '🎨' },
    ...TEMPLATES.map(t => ({
      id: t.id,
      name: t.name,
      description: t.description,
      thumbnail: getCategoryEmoji(t.category),
      hasSlots: !!t.slots,
    })),
  ];

  const handleSelectTemplate = (template) => {
    setSelectedTemplateId(template.id);
    onAddTemplate(template.id);
  };

  const handleSlotClick = (slotId) => {
    setUploadSlotId(slotId);
    document.getElementById('slot-file-input')?.click();
  };

  const handleFileChange = (e) => {
    const file = e.target.files?.[0];
    if (file && uploadSlotId) {
      const reader = new FileReader();
      reader.onload = (event) => {
        onSlotImageUpload?.(uploadSlotId, event.target.result);
      };
      reader.readAsDataURL(file);
    }
    e.target.value = '';
    setUploadSlotId(null);
  };

  const selectedTemplate = TEMPLATES.find(t => t.id === selectedTemplateId);
  const slots = selectedTemplate?.slots || [];

  return (
    <div>
      <input id="slot-file-input" type="file" accept="image/*" onChange={handleFileChange} className="templates-hidden-input" />

      <h3 className="templates-title">Templates</h3>

      <div className="templates-description">
        Choose a template to get started or design freely.
      </div>

      <div className="templates-list">
        {templates.map((template) => (
          <button
            key={template.id}
            onClick={() => handleSelectTemplate(template)}
            className={`template-btn${template.id === selectedTemplateId ? ' selected' : ''}`}
          >
            <div className="template-thumbnail">
              {template.thumbnail}
            </div>
            <div className="template-info">
              <div className="template-name">{template.name}</div>
              <div className="template-desc">{template.description}</div>
            </div>
            {template.hasSlots && (
              <span className="template-slots-badge">SLOTS</span>
            )}
          </button>
        ))}
      </div>

      {selectedTemplateId && selectedTemplateId !== 'freeform' && slots.length > 0 && (
        <div className="template-slots-section">
          <h4 className="template-slots-title">Template Slots</h4>
          <div className="template-slots-list">
            {slots.map((slot) => (
              <button
                key={slot.id}
                onClick={() => handleSlotClick(slot.id)}
                className="template-slot-btn"
              >
                <span className="template-slot-icon">📷</span>
                <span>{slot.label}</span>
                <span className="template-slot-dimensions">
                  {slot.bounds.width}×{slot.bounds.height}
                </span>
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
