import { MagicWand } from "@phosphor-icons/react";
import { commandIds } from "@commands/ids";
import type { AppStore } from "@editor/store";
import type { MagicWandSettings } from "@editor/tools";
import { BottomControlDivider } from "./Divider";
import { BottomControlSlider } from "./Slider";
import { bottomControlFieldClass, bottomControlIconSlotClass, bottomControlLabelClass, bottomControlMenuClass } from "./styles";

export function MagicWandControls({ settings, dispatch }: { settings: MagicWandSettings; dispatch: AppStore["dispatch"] }) {
  return (
    <div className={bottomControlMenuClass()}>
      <span className={bottomControlIconSlotClass()} title="Magic wand"><MagicWand size={24} /></span>
      <BottomControlDivider />
      <Slider label="Tol" value={settings.tolerance} min={0} max={255} onChange={(tolerance) => dispatch(commandIds.toolSetMagicWandSettings, { tolerance })} />
      <BottomControlDivider />
      <Slider label="Feather" value={settings.feather} min={0} max={20} onChange={(feather) => dispatch(commandIds.toolSetMagicWandSettings, { feather })} />
      <BottomControlDivider />
      <Slider label="Choke" value={settings.choke} min={-20} max={20} onChange={(choke) => dispatch(commandIds.toolSetMagicWandSettings, { choke })} />
      <BottomControlDivider />
      <Slider label="Clean" value={settings.despeckle} min={0} max={20} onChange={(despeckle) => dispatch(commandIds.toolSetMagicWandSettings, { despeckle })} />
      <BottomControlDivider />
      <button type="button" className={`rounded-full px-4 py-2 text-base font-medium transition ${settings.contiguous ? "bg-white text-black" : "bg-white/10 text-white"}`} onClick={() => dispatch(commandIds.toolSetMagicWandSettings, { contiguous: !settings.contiguous })}>Contig</button>
      <BottomControlDivider />
      {(["replace", "add", "subtract"] as const).map((mode) => (
        <button key={mode} type="button" className={`rounded-full px-4 py-2 text-base font-medium capitalize transition ${settings.mode === mode ? "bg-white text-black" : "bg-white/10 text-white"}`} onClick={() => dispatch(commandIds.toolSetMagicWandSettings, { mode })}>{mode === "subtract" ? "Sub" : mode}</button>
      ))}
      <span className="px-2 text-sm text-white/60">Shift-click adds, Alt-click subtracts</span>
    </div>
  );
}

function Slider({ label, value, min, max, onChange }: { label: string; value: number; min: number; max: number; onChange: (value: number) => void }) {
  return <label className={bottomControlFieldClass()}><span className={bottomControlLabelClass()}>{label}</span><BottomControlSlider min={min} max={max} value={value} className="w-32" aria-label={`Magic wand ${label}`} onValueChange={onChange} /><span className="w-8 text-right text-base text-white">{Math.round(value)}</span></label>;
}
