import React, { useState, useEffect } from 'react';
import PageBuilder from './PageBuilder';

interface Template {
  id: string;
  name: string;
  description: string;
  preview_image_url?: string;
  created_at: string;
  updated_at: string;
  is_active: boolean;
}

interface TemplateManagerProps {
  organizationId: string;
  onTemplateSelect?: (template: Template) => void;
}

const TemplateManager: React.FC<TemplateManagerProps> = ({
  organizationId,
  onTemplateSelect
}) => {
  const [templates, setTemplates] = useState<Template[]>([]);
  const [loading, setLoading] = useState(true);
  const [showBuilder, setShowBuilder] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState<Template | null>(null);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [newTemplate, setNewTemplate] = useState({ name: '', description: '' });

  useEffect(() => {
    loadTemplates();
  }, [organizationId]);

  const loadTemplates = async () => {
    try {
      const response = await fetch(`/api/templates?organization_id=${organizationId}`);
      const data = await response.json();
      
      if (data.success) {
        setTemplates(data.templates);
      }
    } catch (error) {
      console.error('Templates loading error:', error);
      // Silently handle error - user will see empty state
    } finally {
      setLoading(false);
    }
  };

  const handleCreateTemplate = async () => {
    if (!newTemplate.name.trim()) return;

    try {
      const response = await fetch('/api/templates', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: newTemplate.name,
          description: newTemplate.description,
          organization_id: organizationId
        })
      });

      const data = await response.json();
      
      if (data.success) {
        setTemplates([...templates, data.template]);
        setShowCreateModal(false);
        setNewTemplate({ name: '', description: '' });
        setSelectedTemplate(data.template);
        setShowBuilder(true);
      }
    } catch (error) {
      console.error('Template creation error:', error);
      // Error creating template - user will see modal remain open
    }
  };

  const handleEditTemplate = (template: Template) => {
    setSelectedTemplate(template);
    setShowBuilder(true);
  };

  const handleDeleteTemplate = async (templateId: string) => {
    if (!confirm('Are you sure you want to delete this template?')) return;

    try {
      const response = await fetch(`/api/templates/${templateId}`, {
        method: 'DELETE'
      });

      if (response.ok) {
        setTemplates(templates.filter(t => t.id !== templateId));
      }
    } catch (error) {
      console.error('Template deletion error:', error);
      // Error deleting template - user will see no change
    }
  };

  const handleSaveTemplate = async (pageData: Record<string, unknown>) => {
    if (!selectedTemplate) return;

    try {
      const response = await fetch(`/api/templates/${selectedTemplate.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          page_data: pageData,
          updated_at: new Date().toISOString()
        })
      });

      if (response.ok) {
        alert('Template saved successfully!');
        loadTemplates();
      }
    } catch (error) {
      console.error('Template save error:', error);
      alert('Failed to save template. Please try again.');
    }
  };

  const handlePreviewTemplate = (_pageData: Record<string, unknown>) => {
    // Open preview in new window
    const previewWindow = window.open('', '_blank', 'width=1200,height=800');
    if (previewWindow) {
      previewWindow.document.write(`
        <html>
          <head>
            <title>Template Preview</title>
            <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
          </head>
          <body class="bg-gray-100">
            <div class="p-8">
              <div class="max-w-4xl mx-auto bg-white rounded-lg shadow-lg">
                <div class="p-6">
                  <h1 class="text-2xl font-bold mb-4">Template Preview</h1>
                  <div id="preview-content">
                    <!-- Preview content would be rendered here -->
                    <p class="text-gray-600">Preview functionality coming soon...</p>
                  </div>
                </div>
              </div>
            </div>
          </body>
        </html>
      `);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
      </div>
    );
  }

  if (showBuilder) {
    return (
      <div className="h-screen">
        <div className="bg-white border-b border-gray-200 p-4 flex items-center justify-between">
          <div className="flex items-center space-x-4">
            <button
              onClick={() => setShowBuilder(false)}
              className="flex items-center px-3 py-2 text-sm text-gray-600 hover:text-gray-900 border border-gray-300 rounded-md hover:bg-gray-50"
            >
              ← Back to Templates
            </button>
            <h1 className="text-lg font-semibold">
              {selectedTemplate ? `Editing: ${selectedTemplate.name}` : 'New Template'}
            </h1>
          </div>
        </div>
        
        <PageBuilder
          eventId="" // Templates don't have specific event IDs
          templateId={selectedTemplate?.id}
          onSave={handleSaveTemplate}
          onPreview={handlePreviewTemplate}
        />
      </div>
    );
  }

  return (
    <div className="p-6">
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-gray-900">Page Templates</h1>
        <button
          onClick={() => setShowCreateModal(true)}
          className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
        >
          Create New Template
        </button>
      </div>

      {/* Templates Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {templates.map((template) => (
          <div
            key={template.id}
            className="bg-white rounded-lg shadow-md border border-gray-200 overflow-hidden hover:shadow-lg transition-shadow"
          >
            {/* Template Preview */}
            <div className="aspect-video bg-gray-100 flex items-center justify-center">
              {template.preview_image_url ? (
                <img
                  src={template.preview_image_url}
                  alt={template.name}
                  className="w-full h-full object-cover"
                />
              ) : (
                <div className="text-gray-400">
                  <div className="text-4xl mb-2">🎨</div>
                  <p className="text-sm">No Preview</p>
                </div>
              )}
            </div>

            {/* Template Info */}
            <div className="p-4">
              <h3 className="font-semibold text-gray-900 mb-1">{template.name}</h3>
              {template.description && (
                <p className="text-sm text-gray-600 mb-3">{template.description}</p>
              )}
              
              <div className="flex items-center justify-between text-xs text-gray-500 mb-3">
                <span>Updated {new Date(template.updated_at).toLocaleDateString()}</span>
                <span className={`px-2 py-1 rounded-full ${
                  template.is_active 
                    ? 'bg-green-100 text-green-800' 
                    : 'bg-gray-100 text-gray-600'
                }`}>
                  {template.is_active ? 'Active' : 'Inactive'}
                </span>
              </div>

              {/* Actions */}
              <div className="flex space-x-2">
                <button
                  onClick={() => handleEditTemplate(template)}
                  className="flex-1 px-3 py-2 text-sm text-blue-600 hover:text-blue-800 border border-blue-300 rounded-md hover:bg-blue-50"
                >
                  Edit
                </button>
                <button
                  onClick={() => onTemplateSelect?.(template)}
                  className="flex-1 px-3 py-2 text-sm text-green-600 hover:text-green-800 border border-green-300 rounded-md hover:bg-green-50"
                >
                  Use
                </button>
                <button
                  onClick={() => handleDeleteTemplate(template.id)}
                  className="px-3 py-2 text-sm text-red-600 hover:text-red-800 border border-red-300 rounded-md hover:bg-red-50"
                >
                  Delete
                </button>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Empty State */}
      {templates.length === 0 && (
        <div className="text-center py-12">
          <div className="text-6xl mb-4">🎨</div>
          <h3 className="text-lg font-medium text-gray-900 mb-2">No Templates Yet</h3>
          <p className="text-gray-600 mb-4">Create your first template to get started</p>
          <button
            onClick={() => setShowCreateModal(true)}
            className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
          >
            Create Your First Template
          </button>
        </div>
      )}

      {/* Create Template Modal */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-lg max-w-md w-full p-6">
            <h2 className="text-xl font-bold mb-4">Create New Template</h2>
            
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Template Name
                </label>
                <input
                  type="text"
                  value={newTemplate.name}
                  onChange={(e) => setNewTemplate({ ...newTemplate, name: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="Enter template name"
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Description (Optional)
                </label>
                <textarea
                  value={newTemplate.description}
                  onChange={(e) => setNewTemplate({ ...newTemplate, description: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  rows={3}
                  placeholder="Describe your template"
                />
              </div>
            </div>
            
            <div className="flex justify-end space-x-2 mt-6">
              <button
                onClick={() => setShowCreateModal(false)}
                className="px-4 py-2 text-gray-600 hover:text-gray-800 border border-gray-300 rounded-md hover:bg-gray-50"
              >
                Cancel
              </button>
              <button
                onClick={handleCreateTemplate}
                className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
              >
                Create Template
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default TemplateManager;