import { useState, useEffect } from 'react';
import MainPage from './components/MainPage';
import Wizard from './components/Wizard';
import ThemeToggle from './components/ThemeToggle';
import partsData from './data/index.js';
import { getSharedConfig } from './utils/shareService';

function App() {
  const [buildType, setBuildType] = useState(null);
  const [config, setConfig] = useState({
    motor: null,
    powerSupply: null,
    primaryColor: 'black',
    accentColor: 'black',
    mount: null,
    cover: null,
    standHinge: null,
    standFeet: null,
    standCrossbarSupports: [],
    toyMountOptions: [],
    toyMounts: [],
    actuatorMount: null,
    standParts: [],
    pcbMount: null,
  });

  // Check for share link on load
  useEffect(() => {
    const urlParams = new URLSearchParams(window.location.search);
    const shareId = urlParams.get('share');
    const isSession = urlParams.get('session') === 'true';
    
    if (shareId) {
      const sharedConfig = getSharedConfig(shareId, isSession);
      if (sharedConfig) {
        setConfig(sharedConfig);
        setBuildType('self-source'); // Default build type for shared configs
        // Clean up the URL
        window.history.replaceState({}, document.title, window.location.pathname);
      } else {
        alert('This share link has expired or is invalid. Share links are valid for 7 days.');
      }
    }
  }, []);

  const handleSelectBuildType = (type) => {
    if (type === 'rad-kit') {
      // Pre-select RAD kit parts
      const radKitConfig = getRADKitConfig();
      setConfig(radKitConfig);
      setBuildType('rad-kit');
    } else {
      setBuildType(type);
    }
  };

  const getRADKitConfig = () => {
    // Standard RAD kit configuration
    // Assuming the kit includes:
    // - 57AIM30 motor (recommended)
    // - 24V 5A PSU
    // - Standard mount (middle-pivot or pitclamp - using middle-pivot as default)
    // - Standard colors (black/black)
    // - Basic stand components
    // - Default toy mount options (flange mount base)
    
    const motor = partsData.motors.find(m => m.id === '57AIM30') || partsData.motors[0];
    const powerSupply = partsData.powerSupplies.find(ps => ps.id === 'psu-24v-5a') || partsData.powerSupplies[0];
    
    // Get mount from options data to ensure proper structure
    const mountOptions = partsData.options?.actuator?.sections?.mounts?.options || [];
    const mount = mountOptions.find(m => m.id === 'middle-pivot') || mountOptions[0] || null;

    // Get stand hinge (default: pivot-plate)
    const hingeOptions = partsData.options?.stand?.sections?.hinges?.options || [];
    const standHinge = hingeOptions.find(h => h.id === 'pivot-plate') || hingeOptions[0] || null;

    // Get stand feet (default: standard-feet)
    const feetOptions = partsData.options?.stand?.sections?.feet?.options || [];
    const standFeet = feetOptions.find(f => f.id === 'standard-feet') || feetOptions[0] || null;

    // Get stand crossbar supports (default: standard-90-degree-support)
    const crossbarSupportOptions = partsData.options?.stand?.sections?.crossbarSupports?.options || [];
    const standCrossbarSupports = [];
    const standardSupport = crossbarSupportOptions.find(s => s.id === 'standard-90-degree-support') || crossbarSupportOptions[0];
    if (standardSupport) {
      standCrossbarSupports.push(standardSupport);
    }

    // Get default toy mount options (flange mount base - first option)
    const toyMountOptions = [];
    const flangeMountOptions = partsData.options?.toyMounts?.sections?.flangeMount?.options || [];
    if (flangeMountOptions.length > 0) {
      // Select the first option (flange-base-24mm-threaded)
      toyMountOptions.push(flangeMountOptions[0]);
    }

    // Get cover (default: standard-cover)
    const coverOptions = partsData.options?.actuator?.sections?.cover?.options || [];
    const cover = coverOptions.find(c => c.id === 'standard-cover') || coverOptions[0] || null;

    // Get PCB mount (default: 3030-mount)
    const pcbMountOptions = partsData.options?.actuator?.sections?.pcbMount?.options || [];
    const pcbMount = pcbMountOptions.find(p => p.id === '3030-mount') || pcbMountOptions[0] || null;

    return {
      motor,
      powerSupply,
      primaryColor: 'black',
      accentColor: 'black',
      mount,
      cover,
      standHinge,
      standFeet,
      standCrossbarSupports,
      toyMountOptions,
      toyMounts: [],
      actuatorMount: null,
      standParts: [],
      pcbMount,
    };
  };

  const updateConfig = (updates) => {
    setConfig((prev) => ({ ...prev, ...updates }));
  };

  const handleBackToMain = () => {
    setBuildType(null);
    setConfig({
      motor: null,
      powerSupply: null,
      primaryColor: 'black',
      accentColor: 'black',
      mount: null,
      cover: null,
      standHinge: null,
      standFeet: null,
      standCrossbarSupports: [],
      toyMountOptions: [],
      toyMounts: [],
      actuatorMount: null,
      standParts: [],
      pcbMount: null,
    });
  };

  if (!buildType) {
    return (
      <>
        <ThemeToggle />
        <MainPage onSelectBuildType={handleSelectBuildType} />
      </>
    );
  }

  return (
    <>
      <ThemeToggle />
      <Wizard
        buildType={buildType}
        initialConfig={config}
        updateConfig={updateConfig}
        onBackToMain={handleBackToMain}
      />
    </>
  );
}

export default App;
