"use client";

import { useState, useTransition } from "react";
import { X, ChevronLeft } from "lucide-react";
import type { SerializedWidgetMeta } from "@/modules/_core/registry";
import { resolveWidgetConfigOptions } from "@/app/d/actions";
import { Button } from "@/components/ui/button";

type Step = "pick" | "configure";

export function WidgetPicker({
  onClose,
  widgetMetas,
  onAdd,
  initialWidgetId,
  initialConfig,
}: {
  onClose: () => void;
  widgetMetas: SerializedWidgetMeta[];
  onAdd: (widgetId: string, config: unknown) => void;
  initialWidgetId?: string;
  initialConfig?: unknown;
}) {
  const [step, setStep] = useState<Step>(initialWidgetId ? "configure" : "pick");
  const [selectedId, setSelectedId] = useState<string | null>(initialWidgetId ?? null);
  const [options, setOptions] = useState<unknown>(null);
  const [config, setConfig] = useState<unknown>(initialConfig ?? null);
  const [, startTransition] = useTransition();

  function selectWidget(id: string) {
    const meta = widgetMetas.find((m) => m.id === id);
    if (!meta) return;
    setSelectedId(id);
    setConfig(meta.defaultConfig);
    setOptions(null);
    setStep("configure");
    startTransition(async () => {
      const opts = await resolveWidgetConfigOptions(id);
      setOptions(opts);
    });
  }

  function handleAdd() {
    if (!selectedId) return;
    onAdd(selectedId, config);
  }

  const grouped = widgetMetas.reduce<Record<string, SerializedWidgetMeta[]>>((acc, m) => {
    const cat = m.category ?? "Other";
    (acc[cat] ??= []).push(m);
    return acc;
  }, {});

  const selected = widgetMetas.find((m) => m.id === selectedId);

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
      onClick={(e) => e.target === e.currentTarget && onClose()}
    >
      <div className="relative bg-background rounded-lg shadow-xl w-full max-w-lg mx-4 max-h-[80vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center gap-2 px-4 py-3 border-b">
          {step === "configure" && !initialWidgetId && (
            <button
              type="button"
              onClick={() => setStep("pick")}
              className="text-muted-foreground hover:text-foreground"
            >
              <ChevronLeft className="size-5" />
            </button>
          )}
          <h2 className="font-semibold flex-1 text-sm">
            {step === "pick"
              ? "Add widget"
              : selected
                ? `Configure: ${selected.title}`
                : "Configure"}
          </h2>
          <button
            type="button"
            onClick={onClose}
            className="text-muted-foreground hover:text-foreground"
          >
            <X className="size-5" />
          </button>
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto p-4">
          {step === "pick" && (
            <div className="space-y-4">
              {Object.entries(grouped)
                .sort(([a], [b]) => a.localeCompare(b))
                .map(([cat, items]) => (
                  <div key={cat}>
                    <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground mb-2">
                      {cat}
                    </p>
                    <div className="space-y-1">
                      {items.map((meta) => (
                        <button
                          key={meta.id}
                          type="button"
                          onClick={() => selectWidget(meta.id)}
                          className="w-full text-left rounded-md px-3 py-2 hover:bg-accent transition-colors"
                        >
                          <p className="text-sm font-medium">{meta.title}</p>
                          <p className="text-xs text-muted-foreground">{meta.description}</p>
                        </button>
                      ))}
                    </div>
                  </div>
                ))}
            </div>
          )}

          {step === "configure" && selected && (
            <WidgetConfigurator
              meta={selected}
              config={config}
              options={options}
              onChange={setConfig}
            />
          )}
        </div>

        {/* Footer */}
        {step === "configure" && (
          <div className="flex justify-end gap-2 px-4 py-3 border-t">
            <Button variant="outline" size="sm" onClick={onClose}>
              Cancel
            </Button>
            <Button size="sm" onClick={handleAdd}>
              {initialWidgetId ? "Apply" : "Add widget"}
            </Button>
          </div>
        )}
      </div>
    </div>
  );
}

// ── Configurator ──────────────────────────────────────────────────────────────

type FieldOption = { id: string; name: string };

function WidgetConfigurator({
  meta,
  config,
  options,
  onChange,
}: {
  meta: SerializedWidgetMeta;
  config: unknown;
  options: unknown;
  onChange: (c: unknown) => void;
}) {
  const cfg = (config ?? meta.defaultConfig) as Record<string, unknown>;
  const opts = options as Record<string, FieldOption[]> | null | undefined;

  function set(key: string, value: unknown) {
    onChange({ ...cfg, [key]: value });
  }

  const entries = Object.entries(cfg);
  if (entries.length === 0) {
    return <p className="text-sm text-muted-foreground">No options available.</p>;
  }

  return (
    <div className="space-y-4">
      {entries.map(([key, value]) => {
        // "all" | string[] — multi-select with All toggle
        if (
          value === "all" ||
          (Array.isArray(value) && (key.endsWith("Ids") || key.endsWith("ids")))
        ) {
          const optKey = key.replace(/Ids?$/i, "s");
          const items: FieldOption[] = (opts?.[optKey] as FieldOption[] | undefined) ?? [];
          const isAll = value === "all";
          const selected = isAll ? [] : (value as string[]);

          return (
            <div key={key}>
              <label className="block text-sm font-medium mb-1 capitalize">
                {key.replace(/([A-Z])/g, " $1").toLowerCase()}
              </label>
              <label className="flex items-center gap-2 text-sm mb-2">
                <input
                  type="checkbox"
                  checked={isAll}
                  onChange={(e) => set(key, e.target.checked ? "all" : [])}
                  className="accent-primary"
                />
                All
              </label>
              {!isAll && (
                <div className="space-y-1 max-h-40 overflow-y-auto border rounded p-2">
                  {items.length === 0 && (
                    <p className="text-xs text-muted-foreground">None available</p>
                  )}
                  {items.map((item) => (
                    <label key={item.id} className="flex items-center gap-2 text-sm">
                      <input
                        type="checkbox"
                        checked={selected.includes(item.id)}
                        onChange={(e) => {
                          const next = e.target.checked
                            ? [...selected, item.id]
                            : selected.filter((id) => id !== item.id);
                          set(key, next);
                        }}
                        className="accent-primary"
                      />
                      {item.name}
                    </label>
                  ))}
                </div>
              )}
            </div>
          );
        }

        // boolean
        if (typeof value === "boolean") {
          return (
            <label key={key} className="flex items-center gap-2 text-sm">
              <input
                type="checkbox"
                checked={value}
                onChange={(e) => set(key, e.target.checked)}
                className="accent-primary"
              />
              <span className="capitalize">{key.replace(/([A-Z])/g, " $1").toLowerCase()}</span>
            </label>
          );
        }

        // number
        if (typeof value === "number") {
          return (
            <div key={key}>
              <label className="block text-sm font-medium mb-1 capitalize">
                {key.replace(/([A-Z])/g, " $1").toLowerCase()}
              </label>
              <input
                type="number"
                value={value}
                onChange={(e) => set(key, Number(e.target.value))}
                className="w-24 rounded-md border border-input bg-background px-3 py-1.5 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
              />
            </div>
          );
        }

        // string (enum / plain)
        if (typeof value === "string") {
          // Detect enum-like: same key appears in options as an array of strings
          const enumOpts = opts?.[key] as string[] | undefined;
          if (Array.isArray(enumOpts)) {
            return (
              <div key={key}>
                <label className="block text-sm font-medium mb-1 capitalize">
                  {key.replace(/([A-Z])/g, " $1").toLowerCase()}
                </label>
                <select
                  value={value}
                  onChange={(e) => set(key, e.target.value)}
                  className="rounded-md border border-input bg-background px-3 py-1.5 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
                >
                  {enumOpts.map((opt) => (
                    <option key={opt} value={opt}>
                      {opt}
                    </option>
                  ))}
                </select>
              </div>
            );
          }

          // Hardcoded enum fallback for known fields
          const knownEnums: Record<string, string[]> = {
            filter: ["pinned", "all"],
          };
          const known = knownEnums[key];
          if (known) {
            return (
              <div key={key}>
                <label className="block text-sm font-medium mb-1 capitalize">
                  {key.replace(/([A-Z])/g, " $1").toLowerCase()}
                </label>
                <select
                  value={value}
                  onChange={(e) => set(key, e.target.value)}
                  className="rounded-md border border-input bg-background px-3 py-1.5 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
                >
                  {known.map((opt) => (
                    <option key={opt} value={opt}>
                      {opt}
                    </option>
                  ))}
                </select>
              </div>
            );
          }
        }

        return null;
      })}
    </div>
  );
}
