import React, { useState, useEffect } from 'react';
import useProjectStore from '../../store/projectStore';
import { getTemplatesByCategory, transformTemplateData } from '../../services/api';
import CustomCategoryCreator from './CustomCategoryCreator';

export default function ProjectTypeSelector() {
  const [selectedCard, setSelectedCard] = useState(null);
  const [projectName, setProjectName] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('Business & Enterprise');
  const [showCustomCreator, setShowCustomCreator] = useState(false);
  const [customCategories, setCustomCategories] = useState({});
  
  // NEW: API state management
  const [templates, setTemplates] = useState({});
  const [isLoadingTemplates, setIsLoadingTemplates] = useState(true);
  const [apiError, setApiError] = useState(null);
  
  const { setProjectType, setProjectName: storeSetProjectName, setCurrentStep } = useProjectStore();

  // NEW: Load templates from Template-Manager API
  useEffect(() => {
    const loadTemplates = async () => {
      try {
        setIsLoadingTemplates(true);
        setApiError(null);
        
        console.log('🏗️ Loading templates from Template-Manager...');
        const apiTemplates = await getTemplatesByCategory();
        const transformedTemplates = transformTemplateData(apiTemplates);
        
        setTemplates(transformedTemplates);
        console.log('✅ Templates loaded successfully:', transformedTemplates);
        
        // Set default category if current selection doesn't exist
        if (!transformedTemplates[selectedCategory]) {
          const firstCategory = Object.keys(transformedTemplates)[0];
          if (firstCategory) {
            setSelectedCategory(firstCategory);
          }
        }
        
      } catch (error) {
        console.error('❌ Failed to load templates:', error);
        setApiError(error.message);
        
        // Fallback: Keep using any existing templates or empty state
        console.log('⚠️ Using fallback empty templates due to API error');
        setTemplates({});
      } finally {
        setIsLoadingTemplates(false);
      }
    };

    loadTemplates();
  }, []); // Load once on component mount

  // Combine API templates with custom categories
  const allCategories = { ...templates, ...customCategories };
  const categoryNames = Object.keys(allCategories);

  const handleCardSelect = (projectType) => {
    setSelectedCard(projectType);
  };

  const handleContinue = () => {
    if (selectedCard && projectName.trim()) {
      setProjectType(selectedCard);
      storeSetProjectName(projectName.trim());
      setCurrentStep('features');
    }
  };

  const handleCreateCategory = (customCategory) => {
    const categoryName = `${customCategory.title} (Custom)`;
    setCustomCategories(prev => ({
      ...prev,
      [categoryName]: [customCategory]
    }));
    setSelectedCategory(categoryName);
  };

  // Loading state
  if (isLoadingTemplates) {
    return (
      <div className="space-y-6">
        <div className="text-center">
          <h2 className="text-2xl font-semibold text-gray-900 mb-2">
            Loading Templates...
          </h2>
          <p className="text-gray-600">
            Fetching the latest templates from our database
          </p>
        </div>
        
        <div className="flex justify-center items-center py-12">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
        </div>
      </div>
    );
  }

  // Error state with fallback
  if (apiError && Object.keys(allCategories).length === 0) {
    return (
      <div className="space-y-6">
        <div className="text-center">
          <h2 className="text-2xl font-semibold text-gray-900 mb-2">
            Unable to Load Templates
          </h2>
          <p className="text-gray-600 mb-4">
            {apiError}
          </p>
          <button
            onClick={() => window.location.reload()}
            className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
          >
            Try Again
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="text-center">
        <h2 className="text-2xl font-semibold text-gray-900 mb-2">
          What type of application do you want to build?
        </h2>
        <p className="text-gray-600">
          Choose from our comprehensive categories or create your own custom project type
        </p>
        {/* Show API status indicator */}
        {apiError && (
          <div className="mt-2 text-sm text-yellow-600 bg-yellow-50 px-3 py-1 rounded-md inline-block">
            ⚠️ Using cached templates - some features may be limited
          </div>
        )}
      </div>

      {/* Category Tabs */}
      <div className="border-b border-gray-200">
        <div className="flex flex-wrap gap-2 -mb-px">
          {categoryNames.map((category) => (
            <button
              key={category}
              onClick={() => setSelectedCategory(category)}
              className={`px-4 py-2 text-sm font-medium rounded-t-lg transition-colors ${
                selectedCategory === category
                  ? 'border-b-2 border-blue-500 text-blue-600 bg-blue-50'
                  : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
              }`}
            >
              {category}
              {/* Show count for each category */}
              <span className="ml-1 text-xs text-gray-400">
                ({allCategories[category]?.length || 0})
              </span>
            </button>
          ))}
          <button
            onClick={() => setShowCustomCreator(true)}
            className="px-4 py-2 text-sm font-medium text-blue-600 hover:text-blue-700 hover:bg-blue-50 rounded-t-lg transition-colors border border-blue-200 border-dashed"
          >
            + Create Category
          </button>
        </div>
      </div>

      {/* Project Cards for Selected Category */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {allCategories[selectedCategory]?.map((card) => (
          <div
            key={card.type}
            onClick={() => handleCardSelect(card.type)}
            className={`group cursor-pointer transform transition-all duration-200 hover:scale-105 ${
              selectedCard === card.type ? 'ring-2 ring-blue-500' : ''
            }`}
          >
            <div className={`p-6 bg-gradient-to-br ${card.gradient} border ${card.border} rounded-lg hover:shadow-md h-full`}>
              <div className="text-center mb-4">
                <div className="text-4xl mb-3">{card.icon}</div>
                <h3 className={`font-semibold ${card.text} mb-2`}>
                  {card.title}
                  {card.isCustom && <span className="text-xs ml-1 bg-white bg-opacity-50 px-1 rounded">Custom</span>}
                </h3>
                <p className={`${card.subtext} text-sm mb-4`}>{card.description}</p>
              </div>
              
              <div className="space-y-2">
                <p className={`${card.text} font-medium text-xs`}>Key Features:</p>
                <div className="space-y-1">
                  {card.features.slice(0, 4).map((feature, index) => (
                    <div key={index} className={`${card.subtext} text-xs flex items-center`}>
                      <span className="w-1 h-1 bg-current rounded-full mr-2"></span>
                      {feature}
                    </div>
                  ))}
                  {card.features.length > 4 && (
                    <div className={`${card.subtext} text-xs italic`}>
                      +{card.features.length - 4} more features
                    </div>
                  )}
                </div>
              </div>
              
              {selectedCard === card.type && (
                <div className="mt-4 p-2 bg-white bg-opacity-50 rounded border border-blue-300">
                  <p className="text-blue-800 text-xs font-medium text-center">✓ Selected</p>
                </div>
              )}
            </div>
          </div>
        ))}
      </div>

      {/* Empty state for categories with no templates */}
      {allCategories[selectedCategory]?.length === 0 && (
        <div className="text-center py-12">
          <div className="text-gray-400 text-6xl mb-4">📂</div>
          <h3 className="text-lg font-medium text-gray-900 mb-2">
            No templates in this category yet
          </h3>
          <p className="text-gray-600 mb-4">
            Be the first to create a template in "{selectedCategory}"
          </p>
          <button
            onClick={() => setShowCustomCreator(true)}
            className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
          >
            Create Template
          </button>
        </div>
      )}

      {/* Category Stats */}
      <div className="text-center text-sm text-gray-500">
        Showing {allCategories[selectedCategory]?.length || 0} project types in "{selectedCategory}"
        • Total categories: {categoryNames.length}
        • Total project types: {Object.values(allCategories).flat().length}
        {!apiError && (
          <span className="text-green-600 ml-2">• ✅ Live from database</span>
        )}
      </div>

      {selectedCard && (
        <div className="bg-white border border-gray-200 rounded-lg p-6">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">
            Project Details
          </h3>
          
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Project Name
              </label>
              <input
                type="text"
                value={projectName}
                onChange={(e) => setProjectName(e.target.value)}
                placeholder="e.g., HealthCare Pro, My E-commerce Store, Legal Practice Manager"
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>
            
            <button
              onClick={handleContinue}
              disabled={!projectName.trim()}
              className={`w-full py-2 px-4 rounded-md font-medium transition-colors ${
                projectName.trim()
                  ? 'bg-blue-600 text-white hover:bg-blue-700'
                  : 'bg-gray-300 text-gray-500 cursor-not-allowed'
              }`}
            >
              Continue to Feature Selection →
            </button>
          </div>
        </div>
      )}

      {/* Custom Category Creator Modal */}
      {showCustomCreator && (
        <CustomCategoryCreator
          onClose={() => setShowCustomCreator(false)}
          onCreateCategory={handleCreateCategory}
        />
      )}
    </div>
  );
}
