import type { AdminActionSummary } from "@xtablo/shared-types";
import { useEffect, useMemo, useState } from "react";
import { actionSeverityCopy } from "../../registry/actions";

type ActionRunnerProps = {
  actions: AdminActionSummary[];
  error: string | null;
  isRunning: boolean;
  onRun: (payload: Record<string, string>) => Promise<void>;
  onSelectActionId: (actionId: string) => void;
  resultMessage: string | null;
  selectedActionId: string | null;
};

export function ActionRunner({
  actions,
  error,
  isRunning,
  onRun,
  onSelectActionId,
  resultMessage,
  selectedActionId,
}: ActionRunnerProps) {
  const selectedAction = useMemo(
    () => actions.find((action) => action.id === selectedActionId) ?? null,
    [actions, selectedActionId]
  );
  const [values, setValues] = useState<Record<string, string>>({});

  useEffect(() => {
    if (!selectedAction) {
      return;
    }

    setValues(Object.fromEntries(selectedAction.fields.map((field) => [field.id, ""])));
  }, [selectedAction]);

  const tone = selectedAction
    ? actionSeverityCopy[selectedAction.id as keyof typeof actionSeverityCopy]
    : null;

  return (
    <div className="grid gap-6 lg:grid-cols-[280px_minmax(0,1fr)]">
      <aside className="rounded-[2rem] border border-border bg-card p-5">
        <p className="text-xs uppercase tracking-[0.2em] text-foreground/50">Approved Actions</p>
        <div className="mt-4 flex flex-col gap-3">
          {actions.map((action) => (
            <button
              className={`rounded-[1.25rem] border px-4 py-3 text-left ${
                action.id === selectedActionId
                  ? "border-foreground bg-foreground text-background"
                  : "border-border bg-background/70"
              }`}
              key={action.id}
              onClick={() => onSelectActionId(action.id)}
              type="button"
            >
              <p className="text-sm font-semibold">{action.label}</p>
              <p className="mt-1 text-sm opacity-80">{action.description}</p>
            </button>
          ))}
        </div>
      </aside>

      <section className="rounded-[2rem] border border-border bg-card p-6">
        {selectedAction ? (
          <form
            className="space-y-5"
            onSubmit={(event) => {
              event.preventDefault();
              void onRun(values);
            }}
          >
            <div className="flex flex-wrap items-start justify-between gap-4">
              <div>
                <p className="text-xs uppercase tracking-[0.2em] text-foreground/50">Action</p>
                <h2 className="mt-2 text-3xl font-semibold">{selectedAction.label}</h2>
                <p className="mt-2 max-w-2xl text-sm text-foreground/70">
                  {selectedAction.description}
                </p>
              </div>
              {tone ? (
                <span
                  className={`rounded-full px-3 py-1 text-xs uppercase tracking-[0.2em] ${
                    tone.tone === "critical"
                      ? "bg-red-100 text-red-700"
                      : "bg-amber-100 text-amber-700"
                  }`}
                >
                  {tone.badge}
                </span>
              ) : null}
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              {selectedAction.fields.map((field) => (
                <label className="block" htmlFor={field.id} key={field.id}>
                  <span className="mb-2 block text-sm font-medium">{field.label}</span>
                  <input
                    className="w-full rounded-2xl border border-border bg-background px-3 py-2"
                    id={field.id}
                    onChange={(event) =>
                      setValues((currentValue) => ({
                        ...currentValue,
                        [field.id]: event.target.value,
                      }))
                    }
                    placeholder={field.placeholder}
                    required={field.required}
                    value={values[field.id] ?? ""}
                  />
                </label>
              ))}
            </div>

            {error ? <p className="text-sm text-red-600">{error}</p> : null}
            {resultMessage ? <p className="text-sm text-emerald-700">{resultMessage}</p> : null}

            <button
              className="rounded-2xl bg-foreground px-4 py-2 text-background disabled:cursor-not-allowed disabled:opacity-60"
              disabled={isRunning}
              type="submit"
            >
              {isRunning ? "Running..." : "Run Action"}
            </button>
          </form>
        ) : (
          <p className="text-sm text-foreground/70">Select an action to begin.</p>
        )}
      </section>
    </div>
  );
}
