import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { useTheme } from '../contexts/ThemeContext';

function ThemesManager() {
  const { 
    currentTheme, 
    allThemes, 
    activeThemeId, 
    loading, 
    error,
    setActiveTheme, 
    deleteTheme, 
    exportTheme 
  } = useTheme();

  const [changingTheme, setChangingTheme] = useState(null);
  const [deletingTheme, setDeletingTheme] = useState(null);

  const handleSetActive = async (themeId) => {
    setChangingTheme(themeId);
    try {
      const result = await setActiveTheme(themeId);
      if (!result.success) {
        // Check if it's an authentication error
        if (result.error.includes('401') || result.error.includes('Authentication required')) {
          alert('You need to be logged in as an admin to change themes. Please log in and try again.');
        } else {
          alert(`Failed to set theme: ${result.error}`);
        }
      }
    } finally {
      setChangingTheme(null);
    }
  };

  const handleDelete = async (themeId) => {
    if (!confirm('Are you sure you want to delete this theme? This action cannot be undone.')) {
      return;
    }

    setDeletingTheme(themeId);
    try {
      await deleteTheme(themeId);
    } finally {
      setDeletingTheme(null);
    }
  };

  const handleExport = async (themeId) => {
    await exportTheme(themeId);
  };

  const ThemeCard = ({ theme }) => {
    const isActive = theme.id === activeThemeId;
    const isChanging = changingTheme === theme.id;
    const isDeleting = deletingTheme === theme.id;

    return (
      <div className={`relative bg-white rounded-lg border-2 overflow-hidden transition-all duration-200 ${
        isActive ? 'border-blue-500 shadow-lg' : 'border-gray-200 hover:border-gray-300 shadow'
      }`}>
        {/* Theme Preview */}
        <div className="h-32 relative" style={{ backgroundColor: theme.colors.background }}>
          <div className="absolute inset-0 p-4">
            {/* Mini header */}
            <div className="flex items-center justify-between mb-2">
              <div className="h-2 w-16 rounded" style={{ backgroundColor: theme.colors.primary }}></div>
              <div className="flex space-x-1">
                <div className="h-2 w-2 rounded-full" style={{ backgroundColor: theme.colors.accent }}></div>
                <div className="h-2 w-2 rounded-full" style={{ backgroundColor: theme.colors.secondary }}></div>
              </div>
            </div>
            
            {/* Mini content */}
            <div className="space-y-2">
              <div className="h-3 w-full rounded" style={{ backgroundColor: theme.colors.surface }}></div>
              <div className="h-2 w-3/4 rounded" style={{ backgroundColor: theme.colors.textSecondary }}></div>
              <div className="h-2 w-1/2 rounded" style={{ backgroundColor: theme.colors.textSecondary }}></div>
            </div>
            
            {/* Mini button */}
            <div className="absolute bottom-3 right-3">
              <div className="h-6 w-12 rounded text-xs flex items-center justify-center text-white font-medium"
                   style={{ backgroundColor: theme.colors.primary }}>
                BTN
              </div>
            </div>
          </div>
        </div>

        {/* Theme Info */}
        <div className="p-4">
          <div className="flex items-center justify-between mb-2">
            <h3 className="font-semibold text-gray-900">{theme.name}</h3>
            {isActive && (
              <span className="bg-green-100 text-green-800 text-xs px-2 py-1 rounded-full font-medium">
                Active
              </span>
            )}
            {theme.isBuiltIn && (
              <span className="bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded-full font-medium">
                Built-in
              </span>
            )}
          </div>
          
          <p className="text-sm text-gray-500 mb-3">
            {theme.id} • {theme.isBuiltIn ? 'System theme' : 'Custom theme'}
          </p>

          {/* Color Palette Preview */}
          <div className="flex space-x-1 mb-4">
            <div className="h-4 w-4 rounded border border-gray-200" 
                 style={{ backgroundColor: theme.colors.primary }}></div>
            <div className="h-4 w-4 rounded border border-gray-200" 
                 style={{ backgroundColor: theme.colors.background }}></div>
            <div className="h-4 w-4 rounded border border-gray-200" 
                 style={{ backgroundColor: theme.colors.surface }}></div>
            <div className="h-4 w-4 rounded border border-gray-200" 
                 style={{ backgroundColor: theme.colors.text }}></div>
            <div className="h-4 w-4 rounded border border-gray-200" 
                 style={{ backgroundColor: theme.colors.accent }}></div>
          </div>

          {/* Actions */}
          <div className="flex space-x-2">
            {!isActive && (
              <button
                onClick={() => handleSetActive(theme.id)}
                disabled={isChanging}
                className="flex-1 bg-blue-600 text-white py-2 px-3 rounded text-sm font-medium hover:bg-blue-700 disabled:opacity-50"
              >
                {isChanging ? 'Applying...' : 'Apply'}
              </button>
            )}
            
            <Link
              to={`/admin/themes/${theme.id}/edit`}
              className="flex-1 bg-gray-100 text-gray-700 py-2 px-3 rounded text-sm font-medium hover:bg-gray-200 text-center"
            >
              {theme.isBuiltIn ? 'Clone' : 'Edit'}
            </Link>
            
            <button
              onClick={() => handleExport(theme.id)}
              className="bg-green-100 text-green-700 py-2 px-3 rounded text-sm font-medium hover:bg-green-200"
              title="Export Theme"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
              </svg>
            </button>
            
            {!theme.isBuiltIn && (
              <button
                onClick={() => handleDelete(theme.id)}
                disabled={isDeleting}
                className="bg-red-100 text-red-700 py-2 px-3 rounded text-sm font-medium hover:bg-red-200 disabled:opacity-50"
                title="Delete Theme"
              >
                {isDeleting ? (
                  <div className="w-4 h-4 border-2 border-red-700 border-t-transparent rounded-full animate-spin"></div>
                ) : (
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                  </svg>
                )}
              </button>
            )}
          </div>
        </div>
      </div>
    );
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">Loading themes...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
        {/* Header */}
        <div className="bg-white shadow rounded-lg mb-6">
          <div className="px-6 py-4 border-b border-gray-200 flex justify-between items-center">
            <div>
              <h1 className="text-2xl font-bold text-gray-900">Theme Manager</h1>
              <p className="text-gray-600">Customize your blog's appearance</p>
            </div>
            <div className="flex space-x-3">
              <Link
                to="/admin"
                className="bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 transition-colors"
              >
                Back to Admin
              </Link>
              <Link
                to="/admin/themes/new"
                className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors"
              >
                Create Theme
              </Link>
            </div>
          </div>
        </div>

        {error && (
          <div className="mb-6 bg-red-50 border border-red-200 rounded-lg p-4">
            <div className="flex">
              <svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
              </svg>
              <p className="ml-3 text-sm text-red-700">{error}</p>
            </div>
          </div>
        )}

        {/* Current Theme Info */}
        {currentTheme && (
          <div className="bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-lg p-6 mb-6">
            <div className="flex items-center justify-between">
              <div>
                <h2 className="text-lg font-semibold text-blue-900">Currently Active Theme</h2>
                <p className="text-blue-700">
                  <span className="font-medium">{currentTheme.name}</span> is currently applied to your blog
                </p>
              </div>
              <div className="flex items-center space-x-2">
                <div className="flex space-x-1">
                  {Object.entries(currentTheme.colors).slice(0, 5).map(([key, value]) => (
                    <div 
                      key={key}
                      className="w-6 h-6 rounded border-2 border-white shadow-sm"
                      style={{ backgroundColor: value }}
                      title={`${key}: ${value}`}
                    ></div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Themes Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {allThemes.map((theme) => (
            <ThemeCard key={theme.id} theme={theme} />
          ))}
        </div>

        {allThemes.length === 0 && (
          <div className="text-center py-12">
            <svg className="mx-auto h-12 w-12 text-gray-400" stroke="currentColor" fill="none" viewBox="0 0 48 48">
              <path d="M34 40h10v-4a6 6 0 00-10.712-3.714M34 40H14m20 0v-4a9.971 9.971 0 00-.712-3.714M14 40H4v-4a6 6 0 0110.713-3.714M14 40v-4c0-1.313.253-2.566.713-3.714m0 0A9.971 9.971 0 0118 28a9.971 9.971 0 014 4.286" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" />
            </svg>
            <h3 className="mt-2 text-sm font-medium text-gray-900">No themes found</h3>
            <p className="mt-1 text-sm text-gray-500">Get started by creating your first custom theme.</p>
            <div className="mt-6">
              <Link
                to="/admin/themes/new"
                className="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700"
              >
                Create Theme
              </Link>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

export default ThemesManager;