import { Action, ActionPanel, Icon, List, Cache, showHUD, popToRoot } from "@raycast/api";

const cache = new Cache();
const MODE_CACHE_KEY = "selected-mode";
const MODE_CACHE_TTL = 5 * 60 * 1000;

type Mode = "local-fallback" | "prod-only" | "local-only";

interface ModeOption {
  id: Mode;
  title: string;
  description: string;
  icon: Icon;
}

const modes: ModeOption[] = [
  {
    id: "local-fallback",
    title: "Local + Fallback to Prod",
    description: "Try local first, fall back to prod after ~2s timeout",
    icon: Icon.ArrowLeftCircle,
  },
  {
    id: "prod-only",
    title: "Production Only",
    description: "Load only the production URL — safe to share",
    icon: Icon.Globe,
  },
  {
    id: "local-only",
    title: "Local Only",
    description: "Load only the local URL — for rapid dev testing",
    icon: Icon.Monitor,
  },
];

function getCachedMode(): Mode | null {
  const raw = cache.get(MODE_CACHE_KEY);
  if (!raw) return null;
  try {
    const data = JSON.parse(raw) as { mode: Mode; ts: number };
    if (Date.now() - data.ts < MODE_CACHE_TTL) return data.mode;
  } catch {
    // ignore
  }
  return null;
}

function setCachedMode(mode: Mode) {
  cache.set(MODE_CACHE_KEY, JSON.stringify({ mode, ts: Date.now() }));
}

export default function Command() {
  const cachedMode = getCachedMode();

  return (
    <List searchBarPlaceholder="Change script mode…">
      {modes.map((m) => {
        const isCurrent = cachedMode === m.id;
        return (
          <List.Item
            key={m.id}
            icon={m.icon}
            title={m.title}
            subtitle={m.description}
            accessories={isCurrent ? [{ tag: { value: "current" }, icon: Icon.Checkmark }] : []}
            actions={
              <ActionPanel>
                <Action
                  title="Set Mode"
                  icon={Icon.Checkmark}
                  onAction={async () => {
                    setCachedMode(m.id);
                    const label = modes.find((x) => x.id === m.id)?.title ?? m.id;
                    await showHUD(`✅ Mode set to: ${label}`);
                    await popToRoot();
                  }}
                />
              </ActionPanel>
            }
          />
        );
      })}
    </List>
  );
}
