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

export default function ToyMountStep({ config, updateConfig }) {
  const [expandedSubSections, setExpandedSubSections] = useState({});

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

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

  const getSelectedOptionsForSubSection = (subSectionId, subSection) => {
    const allToyMountOptions = config.toyMountOptions || [];
    const subsectionOptionIds = new Set(subSection.options.map(opt => opt.id));
    return allToyMountOptions.filter(opt => subsectionOptionIds.has(opt.id));
  };

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

  const handleOptionClick = (option, subSectionId, subSection) => {
    handleToyMountToggle(option);
  };

  const renderOptionCard = (option, subSectionId, subSection) => {
    const isSelected = isOptionSelected(option, subSectionId, subSection);

    return (
      <button
        key={option.id}
        onClick={() => handleOptionClick(option, subSectionId, subSection)}
        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'
        }`}
      >
        <div className="flex items-start gap-4">
          {option.image && (
            <div className="flex-shrink-0">
              <img
                src={option.image}
                alt={option.name}
                className="h-24 w-24 object-contain rounded-lg bg-gray-100 dark:bg-gray-700"
                onError={(e) => {
                  e.target.style.display = 'none';
                }}
              />
            </div>
          )}
          <div className="flex-1 min-w-0">
            <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">
                  <span className="text-white text-sm font-bold">✓</span>
                </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>
          </div>
        </div>
      </button>
    );
  };

  const renderSubSection = (subSectionId, subSection) => {
    const subSectionKey = `toyMounts.${subSectionId}`;
    const selectedOptions = getSelectedOptionsForSubSection(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 space-y-3 bg-white dark:bg-gray-800">
            {subSection.options.map((option) =>
              renderOptionCard(option, subSectionId, subSection)
            )}
          </div>
        )}
      </div>
    );
  };

  const toyMountsSection = partsData.options?.toyMounts;
  const subSections = toyMountsSection ? Object.entries(toyMountsSection.sections || {}) : [];
  const hasSelection = (config.toyMountOptions || []).length > 0;

  return (
    <div>
      <h2 className="text-2xl font-bold mb-4 text-gray-900 dark:text-white">Select Toy Mounts</h2>
      <p className="text-gray-600 dark:text-gray-300 mb-6">
        Choose your preferred toy mount options. You can select multiple options from different categories.
      </p>

      {subSections.length > 0 && (
        <div className="space-y-4">
          {subSections.map(([subSectionId, subSection]) =>
            renderSubSection(subSectionId, subSection)
          )}
        </div>
      )}

      {!hasSelection && (
        <div className="mt-6 bg-yellow-50 dark:bg-yellow-900/30 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4">
          <p className="text-yellow-800 dark:text-yellow-300 text-sm">
            <strong>Note:</strong> At least one toy mount option is recommended for your build.
          </p>
        </div>
      )}
    </div>
  );
}
