import React, { useState, useEffect } from 'react';

// Define the available model options
const modelDropdown = {
  offlineWithoutFoss: ['Offline Fast', 'Offline Slow'],
  offlineFoss: ['Offline Fast (FOSS)', 'Offline Slow (FOSS)'],
  onlineWithoutFoss: [
    'Online Cheap (OpenAI)',
    'Online Expensive (OpenAI)',
    'Online Cheap (Anthropic)',
    'Online Expensive (Anthropic)',
    'Online Cheap (Google)',
    'Online Expensive (Google)',
  ],
  onlineFoss: ['Online (FOSS) (La Plateforme)'],
};

const Models: React.FC = () => {
  // Initialize state with value from localStorage or default to ''
  const [selectedModel, setSelectedModel] = useState('');
  const radioSelection = localStorage.getItem('radioSelection')

  useEffect(() => {
    const handleStorageChange = () => {
      setSelectedModel(localStorage.getItem('selectedModel') || '');
    };
    handleStorageChange();

    // Update dropdown immediately when localStorage changes internally or externally
    window.addEventListener('storage', handleStorageChange);

    // Cleanup listener on component unmount
    return () => {
      window.removeEventListener('storage', handleStorageChange);
    };
  }, []);

  const handleModelChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    const newModel = event.target.value;
    setSelectedModel(newModel);
    localStorage.setItem('radioSelection', newModel); // Update localStorage directly
  };

  // Determine the filtered models based on current radioSelection
  const filteredModels = (() => {
    let models = [];
    switch (radioSelection) {
      case 'Offline':
        models = [
          ...modelDropdown.onlineWithoutFoss,
          ...modelDropdown.onlineFoss,
        ]; // Show only offline models without FOSS
        break;
      case 'Offline (FOSS)':
        models = [
          ...modelDropdown.onlineFoss,
        ]; // Show only offline models with FOSS
        break;
      case 'Online':
        models = [
          ...modelDropdown.offlineWithoutFoss,
          ...modelDropdown.offlineFoss,
        ]; // Show only online models without FOSS
        break;
      case 'Online (FOSS)':
        models = [
          ...modelDropdown.offlineFoss,
        ]; // Show only online models with FOSS
        break;
      case 'None':
        models = [
          ...modelDropdown.offlineWithoutFoss,
          ...modelDropdown.offlineFoss,
          ...modelDropdown.onlineWithoutFoss,
          ...modelDropdown.onlineFoss,
        ]; // Show all models if nothing matches
        break;
      case 'None (FOSS)':
        models = [
          ...modelDropdown.offlineFoss,
          ...modelDropdown.onlineFoss,
        ]; // Show all models if nothing matches
        break;
      default:
        models = [
          ...modelDropdown.offlineWithoutFoss,
          ...modelDropdown.offlineFoss,
          ...modelDropdown.onlineWithoutFoss,
          ...modelDropdown.onlineFoss,
        ]; // Show all models if nothing matches
        break;
    }
    return Array.from(new Set(models)); // Remove duplicates using Set
  })();

  const isOfflineModel = (model: string) =>
    modelDropdown.offlineWithoutFoss.includes(model) || modelDropdown.offlineFoss.includes(model);

  return (
    <div className="model-background">
      <div className="models">
        <div className="title">
          <h3>Different AI Models</h3>
        </div>

        {/* Model Selection Dropdown */}
        <div className="model-dropdown">
          <label htmlFor="model-select">Select AI Model:</label>
          <select id="model-select" value={selectedModel} onChange={handleModelChange}>
            {filteredModels.map((model) => (
              <option key={model} value={model}>
                {model}
              </option>
            ))}
          </select>
        </div>


        {/* Model Grid with Cards */}
        <div className="grid">
          {['Code', 'Math', 'Language', 'Character', 'Finance', 'Weather', 'Time', 'Image', 'Custom1', 'Custom2'].map(
            (category) => (
              <button key={category} className={`${category.toLowerCase()}-model model-box`}>
                <div className="overlay">
                  <h3>{category}</h3>
                  {isOfflineModel(selectedModel) && <img src="/img/nowifi.svg" alt="No Wi-Fi" />}
                </div>
              </button>
            )
          )}
        </div>
      </div>
    </div>
  );
};

export default Models;
