import { useState, type ReactNode } from "react";
import { ConfirmDialog, Field, FormError, Select, TextArea, TextInput } from "./form";
import { useAct } from "./blocks";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";

export interface ActionField {
  key: string;
  label: string;
  type?: "text" | "area" | "date" | "number" | "select";
  options?: [string, string][];
  required?: boolean;
  help?: string;
  min?: string;
}
/** A button that asks for a few values, then does one thing. */
export function ActionButton<R>({
  label,
  title,
  description,
  fields = [],
  initial = {},
  run,
  success,
  refresh = [],
  destructive,
  confirmLabel,
  size = "sm",
  variant = "outline",
  onDone,
}: {
  label: ReactNode;
  title: string;
  description?: string;
  fields?: ActionField[];
  initial?: Record<string, string>;
  run: (v: Record<string, string>) => Promise<R>;
  success: string | ((r: R) => string);
  refresh?: string[];
  destructive?: boolean;
  confirmLabel?: string;
  size?: "sm" | "default";
  variant?: "outline" | "ghost" | "default";
  onDone?: (r: R) => void;
}) {
  const [open, setOpen] = useState(false);
  const [v, setV] = useState<Record<string, string>>(initial);
  const m = useAct((_: void) => run(v), {
    success,
    refresh,
    onError: () => {},
    onDone: (r) => {
      setOpen(false);
      onDone?.(r);
    },
  });
  const bad = fields.some((f) => f.required && !(v[f.key] ?? "").trim());
  return (
    <>
      <Button
        type="button"
        size={size}
        variant={variant}
        onClick={() => {
          setV(initial);
          m.reset();
          setOpen(true);
        }}
      >
        {label}
      </Button>
      <ConfirmDialog
        open={open}
        onOpenChange={setOpen}
        title={title}
        {...(description ? { description } : {})}
        confirmLabel={confirmLabel ?? "Save"}
        {...(destructive ? { destructive } : {})}
        pending={m.isPending || bad}
        onConfirm={() => m.mutate()}
      >
        <FormError error={m.error} />
        <div className="space-y-3">
          {fields.map((f) => {
            const set = (x: string) => setV((s) => ({ ...s, [f.key]: x }));
            const value = v[f.key] ?? "";
            return (
              <Field key={f.key} label={f.label} required={!!f.required} help={f.help}>
                {f.type === "select" ? (
                  <Select value={value} onChange={set} options={f.options ?? []} />
                ) : f.type === "area" ? (
                  <TextArea rows={2} value={value} onChange={set} maxLength={480} />
                ) : f.type === "date" ? (
                  <Input
                    type="date"
                    value={value}
                    min={f.min}
                    onChange={(e) => set(e.target.value)}
                  />
                ) : (
                  <TextInput
                    value={value}
                    onChange={set}
                    {...(f.type === "number" ? { inputMode: "numeric" as const } : {})}
                  />
                )}
              </Field>
            );
          })}
        </div>
      </ConfirmDialog>
    </>
  );
}
