/**
 * BlocklistsPage — external IP blocklist source management.
 *
 * Responsible for composition of sources, schedule, and import log sections.
 */

import { useCallback, useState } from "react";
import { MessageBar, MessageBarBody, Text } from "@fluentui/react-components";
import { useBlocklistStyles } from "../components/blocklist/blocklistStyles";
import { BlocklistSourcesSection } from "../components/blocklist/BlocklistSourcesSection";
import { BlocklistScheduleSection } from "../components/blocklist/BlocklistScheduleSection";
import { BlocklistImportLogSection } from "../components/blocklist/BlocklistImportLogSection";
import { useRunImport } from "../hooks/useBlocklist";
import { ImportResultDialog } from "./blocklists/ImportResultDialog";

export function BlocklistsPage(): React.JSX.Element {
  const styles = useBlocklistStyles();
  const { running, lastResult, error: importError, runNow } = useRunImport();
  const [importResultOpen, setImportResultOpen] = useState(false);

  const handleRunImport = useCallback((): void => {
    void runNow().then(() => {
      setImportResultOpen(true);
    });
  }, [runNow]);

  return (
    <div className={styles.root}>
      <Text as="h1" size={700} weight="semibold">
        Blocklists
      </Text>

      {importError && (
        <MessageBar intent="error">
          <MessageBarBody>Import error: {importError}</MessageBarBody>
        </MessageBar>
      )}

      <BlocklistSourcesSection onRunImport={handleRunImport} runImportRunning={running} />
      <BlocklistScheduleSection onRunImport={handleRunImport} runImportRunning={running} />
      <BlocklistImportLogSection />

      <ImportResultDialog
        open={importResultOpen}
        result={lastResult}
        onClose={() => { setImportResultOpen(false); }}
      />
    </div>
  );
}
