import {FC, useMemo} from "react";
import {FactorySelect} from "./FactorySelect";
import {useDetails} from "../src/hooks/useDetails";
import {Entity} from "../src/types";
import styles from "./Group.module.css"

interface Props {
  onRemove: () => void
  onSetOutputFactories: (uids: string[]) => void
  outputFactories: string[]
  onSetIntermediateFactories: (uids: string[]) => void
  intermediateFactories: string[]
  onSetInputFactories: (uids: string[]) => void
  inputFactories: string[]
  onToggleExported: () => void
  isExported: boolean
  onRename: (name: string) => void
  onDoIgnore: (name: string) => void
  name: string
  sets: {
    doNotSuggest: Set<string>
    basic: Set<string>
    exported: Set<string>
  }
}

export const Group: FC<Props> = ({
  onRemove,
  onRename,
  onSetOutputFactories,
  outputFactories,
  onSetIntermediateFactories,
  intermediateFactories,
  onSetInputFactories,
  inputFactories,
  onToggleExported,
  isExported,
  name,
  sets: {
    doNotSuggest,
    basic,
    exported
  },
  onDoIgnore
}) => {
  const details = useDetails()

  const inputs = useMemo<string[]>(() => {
    const newData: string[] = details
      .filter(detail => intermediateFactories.includes(detail.href) || outputFactories.includes(detail.href))
      .flatMap(detail => Object.keys(detail.recipe?.prerequisites ?? {}))
    const uniqueInputs = Array.from(new Set(newData))
    return uniqueInputs
      .filter(input => !intermediateFactories.includes(input) && !outputFactories.includes(input))
  }, [details, intermediateFactories, outputFactories])

  const suggestions = useMemo<Entity[]>(() => {
    const availableIngredients = Array.from(new Set([...intermediateFactories, ...outputFactories, ...inputs, ...inputFactories]))
    const selectedValues = Array.from(new Set([...intermediateFactories, ...outputFactories, ...inputFactories]))
    return details
      .filter(detail => {
        if (!detail.recipe) return false
        if (selectedValues.includes(detail.href)) return false
        if (doNotSuggest.has(detail.href)) return false
        const prerequisites = Object.keys(detail.recipe?.prerequisites ?? {})
        return prerequisites.every(pre => availableIngredients.includes(pre))
      })
  }, [inputFactories, doNotSuggest, details, inputs, intermediateFactories, outputFactories])

  const addIntermediateFactory = (uid: string) => {
    onSetIntermediateFactories([...intermediateFactories, uid])
  }

  const addOutputFactory = (uid: string) => {
    onSetOutputFactories([...outputFactories, uid])
  }

  return <div style={{border: "2px solid black", padding: "0.5em", margin: "1em"}}>
    <div>
      <h3
        contentEditable={true}
        suppressContentEditableWarning={true}
        onBlur={event => {
          event.currentTarget.innerText = event.currentTarget.innerText.trim()
          onRename(event.currentTarget.innerText);
        }}
      >
        {name}
      </h3>
      <button onClick={onRemove} style={{display: 'block'}}>X</button>
      <input type={"checkbox"} onChange={onToggleExported} checked={isExported} style={{display: 'block'}}/>
      <label>Additional Inputs</label>
      <FactorySelect
        factories={inputFactories}
        onSetFactories={onSetInputFactories}
      />
      <label>Intermediate Factories</label>
      <FactorySelect
        factories={intermediateFactories}
        onSetFactories={onSetIntermediateFactories}
      />
      <label>Output Factories</label>
      <FactorySelect
        factories={outputFactories}
        onSetFactories={onSetOutputFactories}
      />
      <div className={styles.grid}>
        <div>
          <h4>Inputs</h4>
          <ul>
            {
              inputs.map(input => <li key={input}><a
                href={'javascript:void(0)'}
                onClick={() => addIntermediateFactory(input)}
                style={{color: basic.has(input) ? 'darkgreen' : exported.has(input) ? 'orange' : undefined}}
              >
                {input}
              </a></li>)
            }
          </ul>
        </div>
        <div>
          <h4>Suggestions</h4>
          <ul>
            {suggestions.map(suggestion => <li key={suggestion.href}>
              <a
                href={'javascript:void(0)'}
                onClick={() => addOutputFactory(suggestion.href)}
                onContextMenu={event => {
                  event.preventDefault()
                  onDoIgnore(suggestion.href)
                }}
                style={{color: basic.has(suggestion.href) ? 'darkgreen' : exported.has(suggestion.href) ? 'orange' : undefined}}
              >
                {suggestion.name}
              </a>
            </li>)}
          </ul>
        </div>
      </div>
    </div>
  </div>
}
