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

interface Props {
  index: number
}

export const GroupBox: FC<Props> = ({ index }) => {
  const details = useDetails()
  const {
    getGroup,
    doNotSuggest,
    setFactories,
    ignoredFactories,
    setIgnoredFactories,
    renameGroup,
    removeGroup,
    getInputType
  } = useGroups()
  const {
    name,
    inputs,
    intermediates,
    exports,
    malls
  } = getGroup(index)

  const calculatedInputs = useMemo<string[]>(() => {
    const allProducingFactories = [...intermediates, ...exports, ...malls]
    const newData: string[] = details
      .filter(detail => allProducingFactories.includes(detail.href))
      .flatMap(detail => Object.keys(detail.recipe?.prerequisites ?? {}))
    const uniqueInputs = Array.from(new Set(newData))
    return uniqueInputs
      .filter(input => !allProducingFactories.includes(input))
  }, [details, intermediates, exports, malls])

  const suggestions = useMemo<Entity[]>(() => {
    const selectedValues = Array.from(new Set([...inputs, ...intermediates, ...exports, ...malls]))
    const availableIngredients = Array.from(new Set([...selectedValues, ...calculatedInputs]))
    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))
      })
  }, [doNotSuggest, details, calculatedInputs, inputs, intermediates, exports, malls])

  const addFactory = (uid: string, type: Parameters<typeof setFactories>[2]) => {
    setFactories(index, [...intermediates, uid], 'intermediates')
  }

  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()
          renameGroup(index, event.currentTarget.innerText);
        }}
      >
        {name}
      </h3>
      <button onClick={() => removeGroup(index)} style={{display: 'block'}}>X</button>
      <label>Additional Inputs</label>
      <FactorySelect
        factories={inputs}
        onSetFactories={factories => setFactories(index, factories, 'inputs')}
      />
      <label>Intermediate Factories</label>
      <FactorySelect
        factories={intermediates}
        onSetFactories={factories => setFactories(index, factories, 'intermediates')}
      />
      <label>Exported Factories</label>
      <FactorySelect
        factories={exports}
        onSetFactories={factories => setFactories(index, factories, 'exports')}
      />
      <label>Mall Factories</label>
      <FactorySelect
        factories={malls}
        onSetFactories={factories => setFactories(index, factories, 'malls')}
      />
      <div className={styles.grid}>
        <div>
          <h4>Inputs</h4>
          <ul>
            {
              calculatedInputs.map(input => <li key={input}><EntitySpan
                value={input}
                onClick={() => addFactory(input, 'intermediates')}
                style={{color: {base: 'darkgreen', produced: 'orange', unknown: undefined}[getInputType(input)]}}
                leftClickText={"Add to intermediate factories"}
              /></li>)
            }
          </ul>
        </div>
        <div>
          <h4>Suggestions</h4>
          <ul>
            {suggestions.map(suggestion => <li key={suggestion.href}>
              <EntitySpan
                value={suggestion}
                onClick={() => addFactory(suggestion.href, 'exports')}
                onContextMenu={event => {
                  event.preventDefault()
                  setIgnoredFactories([...ignoredFactories, suggestion.href])
                }}
                leftClickText={"Add to exported factories"}
                rightClickText={"Exclude this recipe from suggestions"}
              />
            </li>)}
          </ul>
        </div>
      </div>
    </div>
  </div>
}
