/**
 * CreateJailDialog — dialog for creating a new jail configuration file.
 *
 * Asks for a config file name and calls ``POST /api/config/jail-files`` on
 * confirmation, seeding the file with a minimal comment header.
 */

import { useCallback, useEffect, useState } from "react";
import {
  Button,
  Dialog,
  DialogActions,
  DialogBody,
  DialogContent,
  DialogSurface,
  DialogTitle,
  Field,
  Input,
  MessageBar,
  MessageBarBody,
  Spinner,
  Text,
  tokens,
} from "@fluentui/react-components";
import type { ConfFileCreateRequest } from "../../types/config";
import { ApiError } from "../../api/client";

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

export interface CreateJailDialogProps {
  /** Whether the dialog is currently open. */
  open: boolean;
  /** Called when the dialog should close without taking action. */
  onClose: () => void;
  /** Called when the form is submitted with valid dialog data. */
  onCreateJail: (payload: ConfFileCreateRequest) => Promise<void>;
  /** Called after the jail config file has been successfully created. */
  onCreated: () => void;
}

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

/**
 * Dialog for creating a new jail configuration file at
 * ``jail.d/{name}.conf``.
 *
 * The name field accepts a plain base name (e.g. ``my-custom-jail``); the
 * backend appends the ``.conf`` extension.
 *
 * @param props - Component props.
 * @returns JSX element.
 */
export function CreateJailDialog({
  open,
  onClose,
  onCreateJail,
  onCreated,
}: CreateJailDialogProps): React.JSX.Element {
  const [name, setName] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Reset form when the dialog opens.
  useEffect(() => {
    if (open) {
      setName("");
      setError(null);
    }
  }, [open]);

  const handleClose = useCallback((): void => {
    if (submitting) return;
    onClose();
  }, [submitting, onClose]);

  const handleConfirm = useCallback((): void => {
    const trimmedName = name.trim();
    if (!trimmedName || submitting) return;

    const req: ConfFileCreateRequest = {
      name: trimmedName,
      content: `# ${trimmedName}\n`,
    };

    setSubmitting(true);
    setError(null);

    onCreateJail(req)
      .then(() => {
        onCreated();
      })
      .catch((err: unknown) => {
        setError(
          err instanceof ApiError ? err.message : "Failed to create jail config.",
        );
      })
      .finally(() => {
        setSubmitting(false);
      });
  }, [name, submitting, onCreated]);

  const canConfirm = name.trim() !== "" && !submitting;

  return (
    <Dialog open={open} onOpenChange={(_e, data) => { if (!data.open) handleClose(); }}>
      <DialogSurface>
        <DialogBody>
          <DialogTitle>Create Config</DialogTitle>
          <DialogContent>
            <Text
              as="p"
              size={300}
              style={{ marginBottom: tokens.spacingVerticalM }}
            >
              Creates a new jail configuration file at{" "}
              <code>jail.d/&lt;name&gt;.conf</code>.
            </Text>

            {error !== null && (
              <MessageBar
                intent="error"
                style={{ marginBottom: tokens.spacingVerticalS }}
              >
                <MessageBarBody>{error}</MessageBarBody>
              </MessageBar>
            )}

            <Field
              label="Config name"
              required
              hint='Base name without extension, e.g. "my-custom-jail". Must not already exist.'
            >
              <Input
                value={name}
                onChange={(_e, d) => { setName(d.value); }}
                placeholder="my-custom-jail"
                disabled={submitting}
              />
            </Field>
          </DialogContent>
          <DialogActions>
            <Button
              appearance="secondary"
              onClick={handleClose}
              disabled={submitting}
            >
              Cancel
            </Button>
            <Button
              appearance="primary"
              onClick={handleConfirm}
              disabled={!canConfirm}
              icon={submitting ? <Spinner size="extra-small" /> : undefined}
            >
              {submitting ? "Creating…" : "Create Config"}
            </Button>
          </DialogActions>
        </DialogBody>
      </DialogSurface>
    </Dialog>
  );
}
