import { useCallback, useState } from "react";
import { Button, Field, Input, MessageBar, MessageBarBody } from "@fluentui/react-components";
import { Delete24Regular, LinkEdit24Regular } from "@fluentui/react-icons";
import type { ActionConfig } from "../../types/config";
import { useActionRawFile } from "../../hooks/useActionRawFile";
import { ActionForm } from "./ActionForm";
import { RawConfigSection } from "./RawConfigSection";
import { useConfigStyles } from "./configStyles";

interface ActionDetailProps {
  action: ActionConfig;
  onAssignClick: () => void;
  onRemovedFromJail: (jailName: string) => Promise<void>;
}

export function ActionDetail({ action, onAssignClick, onRemovedFromJail }: ActionDetailProps): React.JSX.Element {
  const styles = useConfigStyles();
  const [removingJail, setRemovingJail] = useState<string | null>(null);
  const [removeError, setRemoveError] = useState<string | null>(null);
  const { fetchRawContent, saveRawContent } = useActionRawFile(action.name);

  const handleRemoveFromJail = useCallback(
    (jailName: string): void => {
      setRemovingJail(jailName);
      setRemoveError(null);
      onRemovedFromJail(jailName)
        .catch((err: unknown) => {
          setRemoveError(err instanceof Error ? err.message : "Failed to remove action from jail.");
        })
        .finally(() => {
          setRemovingJail(null);
        });
    },
    [onRemovedFromJail],
  );

  return (
    <div>
      <div className={styles.fieldRow} style={{ marginBottom: "var(--spacingVerticalS)" }}>
        <Field label="Source file">
          <Input
            readOnly
            value={action.source_file || action.filename}
            className={styles.codeInput}
            size="small"
          />
        </Field>
      </div>

      <ActionForm name={action.name} />

      <div style={{ marginTop: "var(--spacingVerticalM)" }}>
        <Button appearance="secondary" icon={<LinkEdit24Regular />} onClick={onAssignClick}>
          Assign to Jail
        </Button>
      </div>

      {action.used_by_jails.length > 0 && (
        <div style={{ marginTop: "var(--spacingVerticalM)" }}>
          {removeError !== null && (
            <MessageBar intent="error" style={{ marginBottom: "var(--spacingVerticalXS)" }}>
              <MessageBarBody>{removeError}</MessageBarBody>
            </MessageBar>
          )}
          <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            {action.used_by_jails.map((jailName) => (
              <div key={jailName} style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ fontFamily: "monospace", fontSize: 13 }}>{jailName}</span>
                <Button
                  appearance="subtle"
                  size="small"
                  icon={<Delete24Regular />}
                  disabled={removingJail !== null}
                  onClick={() => { handleRemoveFromJail(jailName); }}
                  aria-label={`Remove action from ${jailName}`}
                >
                  Remove
                </Button>
              </div>
            ))}
          </div>
        </div>
      )}

      <div style={{ marginTop: "var(--spacingVerticalL)" }}>
        <RawConfigSection
          fetchContent={fetchRawContent}
          saveContent={saveRawContent}
          label="Raw Action Configuration"
        />
      </div>
    </div>
  );
}
