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

export default function RemoteStep({ config, updateConfig, buildType }) {
  const [expandedKnobs, setExpandedKnobs] = useState(false);

  const availableRemotes = [
    {
      id: 'ossm-remote-standard',
      name: 'OSSM - Remote',
      description: 'Standard OSSM remote (can be purchased from RAD or self-sourced with PCB Way)',
      radrOnly: false,
    },
    {
      id: 'ossm-remote-radr',
      name: 'OSSM - RADR',
      description: 'RADR remote system (RAD only)',
      radrOnly: true,
    },
  ];

  // Show all available remotes for both build types
  const getAvailableRemotes = () => {
    return availableRemotes;
  };

  const selectedRemoteId = config.remoteType || config.remote?.id;
  const selectedRemotePCB = config.remotePCB || null;

  const handleRemoteSelect = (remoteId) => {
    // Consolidate all updates into a single call to prevent state issues
    const updates = {
      remoteType: remoteId,
    };
    
    // Reset PCB selection when switching remotes
    if (remoteId === 'ossm-remote-radr') {
      // RADR only available from RAD
      updates.remotePCB = 'rad';
    } else {
      updates.remotePCB = null;
    }
    
    // Clear knob selection when switching remotes
    updates.remoteKnob = null;
    
    updateConfig(updates);
  };

  const handlePCBSelect = (source) => {
    updateConfig({ remotePCB: source });
  };

  const handleKnobSelect = (knob) => {
    updateConfig({ remoteKnob: knob });
  };

  const getSelectedRemoteSystem = () => {
    if (!selectedRemoteId) return null;
    return partsData.components?.remotes?.systems?.[selectedRemoteId] || null;
  };

  const getAvailableKnobs = () => {
    const remoteSystem = getSelectedRemoteSystem();
    if (!remoteSystem || !remoteSystem.knobs) return [];
    
    return remoteSystem.knobs.map((knob) => ({
      id: knob.id,
      name: knob.name,
      description: knob.description,
      filamentEstimate: knob.filamentEstimate !== undefined ? `~${knob.filamentEstimate}g` : "0g",
      timeEstimate: knob.timeEstimate,
      colour: knob.colour,
    }));
  };

  const isKnobSelected = (knobId) => {
    return config.remoteKnob?.id === knobId;
  };

  const renderRemoteCard = (remote) => {
    const isSelected = selectedRemoteId === remote.id;
    const remoteSystem = partsData.components?.remotes?.systems?.[remote.id];
    const imagePath = remoteSystem?.image ? `${remoteSystem.image}` : null;

    return (
      <button
        key={remote.id}
        onClick={() => handleRemoteSelect(remote.id)}
        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'
        }`}
      >
        {imagePath && (
          <div className="mb-3 flex justify-center">
            <img
              src={imagePath}
              alt={remote.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">
              {remote.name}
            </h4>
            <p className="text-sm text-gray-600 dark:text-gray-300">{remote.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">
              <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>
      </button>
    );
  };

  const renderPCBSelection = () => {
    if (!selectedRemoteId || selectedRemoteId === 'ossm-remote-radr') {
      // RADR only available from RAD, so no selection needed
      return null;
    }

    return (
      <div className="mt-4 mb-6">
        <h3 className="text-lg font-semibold mb-3 text-gray-900 dark:text-white">PCB Purchase Source</h3>
        <div className="flex gap-4">
          <button
            onClick={() => handlePCBSelect('rad')}
            className={`px-4 py-2 border-2 rounded-lg transition-all ${
              selectedRemotePCB === 'rad'
                ? 'border-blue-600 dark:border-blue-500 bg-blue-50 dark:bg-blue-900/30 text-blue-900 dark:text-blue-300 font-medium'
                : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
            }`}
          >
            Purchase from RAD
          </button>
          <button
            onClick={() => handlePCBSelect('pcbway')}
            className={`px-4 py-2 border-2 rounded-lg transition-all ${
              selectedRemotePCB === 'pcbway'
                ? 'border-blue-600 dark:border-blue-500 bg-blue-50 dark:bg-blue-900/30 text-blue-900 dark:text-blue-300 font-medium'
                : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
            }`}
          >
            Self-source with PCBWay
          </button>
        </div>
      </div>
    );
  };

  const renderKnobCard = (knob) => {
    const isSelected = isKnobSelected(knob.id);

    return (
      <button
        key={knob.id}
        onClick={() => handleKnobSelect(knob)}
        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 justify-between mb-2">
          <div className="flex-1">
            <h4 className="font-semibold text-gray-900 dark:text-white mb-1">
              {knob.name}
            </h4>
            {knob.description && (
              <p className="text-sm text-gray-600 dark:text-gray-300">{knob.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">
              <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">
          {knob.filamentEstimate && (
            <div>
              <span className="text-gray-500 dark:text-gray-400">Filament:</span>{' '}
              <span className="font-medium text-gray-900 dark:text-white">{knob.filamentEstimate}</span>
            </div>
          )}
        </div>
      </button>
    );
  };

  const availableRemotesFiltered = getAvailableRemotes();
  const availableKnobs = getAvailableKnobs();
  const hasRemoteSelected = !!selectedRemoteId;
  const hasKnobSelected = !!config.remoteKnob;

  // Auto-expand knobs section when remote is selected
  useEffect(() => {
    if (hasRemoteSelected && availableKnobs.length > 0) {
      setExpandedKnobs(true);
    }
  }, [hasRemoteSelected, availableKnobs.length]);

  return (
    <div>
      <h2 className="text-2xl font-bold mb-4 text-gray-900 dark:text-white">Select Remote Control</h2>
      <p className="text-gray-600 dark:text-gray-300 mb-6">
        Choose your remote control system and knob option.
      </p>

      {/* Remote Selection */}
      <div className="mb-6">
        <h3 className="text-lg font-semibold mb-3">Remote System</h3>
        <div className="grid grid-cols-2 gap-4">
          {availableRemotesFiltered.map((remote) => renderRemoteCard(remote))}
        </div>
      </div>

      {/* PCB Purchase Source (only for OSSM - Remote) */}
      {hasRemoteSelected && renderPCBSelection()}

      {/* Knobs Selection (only shown when remote is selected) */}
      {hasRemoteSelected && availableKnobs.length > 0 && (
        <div className="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
          <button
            onClick={() => setExpandedKnobs(!expandedKnobs)}
            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">
              <h3 className="text-lg font-semibold text-gray-800 dark:text-gray-200">Remote Knobs</h3>
              {hasKnobSelected && (
                <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">
                    {config.remoteKnob?.name}
                  </span>
                </div>
              )}
            </div>
            <svg
              className={`w-4 h-4 text-gray-500 dark:text-gray-400 transition-transform ${
                expandedKnobs ? '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>
          {expandedKnobs && (
            <div className="p-4 bg-white dark:bg-gray-800">
              <div className="grid grid-cols-2 lg:grid-cols-3 gap-4">
                {availableKnobs.map((knob) => renderKnobCard(knob))}
              </div>
            </div>
          )}
        </div>
      )}

      {!hasRemoteSelected && (
        <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> Please select a remote control system to continue.
          </p>
        </div>
      )}
    </div>
  );
}
