import Wheel from "@uiw/react-color-wheel";
import { hsvaToRgba, rgbaToHsva } from "@uiw/color-convert";
import { Copy, RotateCcw } from "lucide-react";

import { useThrottledParameterValue } from "../hooks/useThrottledParameterValue";
import { ParameterValueDisplay } from "./ParameterValueDisplay";

function valuesMatch(left, right) {
  return JSON.stringify(left) === JSON.stringify(right);
}

function ParameterHeader({ layer, parameter, onReset, resetDisabled }) {
  const layerKey = layer.shaderId || layer.shaderName || layer.id;
  const oscRoute = `/VideoShaderToys/${layerKey}/${parameter.id}`;

  function copyRoute() {
    if (navigator.clipboard) {
      navigator.clipboard.writeText(oscRoute);
    }
  }

  return (
    <div className="parameter__header">
      <label>{parameter.label}</label>
      <button
        type="button"
        className="parameter__osc"
        title="Copy OSC route"
        aria-label={`Copy OSC route ${oscRoute}`}
        onClick={copyRoute}
      >
        <span>{oscRoute}</span>
        <Copy size={13} strokeWidth={1.75} aria-hidden="true" />
      </button>
      <button
        type="button"
        className="parameter__reset"
        title={`Reset ${parameter.label}`}
        aria-label={`Reset ${parameter.label}`}
        disabled={resetDisabled}
        onClick={onReset}
      >
        <RotateCcw size={13} strokeWidth={1.9} aria-hidden="true" />
      </button>
    </div>
  );
}

function clamp01(value) {
  return Math.max(0, Math.min(1, Number(value) || 0));
}

function colorComponentToHex(value) {
  return Math.round(clamp01(value) * 255)
    .toString(16)
    .padStart(2, "0");
}

function colorValueToHex(value) {
  const values = [...(value ?? [])];
  while (values.length < 3) {
    values.push(0);
  }
  return `#${colorComponentToHex(values[0])}${colorComponentToHex(values[1])}${colorComponentToHex(values[2])}`;
}

function colorValueToHsva(value) {
  const values = [...(value ?? [])];
  while (values.length < 4) {
    values.push(values.length === 3 ? 1 : 0);
  }
  return rgbaToHsva({
    r: Math.round(clamp01(values[0]) * 255),
    g: Math.round(clamp01(values[1]) * 255),
    b: Math.round(clamp01(values[2]) * 255),
    a: clamp01(values[3]),
  });
}

function hsvaToColorValue(hsva, alpha) {
  const rgba = hsvaToRgba({ ...hsva, a: clamp01(alpha ?? hsva.a ?? 1) });
  return [
    clamp01(rgba.r / 255),
    clamp01(rgba.g / 255),
    clamp01(rgba.b / 255),
    clamp01(alpha ?? rgba.a ?? 1),
  ];
}

export function ParameterField({ layer, parameter, onParameterChange }) {
  const {
    appliedValue,
    beginInteraction,
    draftValue,
    endInteraction,
    isPending,
    scheduleSendValue,
    sendValue,
  } = useThrottledParameterValue(parameter, onParameterChange);

  const defaultValue = parameter.defaultValue;
  const resetDisabled = defaultValue === undefined || valuesMatch(draftValue, defaultValue);
  const resetParameter = () => {
    if (defaultValue !== undefined) {
      sendValue(defaultValue);
    }
  };
  const header = (
    <ParameterHeader
      layer={layer}
      parameter={parameter}
      resetDisabled={resetDisabled}
      onReset={resetParameter}
    />
  );

  if (parameter.type === "float") {
    return (
      <section className="parameter">
        {header}
        <div className="parameter__pair">
          <input
            type="range"
            min={parameter.min?.[0] ?? 0}
            max={parameter.max?.[0] ?? 1}
            step={parameter.step?.[0] ?? 0.01}
            value={draftValue}
            onMouseDown={beginInteraction}
            onPointerDown={beginInteraction}
            onTouchStart={beginInteraction}
            onChange={(event) => scheduleSendValue(Number(event.target.value))}
            onMouseUp={endInteraction}
            onTouchEnd={endInteraction}
            onPointerUp={endInteraction}
            onKeyDown={beginInteraction}
            onKeyUp={endInteraction}
            onBlur={endInteraction}
          />
          <input
            type="number"
            min={parameter.min?.[0] ?? ""}
            max={parameter.max?.[0] ?? ""}
            step={parameter.step?.[0] ?? 0.01}
            value={draftValue}
            onFocus={beginInteraction}
            onChange={(event) => sendValue(Number(event.target.value))}
            onBlur={endInteraction}
          />
        </div>
        <ParameterValueDisplay parameterType={parameter.type} value={appliedValue} pending={isPending} />
      </section>
    );
  }

  if (parameter.type === "vec2") {
    const values = [...(draftValue ?? [])];
    while (values.length < 2) {
      values.push(0);
    }

    return (
      <section className="parameter">
        {header}
        <div className="parameter__pair">
          {Array.from({ length: 2 }, (_, index) => (
            <input
              key={index}
              type="number"
              min={parameter.min?.[index] ?? ""}
              max={parameter.max?.[index] ?? ""}
              step={parameter.step?.[index] ?? 0.01}
              value={values[index]}
              onFocus={beginInteraction}
              onChange={(event) => {
                const next = [...values];
                next[index] = Number(event.target.value);
                sendValue(next);
              }}
              onBlur={endInteraction}
            />
          ))}
        </div>
        <ParameterValueDisplay parameterType={parameter.type} value={appliedValue} pending={isPending} />
      </section>
    );
  }

  if (parameter.type === "color") {
    const values = [...(draftValue ?? [])];
    while (values.length < 4) {
      values.push(values.length === 3 ? 1 : 0);
    }

    return (
      <section className="parameter">
        {header}
        <div className="parameter__wheel-row">
          <div
            className="parameter__wheel"
            onPointerDown={beginInteraction}
            onPointerUp={endInteraction}
            onPointerCancel={endInteraction}
            onBlur={endInteraction}
          >
            <Wheel
              color={colorValueToHsva(values)}
              width={132}
              height={132}
              onChange={(color) => scheduleSendValue(hsvaToColorValue(color.hsva, values[3]))}
            />
          </div>
          <label className="parameter__alpha">
            <span>Alpha</span>
            <input
              type="number"
              min={parameter.min?.[3] ?? 0}
              max={parameter.max?.[3] ?? 1}
              step={parameter.step?.[3] ?? 0.01}
              value={values[3]}
              onFocus={beginInteraction}
              onChange={(event) => {
                const next = [...values];
                next[3] = Number(event.target.value);
                sendValue(next);
              }}
              onBlur={endInteraction}
            />
          </label>
          <div className="parameter__swatch" style={{ background: colorValueToHex(values) }} aria-hidden="true" />
        </div>
        <ParameterValueDisplay parameterType={parameter.type} value={appliedValue} pending={isPending} />
      </section>
    );
  }

  if (parameter.type === "bool") {
    return (
      <section className="parameter">
        {header}
        <label className="toggle toggle--field">
          <input
            type="checkbox"
            checked={Boolean(draftValue)}
            onFocus={beginInteraction}
            onChange={(event) => sendValue(event.target.checked)}
            onBlur={endInteraction}
          />
          <span>{draftValue ? "Enabled" : "Disabled"}</span>
        </label>
        <ParameterValueDisplay parameterType={parameter.type} value={appliedValue} pending={isPending} />
      </section>
    );
  }

  if (parameter.type === "enum") {
    return (
      <section className="parameter">
        {header}
        <select
          value={draftValue}
          onFocus={beginInteraction}
          onChange={(event) => sendValue(event.target.value)}
          onBlur={endInteraction}
        >
          {parameter.options.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
        <ParameterValueDisplay parameterType={parameter.type} value={appliedValue} pending={isPending} />
      </section>
    );
  }

  if (parameter.type === "text") {
    return (
      <section className="parameter">
        {header}
        <input
          type="text"
          maxLength={parameter.maxLength ?? 64}
          value={draftValue ?? ""}
          onFocus={beginInteraction}
          onChange={(event) => sendValue(event.target.value)}
          onBlur={endInteraction}
        />
        <ParameterValueDisplay parameterType={parameter.type} value={appliedValue} pending={isPending} />
      </section>
    );
  }

  return null;
}
