import { useState } from "react";
import {
  Badge,
  Button,
  Field,
  Input,
  MessageBar,
  MessageBarBody,
  Switch,
  Text,
  Tooltip,
} from "@fluentui/react-components";
import { DismissRegular } from "@fluentui/react-icons";
import { useCommonSectionStyles } from "../../components/commonStyles";
import { useJailDetailPageStyles } from "./jailDetailPageStyles";

interface IgnoreListSectionProps {
  jailName: string;
  ignoreList: string[];
  ignoreSelf: boolean;
  onAdd: (ip: string) => Promise<void>;
  onRemove: (ip: string) => Promise<void>;
  onToggleIgnoreSelf: (on: boolean) => Promise<void>;
}

export function IgnoreListSection({
  jailName: _jailName,
  ignoreList,
  ignoreSelf,
  onAdd,
  onRemove,
  onToggleIgnoreSelf,
}: IgnoreListSectionProps): React.JSX.Element {
  const styles = useJailDetailPageStyles();
  const sectionStyles = useCommonSectionStyles();
  const [inputVal, setInputVal] = useState("");
  const [opError, setOpError] = useState<string | null>(null);

  const handleAdd = (): void => {
    if (!inputVal.trim()) return;
    setOpError(null);
    onAdd(inputVal.trim())
      .then(() => {
        setInputVal("");
      })
      .catch((err: unknown) => {
        setOpError(err instanceof Error ? err.message : String(err));
      });
  };

  const handleRemove = (ip: string): void => {
    setOpError(null);
    onRemove(ip).catch((err: unknown) => {
      setOpError(err instanceof Error ? err.message : String(err));
    });
  };

  return (
    <div className={sectionStyles.section}>
      <div className={sectionStyles.sectionHeader}>
        <div style={{ display: "flex", alignItems: "center", gap: "var(--spacingHorizontalM)" }}>
          <Text as="h2" size={500} weight="semibold">
            Ignore List (IP Whitelist)
          </Text>
        </div>
        <Badge appearance="tint">{String(ignoreList.length)}</Badge>
      </div>

      <Switch
        label="Ignore self — exclude this server's own IP addresses from banning"
        checked={ignoreSelf}
        onChange={(_e, data): void => {
          onToggleIgnoreSelf(data.checked).catch((err: unknown) => {
            setOpError(err instanceof Error ? err.message : String(err));
          });
        }}
      />

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

      <div className={styles.formRow}>
        <div className={styles.formField}>
          <Field label="Add IP or CIDR network">
            <Input
              placeholder="e.g. 10.0.0.0/8 or 192.168.1.1"
              value={inputVal}
              onChange={(_, d) => {
                setInputVal(d.value);
              }}
              onKeyDown={(e) => {
                if (e.key === "Enter") handleAdd();
              }}
            />
          </Field>
        </div>
        <Button
          appearance="primary"
          onClick={handleAdd}
          disabled={!inputVal.trim()}
        >
          Add
        </Button>
      </div>

      {ignoreList.length === 0 ? (
        <Text size={200} style={{ color: "var(--colorNeutralForeground3)" }}>
          The ignore list is empty.
        </Text>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: "4px" }}>
          {ignoreList.map((ip) => (
            <div key={ip} className={styles.ignoreRow}>
              <Text className={styles.mono}>{ip}</Text>
              <Tooltip content={`Remove ${ip} from ignore list`} relationship="label">
                <Button
                  size="small"
                  appearance="subtle"
                  icon={<DismissRegular />}
                  onClick={() => {
                    handleRemove(ip);
                  }}
                  aria-label={`Remove ${ip}`}
                >
                  Remove
                </Button>
              </Tooltip>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
