import { useState, useEffect } from 'react';
import partsData from '../../data/index.js';
import { formatPrice } from '../../utils/priceFormat';

export default function OptionsStep({ config, updateConfig, buildType }) {
  const [expandedMainSections, setExpandedMainSections] = useState({});
  const [expandedSubSections, setExpandedSubSections] = useState({});

  const handleMountSelect = (option) => {
    updateConfig({ mount: option });
    setExpandedSubSections((prev) => ({ ...prev, 'actuator.mounts': false }));
  };

  const handleCoverSelect = (option) => {
    updateConfig({ cover: option });
    setExpandedSubSections((prev) => ({ ...prev, 'actuator.cover': false }));
  };

  const handlePcbMountSelect = (option) => {
    updateConfig({ pcbMount: option });
    setExpandedSubSections((prev) => ({ ...prev, 'actuator.pcbMount': false }));
  };

  const handleStandHingeSelect = (option) => {
    updateConfig({ standHinge: option });
    setExpandedSubSections((prev) => ({ ...prev, 'stand.hinges': false }));
  };

  const handleStandFeetSelect = (option) => {
    updateConfig({ standFeet: option });
    setExpandedSubSections((prev) => ({ ...prev, 'stand.feet': false }));
  };

  const handleStandCrossbarSupportToggle = (option) => {
    const currentSupports = config.standCrossbarSupports || [];
    const isSelected = currentSupports.some((opt) => opt.id === option.id);
    
    if (isSelected) {
      updateConfig({
        standCrossbarSupports: currentSupports.filter((opt) => opt.id !== option.id),
      });
    } else {
      updateConfig({
        standCrossbarSupports: [...currentSupports, option],
      });
    }
  };

  const toggleMainSection = (mainSectionId) => {
    setExpandedMainSections((prev) => ({
      ...prev,
      [mainSectionId]: !prev[mainSectionId],
    }));
  };

  const toggleSubSection = (subSectionKey) => {
    setExpandedSubSections((prev) => ({
      ...prev,
      [subSectionKey]: !prev[subSectionKey],
    }));
  };

  const getSelectedOptionsForSubSection = (mainSectionId, subSectionId, subSection = null) => {
    const key = `${mainSectionId}.${subSectionId}`;
    
    switch (key) {
      case 'actuator.mounts':
        return config.mount ? [config.mount] : [];
      case 'actuator.cover':
        return config.cover ? [config.cover] : [];
      case 'actuator.pcbMount':
        return config.pcbMount ? [config.pcbMount] : [];
      case 'stand.hinges':
        return config.standHinge ? [config.standHinge] : [];
      case 'stand.feet':
        return config.standFeet ? [config.standFeet] : [];
      case 'stand.crossbarSupports':
        return config.standCrossbarSupports || [];
      default:
        return [];
    }
  };

  const isOptionSelected = (option, mainSectionId, subSectionId, subSection = null) => {
    const selected = getSelectedOptionsForSubSection(mainSectionId, subSectionId, subSection);
    return selected.some((opt) => opt.id === option.id);
  };

  const isMainSectionComplete = (mainSectionId, mainSection) => {
    const subSections = Object.entries(mainSection.sections || {});
    
    // Check if all sub-sections with options are complete
    for (const [subSectionId, subSection] of subSections) {
      // Skip if no options available
      if (!subSection.options || subSection.options.length === 0) {
        continue;
      }
      
      const selectedOptions = getSelectedOptionsForSubSection(mainSectionId, subSectionId, subSection);
      
      // All sub-sections (both single-select and multi-select) require at least one selection
      // Multi-select means you can select multiple items, but you still need at least one
      if (selectedOptions.length === 0) {
        return false;
      }
    }
    
    return true;
  };

  // Auto-collapse main sections when they become complete
  useEffect(() => {
    const mainSections = partsData.options ? Object.entries(partsData.options) : [];
    
    mainSections.forEach(([mainSectionId, mainSection]) => {
      // Skip toyMounts and remoteControl sections (now in their own steps)
      if (mainSectionId === 'toyMounts' || mainSectionId === 'remoteControl') {
        return;
      }
      
      if (isMainSectionComplete(mainSectionId, mainSection)) {
        setExpandedMainSections((prev) => {
          // Only auto-collapse if the section is currently expanded (undefined or true)
          // Don't override if user has explicitly collapsed it (false)
          const currentlyExpanded = prev[mainSectionId] !== false;
          if (currentlyExpanded) {
            return { ...prev, [mainSectionId]: false };
          }
          return prev;
        });
      }
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [config.mount, config.cover, config.pcbMount, config.standHinge, config.standFeet, config.standCrossbarSupports]);

  const handleOptionClick = (option, mainSectionId, subSectionId) => {
    const key = `${mainSectionId}.${subSectionId}`;
    
    switch (key) {
      case 'actuator.mounts':
        handleMountSelect(option);
        break;
      case 'actuator.cover':
        handleCoverSelect(option);
        break;
      case 'actuator.pcbMount':
        handlePcbMountSelect(option);
        break;
      case 'stand.hinges':
        handleStandHingeSelect(option);
        break;
      case 'stand.feet':
        handleStandFeetSelect(option);
        break;
      case 'stand.crossbarSupports':
        handleStandCrossbarSupportToggle(option);
        break;
      default:
        break;
    }
  };

  const renderOptionCard = (option, mainSectionId, subSectionId, subSection = null, isMultiSelect = false) => {
    const isSelected = isOptionSelected(option, mainSectionId, subSectionId, subSection);

    return (
      <button
        key={option.id}
        onClick={() => handleOptionClick(option, mainSectionId, subSectionId)}
        className={`p-4 border-2 rounded-lg text-left transition-all w-full ${
          isSelected
            ? 'border-blue-600 dark:border-blue-500 bg-blue-50 dark:bg-blue-900/30'
            : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700/50'
        }`}
      >
        {option.image && (
          <div className="mb-3 flex justify-center">
            <img
              src={option.image}
              alt={option.name}
              className="h-48 w-48 object-contain rounded-lg bg-gray-100 dark:bg-gray-700"
              onError={(e) => {
                e.target.style.display = 'none';
              }}
            />
          </div>
        )}
        <div className="flex items-start justify-between mb-2">
          <div className="flex-1">
            <h4 className="font-semibold text-gray-900 dark:text-white mb-1">
              {option.name}
            </h4>
            {option.description && (
              <p className="text-sm text-gray-600 dark:text-gray-300">{option.description}</p>
            )}
          </div>
          {isSelected && (
            <div className="w-6 h-6 bg-blue-600 dark:bg-blue-500 rounded-full flex items-center justify-center flex-shrink-0 ml-2">
              {isMultiSelect ? (
                <span className="text-white text-sm font-bold">✓</span>
              ) : (
                <svg
                  className="w-4 h-4 text-white"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M5 13l4 4L19 7"
                  />
                </svg>
              )}
            </div>
          )}
        </div>
        <div className="flex flex-wrap gap-4 text-sm mt-3">
          {option.filamentEstimate && (
            <div>
              <span className="text-gray-500 dark:text-gray-400">Filament:</span>{' '}
              <span className="font-medium text-gray-900 dark:text-white">{option.filamentEstimate}</span>
            </div>
          )}
          {option.hardwareCost !== undefined && (
            <div>
              <span className="text-gray-500 dark:text-gray-400">Hardware:</span>{' '}
              <span className="font-medium text-gray-900 dark:text-white">
                {formatPrice(option.hardwareCost)}
              </span>
            </div>
          )}
        </div>
      </button>
    );
  };

  const renderSubSection = (mainSectionId, subSectionId, subSection) => {
    const subSectionKey = `${mainSectionId}.${subSectionId}`;
    const selectedOptions = getSelectedOptionsForSubSection(mainSectionId, subSectionId, subSection);
    const hasSelection = selectedOptions.length > 0;
    const isExpanded = expandedSubSections[subSectionKey] !== false && (!hasSelection || expandedSubSections[subSectionKey] === true);

    return (
      <div key={subSectionId} className="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
        <button
          onClick={() => toggleSubSection(subSectionKey)}
          className="w-full px-4 py-3 bg-gray-50 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors flex items-center justify-between"
        >
          <div className="flex items-center gap-3">
            <h4 className="font-semibold text-gray-800 dark:text-gray-200">{subSection.title}</h4>
            {hasSelection && (
              <div className="flex items-center gap-2">
                <div className="w-4 h-4 bg-green-500 dark:bg-green-600 rounded-full flex items-center justify-center">
                  <svg
                    className="w-2.5 h-2.5 text-white"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={3}
                      d="M5 13l4 4L19 7"
                    />
                  </svg>
                </div>
                <span className="text-sm text-gray-600 dark:text-gray-300">
                  {selectedOptions.map((opt) => opt.name).join(', ')}
                </span>
              </div>
            )}
          </div>
          <svg
            className={`w-4 h-4 text-gray-500 dark:text-gray-400 transition-transform ${
              isExpanded ? 'transform rotate-180' : ''
            }`}
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M19 9l-7 7-7-7"
            />
          </svg>
        </button>
        {isExpanded && subSection.options && subSection.options.length > 0 && (
          <div className="p-4 bg-white dark:bg-gray-800">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {subSection.options.map((option) =>
                renderOptionCard(option, mainSectionId, subSectionId, subSection, subSection.isMultiSelect)
              )}
            </div>
          </div>
        )}
      </div>
    );
  };

  const renderMainSection = (mainSectionId, mainSection) => {
    const isExpanded = expandedMainSections[mainSectionId] !== false;
    const subSections = Object.entries(mainSection.sections || {});
    const isComplete = isMainSectionComplete(mainSectionId, mainSection);

    return (
      <div key={mainSectionId} className={`border-2 rounded-lg overflow-hidden mb-4 ${
        isComplete ? 'border-green-500 dark:border-green-600' : 'border-gray-300 dark:border-gray-700'
      }`}>
        <button
          onClick={() => toggleMainSection(mainSectionId)}
          className={`w-full px-6 py-4 transition-colors flex items-center justify-between ${
            isComplete 
              ? 'bg-green-50 dark:bg-green-900/30 hover:bg-green-100 dark:hover:bg-green-900/40' 
              : 'bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700'
          }`}
        >
          <div className="flex items-center gap-3">
            <h3 className={`text-xl font-bold ${
              isComplete ? 'text-green-900 dark:text-green-300' : 'text-gray-900 dark:text-white'
            }`}>
              {mainSection.title}
            </h3>
            {isComplete && (
              <div className="flex items-center gap-2">
                <div className="w-6 h-6 bg-green-500 dark:bg-green-600 rounded-full flex items-center justify-center">
                  <svg
                    className="w-4 h-4 text-white"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={3}
                      d="M5 13l4 4L19 7"
                    />
                  </svg>
                </div>
                <span className="text-sm font-medium text-green-700 dark:text-green-300">Complete</span>
              </div>
            )}
          </div>
          <svg
            className={`w-6 h-6 transition-transform ${
              isExpanded ? 'transform rotate-180' : ''
            } ${isComplete ? 'text-green-600 dark:text-green-400' : 'text-gray-600 dark:text-gray-400'}`}
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M19 9l-7 7-7-7"
            />
          </svg>
        </button>
        {isExpanded && (
          <div className="p-4 space-y-4 bg-white dark:bg-gray-800">
            {subSections.map(([subSectionId, subSection]) =>
              renderSubSection(mainSectionId, subSectionId, subSection)
            )}
          </div>
        )}
      </div>
    );
  };

  const mainSections = partsData.options ? Object.entries(partsData.options) : [];

  // Filter sections and options for upgrade mode
  const getFilteredSections = () => {
    if (buildType !== 'upgrade') {
      return mainSections;
    }

    // In upgrade mode, only show sections with mod components
    return mainSections
      .map(([mainSectionId, mainSection]) => {
        // Filter sub-sections to only show those with mod options
        const filteredSubSections = {};
        Object.entries(mainSection.sections || {}).forEach(([subSectionId, subSection]) => {
          // Check if this sub-section has mod options
          const hasModOptions = subSection.options?.some(opt => opt.type === 'mod') || 
                               subSection.componentType === 'mod';
          
          if (hasModOptions) {
            // Filter options to only show mods
            const modOptions = subSection.options?.filter(opt => opt.type === 'mod') || [];
            if (modOptions.length > 0 || subSection.componentType === 'mod') {
              filteredSubSections[subSectionId] = {
                ...subSection,
                options: modOptions.length > 0 ? modOptions : subSection.options,
              };
            }
          }
        });

        // Only include main section if it has any filtered sub-sections
        if (Object.keys(filteredSubSections).length > 0) {
          return [mainSectionId, { ...mainSection, sections: filteredSubSections }];
        }
        return null;
      })
      .filter(Boolean);
  };

  const filteredSections = getFilteredSections();

  // Filter out toyMounts and remoteControl sections (now in their own steps)
  const sectionsToRender = filteredSections.filter(([mainSectionId]) => mainSectionId !== 'toyMounts' && mainSectionId !== 'remoteControl');

  return (
    <div>
      <h2 className="text-2xl font-bold mb-4 text-gray-900 dark:text-white">
        {buildType === 'upgrade' ? 'Select Upgrades & Modifications' : 'Select Options'}
      </h2>
      <p className="text-gray-600 dark:text-gray-300 mb-6">
        {buildType === 'upgrade' 
          ? 'Choose upgrade components and modifications for your existing build.'
          : 'Choose your preferred mounting options and accessories.'}
      </p>

      {sectionsToRender.length === 0 && buildType === 'upgrade' && (
        <div className="bg-yellow-50 dark:bg-yellow-900/30 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4 mb-6">
          <p className="text-yellow-800 dark:text-yellow-300">
            No upgrade components available. All components are base modules.
          </p>
        </div>
      )}

      <div className="space-y-4">
        {sectionsToRender.map(([mainSectionId, mainSection]) =>
          renderMainSection(mainSectionId, mainSection)
        )}
      </div>
    </div>
  );
}
