/**
 * ActionsTab — master/detail layout for action.d discovery and editing.
 *
 * Left pane: action names with Active/Inactive badges (active actions sorted
 * to the top).  Active badge also shows which jails reference the action.
 * Right pane: structured action editor, "Assign to Jail" button, a
 * "Remove from Jail" section, and a collapsible raw-config editor.
 *
 * A "Create Action" button at the top of the list pane opens a dialog for
 * creating a new `action.d/*.local` file.
 */

import { useCallback, useMemo, useState } from "react";
import {
  Button,
  MessageBar,
  MessageBarBody,
  Skeleton,
  SkeletonItem,
} from "@fluentui/react-components";
import { Add24Regular } from "@fluentui/react-icons";
import type { ActionConfig } from "../../types/config";
import { useActionList } from "../../hooks/useActionList";
import { AssignActionDialog } from "./AssignActionDialog";
import { ConfigListDetail } from "./ConfigListDetail";
import { CreateActionDialog } from "./CreateActionDialog";
import { ActionDetail } from "./ActionDetail";

function actionBadgeLabel(a: ActionConfig): string {
  if (!a.active) return "Inactive";
  if (a.used_by_jails.length === 0) return "Active";
  return `Active — ${a.used_by_jails.join(", ")}`;
}

export function ActionsTab(): React.JSX.Element {
  const {
    actions,
    loading,
    error,
    refresh,
    removeActionFromJail,
    createAction,
    assignActionToJail,
  } = useActionList();
  const [selectedName, setSelectedName] = useState<string | null>(null);
  const [assignOpen, setAssignOpen] = useState(false);
  const [createOpen, setCreateOpen] = useState(false);

  const selectedAction = useMemo(
    () => actions.find((a) => a.name === selectedName) ?? null,
    [actions, selectedName],
  );

  const handleAssigned = useCallback((): void => {
    setAssignOpen(false);
    refresh();
  }, [refresh]);

  const handleCreated = useCallback(
    (newAction: ActionConfig): void => {
      setCreateOpen(false);
      setSelectedName(newAction.name);
      refresh();
    },
    [refresh],
  );

  const handleRemovedFromJail = useCallback(
    async (jailName: string): Promise<void> => {
      if (!selectedName) return;
      await removeActionFromJail(jailName, selectedName);
      refresh();
    },
    [removeActionFromJail, refresh, selectedName],
  );

  if (loading) {
    return (
      <Skeleton aria-label="Loading actions…">
        {[0, 1, 2].map((i) => (
          <SkeletonItem key={i} size={40} style={{ marginBottom: 4 }} />
        ))}
      </Skeleton>
    );
  }

  if (error) {
    return (
      <MessageBar intent="error">
        <MessageBarBody>{error}</MessageBarBody>
      </MessageBar>
    );
  }

  const listHeader = (
    <Button
      appearance="outline"
      icon={<Add24Regular />}
      size="small"
      onClick={() => { setCreateOpen(true); }}
    >
      Create Action
    </Button>
  );

  return (
    <>
      <ConfigListDetail
        items={actions}
        isActive={(a) => a.active}
        itemBadgeLabel={actionBadgeLabel}
        selectedName={selectedName}
        onSelect={setSelectedName}
        loading={loading}
        error={error}
        listHeader={listHeader}
      >
        {selectedAction !== null && (
          <ActionDetail
            key={selectedAction.name}
            action={selectedAction}
            onAssignClick={() => { setAssignOpen(true); }}
            onRemovedFromJail={handleRemovedFromJail}
          />
        )}
      </ConfigListDetail>

      <AssignActionDialog
        actionName={selectedName}
        open={assignOpen}
        onClose={() => { setAssignOpen(false); }}
        onAssigned={handleAssigned}
        onAssign={async (jailName, payload, reload) => {
          await assignActionToJail(jailName, payload, reload);
        }}
      />

      <CreateActionDialog
        open={createOpen}
        onClose={() => { setCreateOpen(false); }}
        onCreateAction={createAction}
        onCreate={handleCreated}
      />
    </>
  );
}
