﻿import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  Button,
  Field,
  Input,
  Table,
  TableBody,
  TableCell,
  TableHeader,
  TableHeaderCell,
  TableRow,
  Textarea,
} from "@fluentui/react-components";
import { useState } from "react";
import { portalApi } from "../api/portalApi";
import { DataState } from "../components/DataState";
import { FormActions, FormGrid, FormSection, FormWide } from "../components/FormSection";
import { PageHeader } from "../components/PageHeader";

export function RunbooksPage() {
  const queryClient = useQueryClient();
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const { data, error, isLoading } = useQuery({
    queryKey: ["runbooks"],
    queryFn: ({ signal }) => portalApi.getRunbooks(signal),
  });
  const addRunbook = useMutation({
    mutationFn: portalApi.addRunbook,
    onSuccess: async () => {
      setName("");
      setDescription("");
      await queryClient.invalidateQueries({ queryKey: ["runbooks"] });
    },
  });

  return (
    <>
      <PageHeader title="Runbooks" description="Automatisierungen fuer Portalereignisse." />
      <FormSection
        onSubmit={(event) => {
          event.preventDefault();
          addRunbook.mutate({ description, name });
        }}
      >
        <FormGrid>
          <Field label="Name" required>
            <Input value={name} onChange={(_, data) => setName(data.value)} />
          </Field>
          <FormWide>
            <Field label="Description" required validationMessage={addRunbook.error?.message}>
              <Textarea value={description} onChange={(_, data) => setDescription(data.value)} />
            </Field>
          </FormWide>
        </FormGrid>
        <FormActions>
          <Button
            appearance="primary"
            disabled={!name || !description || addRunbook.isPending}
            type="submit"
          >
            Add runbook
          </Button>
        </FormActions>
      </FormSection>
      <DataState isLoading={isLoading} error={error} />
      {data && (
        <Table aria-label="Runbooks">
          <TableHeader>
            <TableRow>
              <TableHeaderCell>Name</TableHeaderCell>
              <TableHeaderCell>Description</TableHeaderCell>
              <TableHeaderCell>Id</TableHeaderCell>
            </TableRow>
          </TableHeader>
          <TableBody>
            {data.map((runbook) => (
              <TableRow key={runbook.id}>
                <TableCell>{runbook.name}</TableCell>
                <TableCell>{runbook.decription ?? "-"}</TableCell>
                <TableCell>{runbook.id}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      )}
    </>
  );
}

