import React, { useState } from 'react';

const builtInTemplates = [
  { id: 'gaming', name: 'Gaming', icon: '🎮', description: 'Perfect for gaming communities', channels: ['general', 'voice-chat', 'lfg', 'clips', 'memes'], roles: ['Admin', 'Moderator', 'Member'] },
  { id: 'school', name: 'School Club', icon: '📚', description: 'For study groups and school clubs', channels: ['announcements', 'homework-help', 'resources', 'off-topic', 'voice-study'], roles: ['Teacher', 'TA', 'Student'] },
  { id: 'creator', name: 'Content Creator', icon: '🎬', description: 'For streamers and creators', channels: ['announcements', 'stream-chat', 'clips', 'fan-art', 'suggestions'], roles: ['Creator', 'Mod', 'Subscriber', 'Fan'] },
  { id: 'friends', name: 'Friends', icon: '👥', description: 'Casual hangout space', channels: ['general', 'memes', 'music', 'gaming'], roles: ['Admin', 'Member'] },
  { id: 'local', name: 'Local Community', icon: '🏘️', description: 'For local groups and neighborhoods', channels: ['announcements', 'events', 'marketplace', 'discussion'], roles: ['Organizer', 'Member'] },
];

const myTemplates = [
  { id: 'my-dev', name: 'Dev Team Setup', icon: '💻', description: 'My development team template', channels: ['general', 'backend', 'frontend', 'devops', 'standup'], roles: ['Lead', 'Senior', 'Junior', 'Intern'], createdAt: '2025-01-15' },
];

export default function ServerTemplate({ mode = 'apply', currentServer, onClose, onApply, onSave }) {
  const [activeTab, setActiveTab] = useState('browse');
  const [selectedTemplate, setSelectedTemplate] = useState(null);
  const [templateName, setTemplateName] = useState('');
  const [templateDesc, setTemplateDesc] = useState('');
  const [includeChannels, setIncludeChannels] = useState(true);
  const [includeRoles, setIncludeRoles] = useState(true);
  const [includeSettings, setIncludeSettings] = useState(true);

  const handleApplyTemplate = () => {
    if (selectedTemplate) {
      onApply?.(selectedTemplate);
    }
  };

  const handleSaveTemplate = () => {
    onSave?.({
      name: templateName,
      description: templateDesc,
      includeChannels,
      includeRoles,
      includeSettings,
    });
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="server-template-modal" onClick={(e) => e.stopPropagation()}>
        <div className="template-header">
          <h2>📋 Server Templates</h2>
          <button className="template-close" onClick={onClose}>✕</button>
        </div>

        <div className="template-tabs">
          <button
            className={`template-tab ${activeTab === 'browse' ? 'active' : ''}`}
            onClick={() => setActiveTab('browse')}
          >
            Browse Templates
          </button>
          <button
            className={`template-tab ${activeTab === 'my-templates' ? 'active' : ''}`}
            onClick={() => setActiveTab('my-templates')}
          >
            My Templates
          </button>
          <button
            className={`template-tab ${activeTab === 'create' ? 'active' : ''}`}
            onClick={() => setActiveTab('create')}
          >
            Create Template
          </button>
        </div>

        <div className="template-content">
          {activeTab === 'browse' && (
            <div className="template-browse">
              <p className="template-intro">
                Start your server with a template to get channels, roles, and settings pre-configured.
              </p>
              <div className="template-grid">
                {builtInTemplates.map(template => (
                  <div
                    key={template.id}
                    className={`template-card ${selectedTemplate?.id === template.id ? 'selected' : ''}`}
                    onClick={() => setSelectedTemplate(template)}
                  >
                    <div className="template-icon">{template.icon}</div>
                    <div className="template-info">
                      <h3>{template.name}</h3>
                      <p>{template.description}</p>
                    </div>
                    <div className="template-preview">
                      <div className="preview-section">
                        <span className="preview-label">Channels:</span>
                        <span className="preview-count">{template.channels.length}</span>
                      </div>
                      <div className="preview-section">
                        <span className="preview-label">Roles:</span>
                        <span className="preview-count">{template.roles.length}</span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>

              {selectedTemplate && (
                <div className="template-detail">
                  <h3>{selectedTemplate.icon} {selectedTemplate.name}</h3>
                  <div className="detail-section">
                    <h4>Channels</h4>
                    <div className="detail-items">
                      {selectedTemplate.channels.map(ch => (
                        <span key={ch} className="detail-item">#{ch}</span>
                      ))}
                    </div>
                  </div>
                  <div className="detail-section">
                    <h4>Roles</h4>
                    <div className="detail-items">
                      {selectedTemplate.roles.map(role => (
                        <span key={role} className="detail-item role">@{role}</span>
                      ))}
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}

          {activeTab === 'my-templates' && (
            <div className="my-templates">
              {myTemplates.length === 0 ? (
                <div className="no-templates">
                  <span className="no-templates-icon">📁</span>
                  <p>No saved templates</p>
                  <span>Create a template from your server to save it here</span>
                </div>
              ) : (
                <div className="template-list">
                  {myTemplates.map(template => (
                    <div
                      key={template.id}
                      className={`template-list-item ${selectedTemplate?.id === template.id ? 'selected' : ''}`}
                      onClick={() => setSelectedTemplate(template)}
                    >
                      <div className="template-icon">{template.icon}</div>
                      <div className="template-info">
                        <h3>{template.name}</h3>
                        <p>{template.description}</p>
                        <span className="template-date">Created {template.createdAt}</span>
                      </div>
                      <div className="template-actions">
                        <button className="template-action-btn" title="Edit">✏️</button>
                        <button className="template-action-btn" title="Delete">🗑️</button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {activeTab === 'create' && (
            <div className="create-template">
              <p className="create-intro">
                Create a template from your current server configuration.
              </p>

              <div className="create-form">
                <div className="form-group">
                  <label>Template Name</label>
                  <input
                    type="text"
                    value={templateName}
                    onChange={(e) => setTemplateName(e.target.value)}
                    placeholder="My Server Template"
                  />
                </div>

                <div className="form-group">
                  <label>Description</label>
                  <textarea
                    value={templateDesc}
                    onChange={(e) => setTemplateDesc(e.target.value)}
                    placeholder="Describe what this template is for..."
                    rows={3}
                  />
                </div>

                <div className="form-group">
                  <label>Include in Template</label>
                  <div className="include-options">
                    <label className="include-option">
                      <input
                        type="checkbox"
                        checked={includeChannels}
                        onChange={(e) => setIncludeChannels(e.target.checked)}
                      />
                      <span>Channels & Categories</span>
                    </label>
                    <label className="include-option">
                      <input
                        type="checkbox"
                        checked={includeRoles}
                        onChange={(e) => setIncludeRoles(e.target.checked)}
                      />
                      <span>Roles & Permissions</span>
                    </label>
                    <label className="include-option">
                      <input
                        type="checkbox"
                        checked={includeSettings}
                        onChange={(e) => setIncludeSettings(e.target.checked)}
                      />
                      <span>Server Settings</span>
                    </label>
                  </div>
                </div>

                <div className="template-warning">
                  <span>⚠️</span>
                  <span>Templates do not include messages, members, or server-specific content.</span>
                </div>
              </div>
            </div>
          )}
        </div>

        <div className="template-footer">
          <button className="cancel-btn" onClick={onClose}>Cancel</button>
          {activeTab === 'create' ? (
            <button
              className="save-btn"
              onClick={handleSaveTemplate}
              disabled={!templateName.trim()}
            >
              Create Template
            </button>
          ) : (
            <button
              className="apply-btn"
              onClick={handleApplyTemplate}
              disabled={!selectedTemplate}
            >
              Use Template
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
