import { useAppSelector } from "@renderer/redux/reduxHooks";
import {
  CheckCircleFilled,
  ExclamationCircleFilled,
  PauseCircleOutlined,
  PlayCircleOutlined,
} from "@ant-design/icons";
import {
  selectWatcherError,
  selectWatcherStatus,
} from "@renderer/redux/app.slice";
import {
  Alert,
  Badge,
  Button,
  Card,
  Col,
  InputNumber,
  Row,
  Space,
  Switch,
} from "antd";
import { FC, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import ipcTypes from "../../../../util/ipcTypes.json";

const colSpans = {
  md: 12,
  sm: 24,
};

const SettingsWatcher: FC = () => {
  const { t } = useTranslation();
  const isWatcherStarted = useAppSelector(selectWatcherStatus);
  const watcherError = useAppSelector(selectWatcherError);

  const [pollingState, setPollingState] = useState<{
    enabled: boolean;
    interval: number;
  }>({
    enabled: false,
    interval: 0,
  });

  const getPollingStateFromStore = (): void => {
    window.electron.ipcRenderer
      .invoke(ipcTypes.toMain.settings.watcher.getpolling)
      .then((storePollingState: { enabled: boolean; interval: number }) => {
        setPollingState(storePollingState);
      });
  };

  //Get state first time it renders.
  useEffect(() => {
    getPollingStateFromStore();
  }, []);

  const handleStart = (): void => {
    window.electron.ipcRenderer.send(ipcTypes.toMain.watcher.start);
  };

  const handleStop = (): void => {
    window.electron.ipcRenderer.send(ipcTypes.toMain.watcher.stop);
  };

  const toggleWatcherMode = (checked: boolean): void => {
    window.electron.ipcRenderer
      .invoke(ipcTypes.toMain.settings.watcher.setpolling, {
        enabled: !checked,
        interval: pollingState.interval,
      })
      .then((storePollingState: { enabled: boolean; interval: number }) => {
        setPollingState(storePollingState);
      });
  };

  const handlePollingIntervalChange = (value: number | null): void => {
    if (value) {
      window.electron.ipcRenderer
        .invoke(ipcTypes.toMain.settings.watcher.setpolling, {
          enabled: pollingState.enabled,
          interval: value,
        })
        .then((storePollingState: { enabled: boolean; interval: number }) => {
          setPollingState(storePollingState);
        });
    }
    getPollingStateFromStore();
  };

  return (
    <Badge.Ribbon
      text={
        isWatcherStarted ? (
          <Space>
            <CheckCircleFilled />
            {t("settings.labels.started")}
          </Space>
        ) : (
          <Space>
            <ExclamationCircleFilled />
            {t("settings.labels.stopped")}
          </Space>
        )
      }
      color={isWatcherStarted ? "green" : "red"}
    >
      <Card title={t("settings.labels.watcherstatus")}>
        <Row gutter={[16, 16]}>
          <Col {...colSpans}>
            {isWatcherStarted ? (
              <Button
                danger
                icon={<PauseCircleOutlined />}
                onClick={handleStop}
              >
                {t("settings.actions.stopwatcher")}
              </Button>
            ) : (
              <Button
                type="primary"
                icon={<PlayCircleOutlined />}
                onClick={handleStart}
              >
                {t("settings.actions.startwatcher")}
              </Button>
            )}
          </Col>
          <Col {...colSpans}>
            <Space direction="vertical" wrap>
              <Switch
                checked={!pollingState.enabled}
                onChange={toggleWatcherMode}
                checkedChildren={t("settings.labels.watchermoderealtime")}
                unCheckedChildren={t("settings.labels.watchermodepolling")}
              />
              {pollingState.enabled && (
                <Space size="small" direction="vertical" wrap>
                  <span>{t("settings.labels.pollinginterval")}</span>
                  <InputNumber
                    title={t("settings.labels.pollinginterval")}
                    disabled={!pollingState.enabled}
                    min={1000}
                    value={pollingState.interval}
                    onChange={handlePollingIntervalChange}
                  />
                </Space>
              )}
              {watcherError && <Alert message={watcherError} />}
            </Space>
          </Col>
        </Row>
      </Card>
    </Badge.Ribbon>
  );
};
export default SettingsWatcher;
