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

interface CustomPageTabProps {
  eventId: string;
  organizationId: string;
  eventSlug?: string | null;
}

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

interface CustomPage {
  id: string;
  custom_slug: string;
  is_active: boolean;
  is_default: boolean;
  template_id?: string;
  meta_title?: string;
  meta_description?: string;
  view_count: number;
  template?: Template;
}

const CustomPageTab: React.FC<CustomPageTabProps> = ({
  eventId,
  organizationId,
  eventSlug
}) => {
  const [customPages, setCustomPages] = useState<CustomPage[]>([]);
  const [templates, setTemplates] = useState<Template[]>([]);
  const [loading, setLoading] = useState(true);
  const [showPageBuilder, setShowPageBuilder] = useState(false);
  const [showTemplateManager, setShowTemplateManager] = useState(false);
  const [selectedPageId, setSelectedPageId] = useState<string | null>(null);
  const [_selectedTemplateId, _setSelectedTemplateId] = useState<string | null>(null);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [newPageData, setNewPageData] = useState({
    custom_slug: '',
    meta_title: '',
    meta_description: '',
    template_id: ''
  });

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

  const loadData = async () => {
    try {
      console.log('Loading data for:', { organizationId, eventId });
      
      // Get auth token
      const { data: { session } } = await supabase.auth.getSession();
      console.log('Session state:', { hasSession: !!session, hasToken: !!session?.access_token });
      
      const headers: Record<string, string> = {};
      if (session?.access_token) {
        headers['Authorization'] = `Bearer ${session.access_token}`;
      }

      console.log('Making API calls...');
      const [pagesRes, templatesRes] = await Promise.all([
        fetch(`/api/custom-pages?organization_id=${organizationId}&event_id=${eventId}`, { headers }),
        fetch(`/api/templates?organization_id=${organizationId}`, { headers })
      ]);

      const pagesData = await pagesRes.json();
      const templatesData = await templatesRes.json();

      console.log('Pages response:', { status: pagesRes.status, data: pagesData });
      console.log('Templates response:', { status: templatesRes.status, data: templatesData });

      if (pagesData.success) {
        setCustomPages(pagesData.pages || []);
      } else {
        console.error('Failed to load pages:', pagesData);
        setCustomPages([]);
      }
      
      if (templatesData.success) {
        setTemplates(templatesData.templates || []);
      } else {
        console.error('Failed to load templates:', templatesData);
        setTemplates([]);
      }
    } catch (error) {
      console.error('Error in loadData:', error);
      setCustomPages([]);
      setTemplates([]);
    } finally {
      setLoading(false);
    }
  };

  const handleCreateCustomPage = async () => {
    if (!newPageData.custom_slug.trim()) {
      alert('Please enter a custom URL slug');
      return;
    }

    try {
      // Get auth token
      const { data: { session } } = await supabase.auth.getSession();
      if (!session?.access_token) {
        alert('Please log in to create custom pages');
        return;
      }

      const requestBody = {
        organization_id: organizationId,
        event_id: eventId,
        template_id: newPageData.template_id || null,
        custom_slug: newPageData.custom_slug.toLowerCase().replace(/[^a-z0-9-]/g, '-'),
        meta_title: newPageData.meta_title,
        meta_description: newPageData.meta_description,
        created_by: session.user.id
      };
      
      console.log('Sending request body:', requestBody);
      console.log('JSON string:', JSON.stringify(requestBody));
      
      const response = await fetch('/api/custom-pages', {
        method: 'POST',
        headers: { 
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${session.access_token}`
        },
        body: JSON.stringify(requestBody)
      });

      const data = await response.json();
      console.log('API Response:', { status: response.status, data });
      
      if (data.success) {
        setShowCreateModal(false);
        setNewPageData({
          custom_slug: '',
          meta_title: '',
          meta_description: '',
          template_id: ''
        });
        // Reload data to show the new page
        await loadData();
      } else {
        const errorMessage = data.details ? `${data.error}: ${data.details}` : data.error || 'Failed to create custom page';
        alert(errorMessage);
      }
    } catch (error) {
      console.error('Error creating custom page:', error);
      alert('Network error: Unable to create custom page. Please try again.');
    }
  };

  const handleEditPage = (pageId: string) => {
    setSelectedPageId(pageId);
    setShowPageBuilder(true);
  };

  const handleDeletePage = async (pageId: string) => {
    if (!confirm('Are you sure you want to delete this custom page?')) return;

    try {
      // Get auth token
      const { data: { session } } = await supabase.auth.getSession();
      if (!session?.access_token) {
        alert('Please log in to delete custom pages');
        return;
      }

      const response = await fetch(`/api/custom-pages/${pageId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${session.access_token}`
        }
      });

      if (response.ok) {
        await loadData(); // Reload data
        alert('Page deleted successfully');
      } else {
        alert('Failed to delete page');
      }
    } catch (error) {
      console.error('Error deleting page:', error);
      alert('Error deleting page');
    }
  };

  const handleTogglePageStatus = async (pageId: string, isActive: boolean) => {
    try {
      // Get auth token
      const { data: { session } } = await supabase.auth.getSession();
      if (!session?.access_token) {
        alert('Please log in to update page status');
        return;
      }

      const response = await fetch(`/api/custom-pages/${pageId}`, {
        method: 'PUT',
        headers: { 
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${session.access_token}`
        },
        body: JSON.stringify({ is_active: isActive })
      });

      if (response.ok) {
        await loadData(); // Reload data
        alert(`Page ${isActive ? 'activated' : 'deactivated'} successfully`);
      } else {
        alert('Failed to update page status');
      }
    } catch (error) {
      console.error('Error updating page status:', error);
      alert('Error updating page status');
    }
  };

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

    try {
      // Get auth token
      const { data: { session } } = await supabase.auth.getSession();
      if (!session?.access_token) {
        alert('Please log in to save page changes');
        return;
      }

      const response = await fetch(`/api/custom-pages/${selectedPageId}`, {
        method: 'PUT',
        headers: { 
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${session.access_token}`
        },
        body: JSON.stringify({
          page_data: pageData,
          updated_at: new Date().toISOString()
        })
      });

      if (response.ok) {
        alert('Page saved successfully!');
        await loadData();
      } else {
        const errorData = await response.json();
        alert(`Failed to save page: ${errorData.error || 'Unknown error'}`);
      }
    } catch (error) {
      console.error('Error saving page:', error);
      alert('Error saving page changes');
    }
  };

  const handleTemplateSelect = (template: Template) => {
    setNewPageData({
      ...newPageData,
      template_id: template.id,
      meta_title: `${eventSlug} - ${template.name}`,
      meta_description: template.description
    });
    setShowTemplateManager(false);
  };

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

  if (showPageBuilder) {
    return (
      <div className="fixed inset-0 z-50 bg-white">
        <div className="h-full flex flex-col">
          <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={() => setShowPageBuilder(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 Custom Pages
              </button>
              <h1 className="text-lg font-semibold">
                Editing Custom Page
              </h1>
            </div>
          </div>
          
          <div className="flex-1 overflow-hidden">
            <PageBuilder
              eventId={eventId}
              pageId={selectedPageId!}
              onSave={handleSavePage}
              onPreview={(pageData) => {
                console.log('Preview data:', pageData);
              }}
            />
          </div>
        </div>
      </div>
    );
  }


  if (showTemplateManager) {
    return (
      <div className="h-screen -m-6">
        <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={() => setShowTemplateManager(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 Custom Pages
            </button>
            <h1 className="text-lg font-semibold">Select Template</h1>
          </div>
        </div>
        
        <TemplateManager
          organizationId={organizationId}
          onTemplateSelect={handleTemplateSelect}
        />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-semibold text-white mb-2">Custom Sales Pages</h2>
          <p className="text-white/60">Create custom branded pages for your event with unique URLs</p>
        </div>
        <button
          onClick={() => setShowCreateModal(true)}
          className="px-4 py-2 text-white rounded-md transition-colors"
          style={{
            background: 'var(--glass-text-accent)'
          }}
        >
          Create Custom Page
        </button>
      </div>

      {/* Default Event Page Info */}
      <div className="bg-white/5 border border-white/20 rounded-xl p-4">
        <div className="flex items-center justify-between">
          <div>
            <h3 className="font-semibold text-white mb-1">Default Event Page</h3>
            <p className="text-white/60 text-sm">Standard event page accessible to everyone</p>
            <p className="text-blue-400 text-sm mt-1">
              blackcanyontickets.com/e/{eventSlug}
            </p>
          </div>
          <div className="flex items-center space-x-2">
            <span className="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-green-500/20 text-green-400">
              Active
            </span>
          </div>
        </div>
      </div>

      {/* Custom Pages List */}
      <div className="space-y-4">
        {customPages.length === 0 ? (
          <div className="text-center py-8 border-2 border-dashed border-white/20 rounded-xl">
            <div className="text-4xl mb-4">🎨</div>
            <h3 className="text-lg font-medium text-white mb-2">No Custom Pages Yet</h3>
            <p className="text-white/60 mb-4">Create custom branded pages with unique URLs for better marketing</p>
            <button
              onClick={() => setShowCreateModal(true)}
              className="px-4 py-2 text-white rounded-md transition-colors"
          style={{
            background: 'var(--glass-text-accent)'
          }}
            >
              Create Your First Custom Page
            </button>
          </div>
        ) : (
          customPages.map((page) => (
            <div
              key={page.id}
              className="bg-white/5 border border-white/20 rounded-xl p-4"
            >
              <div className="flex items-center justify-between">
                <div className="flex-1">
                  <div className="flex items-center space-x-3 mb-2">
                    <h3 className="font-semibold text-white">
                      {page.meta_title || `Custom Page - ${page.custom_slug}`}
                    </h3>
                    <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${
                      page.is_active 
                        ? 'bg-green-500/20 text-green-400' 
                        : 'bg-gray-500/20 text-gray-400'
                    }`}>
                      {page.is_active ? 'Active' : 'Inactive'}
                    </span>
                    {page.template && (
                      <span className="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-blue-500/20 text-blue-400">
                        Template: {page.template.name}
                      </span>
                    )}
                  </div>
                  <p className="text-blue-400 text-sm mb-1">
                    blackcanyontickets.com/{page.custom_slug}
                  </p>
                  {page.meta_description && (
                    <p className="text-white/60 text-sm">{page.meta_description}</p>
                  )}
                  <div className="flex items-center space-x-4 mt-2 text-xs text-white/40">
                    <span>{page.view_count} views</span>
                    <span>Created {new Date(page.created_at).toLocaleDateString()}</span>
                  </div>
                </div>
                
                <div className="flex items-center space-x-2">
                  <button
                    onClick={() => window.open(`/${page.custom_slug}`, '_blank')}
                    className="px-3 py-1 text-xs text-blue-400 hover:text-blue-300 border border-blue-400/50 rounded hover:bg-blue-400/10"
                  >
                    View
                  </button>
                  <button
                    onClick={() => handleEditPage(page.id)}
                    className="px-3 py-1 text-xs text-white hover:text-gray-200 border border-white/50 rounded hover:bg-white/10"
                  >
                    Edit
                  </button>
                  <button
                    onClick={() => handleTogglePageStatus(page.id, !page.is_active)}
                    className={`px-3 py-1 text-xs border rounded ${
                      page.is_active
                        ? 'text-yellow-400 border-yellow-400/50 hover:bg-yellow-400/10'
                        : 'text-green-400 border-green-400/50 hover:bg-green-400/10'
                    }`}
                  >
                    {page.is_active ? 'Deactivate' : 'Activate'}
                  </button>
                  <button
                    onClick={() => handleDeletePage(page.id)}
                    className="px-3 py-1 text-xs text-red-400 hover:text-red-300 border border-red-400/50 rounded hover:bg-red-400/10"
                  >
                    Delete
                  </button>
                </div>
              </div>
            </div>
          ))
        )}
      </div>


      {/* Create Custom Page 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-2xl w-full p-6">
            <h2 className="text-xl font-bold mb-4 text-gray-900">Create Custom Page</h2>
            
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Custom URL Slug
                </label>
                <div className="flex">
                  <span className="inline-flex items-center px-3 py-2 border border-gray-300 border-r-0 rounded-l-md bg-gray-50 text-gray-500 text-sm">
                    blackcanyontickets.com/
                  </span>
                  <input
                    type="text"
                    value={newPageData.custom_slug}
                    onChange={(e) => setNewPageData({ 
                      ...newPageData, 
                      custom_slug: e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, '-')
                    })}
                    className="flex-1 px-3 py-2 border border-gray-300 rounded-r-md focus:outline-none focus:ring-2 text-gray-900"
                    style={{
                      '--tw-ring-color': 'var(--glass-text-accent)'
                    } as React.CSSProperties}
                    placeholder="festival2024"
                  />
                </div>
                <p className="text-xs text-gray-500 mt-1">Use lowercase letters, numbers, and hyphens only</p>
              </div>
              
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Page Title (for SEO)
                </label>
                <input
                  type="text"
                  value={newPageData.meta_title}
                  onChange={(e) => setNewPageData({ ...newPageData, meta_title: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 text-gray-900"
                  style={{
                    '--tw-ring-color': 'var(--glass-text-accent)'
                  } as React.CSSProperties}
                  placeholder="Amazing Festival 2024 - Get Your Tickets"
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Meta Description
                </label>
                <textarea
                  value={newPageData.meta_description}
                  onChange={(e) => setNewPageData({ ...newPageData, meta_description: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 text-gray-900"
                  style={{
                    '--tw-ring-color': 'var(--glass-text-accent)'
                  } as React.CSSProperties}
                  rows={3}
                  placeholder="Join us for an unforgettable festival experience..."
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Template (Optional)
                </label>
                <div className="flex space-x-2">
                  <select
                    value={newPageData.template_id}
                    onChange={(e) => setNewPageData({ ...newPageData, template_id: e.target.value })}
                    className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 text-gray-900"
                    style={{
                      '--tw-ring-color': 'var(--glass-text-accent)'
                    } as React.CSSProperties}
                  >
                    <option value="">No template (start from scratch)</option>
                    {templates.map(template => (
                      <option key={template.id} value={template.id}>
                        {template.name}
                      </option>
                    ))}
                  </select>
                  <button
                    onClick={() => setShowTemplateManager(true)}
                    className="px-4 py-2 rounded-md border"
                    style={{
                      color: 'var(--glass-text-accent)',
                      borderColor: 'var(--glass-text-accent)'
                    }}
                  >
                    Browse Templates
                  </button>
                </div>
              </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={handleCreateCustomPage}
                className="px-4 py-2 text-white rounded-md transition-colors"
          style={{
            background: 'var(--glass-text-accent)'
          }}
              >
                Create Page
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default CustomPageTab;