import { useCallback, useState } from "react";
import {
  Button,
  MessageBar,
  MessageBarBody,
  Spinner,
  Switch,
  Table,
  TableBody,
  TableCell,
  TableCellLayout,
  TableHeader,
  TableHeaderCell,
  TableRow,
  Text,
} from "@fluentui/react-components";
import { useCommonSectionStyles } from "../../components/commonStyles";
import {
  AddRegular,
  ArrowClockwiseRegular,
  DeleteRegular,
  EditRegular,
  EyeRegular,
  PlayRegular,
} from "@fluentui/react-icons";
import { useBlocklists } from "../../hooks/useBlocklist";
import type { BlocklistSource } from "../../types/blocklist";
import { useBlocklistStyles } from "./blocklistStyles";
import { SourceFormDialog } from "./SourceFormDialog";
import { PreviewDialog } from "./PreviewDialog";

interface SourceFormValues {
  name: string;
  url: string;
  enabled: boolean;
}

interface SourcesSectionProps {
  onRunImport: () => void;
  runImportRunning: boolean;
}

const EMPTY_SOURCE: SourceFormValues = { name: "", url: "", enabled: true };

export function BlocklistSourcesSection({ onRunImport, runImportRunning }: SourcesSectionProps): React.JSX.Element {
  const styles = useBlocklistStyles();
  const sectionStyles = useCommonSectionStyles();
  const { sources, loading, error, refresh, createSource, updateSource, removeSource, previewSource } = useBlocklists();

  const [dialogOpen, setDialogOpen] = useState(false);
  const [dialogMode, setDialogMode] = useState<"add" | "edit">("add");
  const [dialogInitial, setDialogInitial] = useState<SourceFormValues>(EMPTY_SOURCE);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewSourceItem, setPreviewSourceItem] = useState<BlocklistSource | null>(null);

  const openAdd = useCallback((): void => {
    setDialogMode("add");
    setDialogInitial(EMPTY_SOURCE);
    setEditingId(null);
    setSaveError(null);
    setDialogOpen(true);
  }, []);

  const openEdit = useCallback((source: BlocklistSource): void => {
    setDialogMode("edit");
    setDialogInitial({ name: source.name, url: source.url, enabled: source.enabled });
    setEditingId(source.id);
    setSaveError(null);
    setDialogOpen(true);
  }, []);

  const handleSubmit = useCallback(
    (values: SourceFormValues): void => {
      setSaving(true);
      setSaveError(null);
      const op =
        dialogMode === "add"
          ? createSource({ name: values.name, url: values.url, enabled: values.enabled })
          : updateSource(editingId ?? -1, { name: values.name, url: values.url, enabled: values.enabled });
      op
        .then(() => {
          setSaving(false);
          setDialogOpen(false);
        })
        .catch((err: unknown) => {
          setSaving(false);
          setSaveError(err instanceof Error ? err.message : "Failed to save source");
        });
    },
    [dialogMode, editingId, createSource, updateSource],
  );

  const handleToggleEnabled = useCallback(
    (source: BlocklistSource): void => {
      void updateSource(source.id, { enabled: !source.enabled });
    },
    [updateSource],
  );

  const handleDelete = useCallback(
    (source: BlocklistSource): void => {
      void removeSource(source.id);
    },
    [removeSource],
  );

  const handlePreview = useCallback((source: BlocklistSource): void => {
    setPreviewSourceItem(source);
    setPreviewOpen(true);
  }, []);

  return (
    <div className={sectionStyles.section}>
      <div className={sectionStyles.sectionHeader}>
        <Text size={500} weight="semibold">
          Blocklist Sources
        </Text>
        <div className={styles.headerActions}>
          <Button icon={<PlayRegular />} appearance="secondary" onClick={onRunImport} disabled={runImportRunning}>
            {runImportRunning ? <Spinner size="tiny" /> : "Run Now"}
          </Button>
          <Button icon={<ArrowClockwiseRegular />} appearance="secondary" onClick={refresh}>
            Refresh
          </Button>
          <Button icon={<AddRegular />} appearance="primary" onClick={openAdd}>
            Add Source
          </Button>
        </div>
      </div>

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

      {loading ? (
        <div className={styles.centred}>
          <Spinner label="Loading sources…" />
        </div>
      ) : sources.length === 0 ? (
        <div className={styles.centred}>
          <Text>No blocklist sources configured. Click "Add Source" to get started.</Text>
        </div>
      ) : (
        <div className={styles.tableWrapper}>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHeaderCell>Name</TableHeaderCell>
                <TableHeaderCell>URL</TableHeaderCell>
                <TableHeaderCell>Enabled</TableHeaderCell>
                <TableHeaderCell>Actions</TableHeaderCell>
              </TableRow>
            </TableHeader>
            <TableBody>
              {sources.map((source) => (
                <TableRow key={source.id}>
                  <TableCell>
                    <TableCellLayout>{source.name}</TableCellLayout>
                  </TableCell>
                  <TableCell>
                    <TableCellLayout>
                      <span className={styles.mono}>{source.url}</span>
                    </TableCellLayout>
                  </TableCell>
                  <TableCell>
                    <Switch
                      checked={source.enabled}
                      onChange={() => { handleToggleEnabled(source); }}
                      label={source.enabled ? "On" : "Off"}
                    />
                  </TableCell>
                  <TableCell>
                    <div className={styles.actionsCell}>
                      <Button
                        icon={<EyeRegular />}
                        size="small"
                        appearance="secondary"
                        onClick={() => { handlePreview(source); }}
                      >
                        Preview
                      </Button>
                      <Button
                        icon={<EditRegular />}
                        size="small"
                        appearance="secondary"
                        onClick={() => { openEdit(source); }}
                      >
                        Edit
                      </Button>
                      <Button
                        icon={<DeleteRegular />}
                        size="small"
                        appearance="secondary"
                        onClick={() => { handleDelete(source); }}
                      >
                        Delete
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}

      <SourceFormDialog
        open={dialogOpen}
        mode={dialogMode}
        initial={dialogInitial}
        saving={saving}
        error={saveError}
        onClose={() => { setDialogOpen(false); }}
        onSubmit={handleSubmit}
      />

      <PreviewDialog
        open={previewOpen}
        source={previewSourceItem}
        onClose={() => { setPreviewOpen(false); }}
        fetchPreview={previewSource}
      />
    </div>
  );
}
