/**
 * FiltersTab — master/detail layout for filter.d discovery and editing.
 *
 * Left pane: filter names with Active/Inactive badges (active filters sorted
 * to the top).  Active badge also shows which jails reference the filter.
 * Right pane: structured filter editor, "Assign to Jail" button, and a
 * collapsible raw-config editor.
 *
 * A "Create Filter" button at the top of the list pane opens a dialog for
 * creating a new `filter.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 { FilterConfig } from "../../types/config";
import { AssignFilterDialog } from "./AssignFilterDialog";
import { ConfigListDetail } from "./ConfigListDetail";
import { CreateFilterDialog } from "./CreateFilterDialog";
import { useFilterList } from "../../hooks/useFilterList";
import { FilterDetail } from "./FilterDetail";

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

export function FiltersTab(): React.JSX.Element {
  const {
    filters,
    loading,
    error,
    refresh,
    createFilter,
    assignFilterToJail,
  } = useFilterList();
  const [selectedName, setSelectedName] = useState<string | null>(null);
  const [assignOpen, setAssignOpen] = useState(false);
  const [createOpen, setCreateOpen] = useState(false);

  const selectedFilter = useMemo(
    () => filters.find((f) => f.name === selectedName) ?? null,
    [filters, selectedName],
  );

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

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

  if (loading) {
    return (
      <Skeleton aria-label="Loading filters…">
        {[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 Filter
    </Button>
  );

  return (
    <>
      <ConfigListDetail
        items={filters}
        isActive={(f) => f.active}
        itemBadgeLabel={filterBadgeLabel}
        selectedName={selectedName}
        onSelect={setSelectedName}
        loading={loading}
        error={error}
        listHeader={listHeader}
      >
        {selectedFilter !== null && (
          <FilterDetail
            key={selectedFilter.name}
            filter={selectedFilter}
            onAssignClick={() => { setAssignOpen(true); }}
          />
        )}
      </ConfigListDetail>

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

      <CreateFilterDialog
        open={createOpen}
        onClose={() => { setCreateOpen(false); }}
        onCreateFilter={createFilter}
        onCreate={handleCreated}
      />
    </>
  );
}
