import {
  selectAppUpdateCompleted,
  selectAppUpdateProgress,
  selectAppUpdateSpeed,
  selectUpdateAvailable,
} from "@renderer/redux/app.slice";
import { useAppSelector } from "@renderer/redux/reduxHooks";
import { Affix, Button, Card, Progress, Space, Statistic } from "antd";
import { useTranslation } from "react-i18next";
import ipcTypes from "../../../../util/ipcTypes.json";
import { useState, FC } from "react";

const UpdateAvailable: FC = () => {
  const { t } = useTranslation();

  const isUpdateAvailable = useAppSelector(selectUpdateAvailable);
  const updateSpeed = useAppSelector(selectAppUpdateSpeed);
  const updateProgress = useAppSelector(selectAppUpdateProgress);
  const isUpdateComplete = useAppSelector(selectAppUpdateCompleted);
  const [applyingUpdate, setApplyingUpdate] = useState<boolean>(false);

  const handleDownload = (): void => {
    window.electron.ipcRenderer.send(ipcTypes.toMain.updates.download);
  };

  const handleApply = (): void => {
    setApplyingUpdate(true);
    window.electron.ipcRenderer.send(ipcTypes.toMain.updates.apply);
  };

  if (!isUpdateAvailable) {
    return null;
  }
  return (
    <Affix offsetTop={40} style={{ position: "absolute", right: 20 }}>
      <Card
        title={t("updates.available")}
        style={{
          maxWidth: 600,
          margin: "auto auto",
          borderRadius: 8,

          boxShadow: "0 4px 12px rgba(0, 0, 0, 0.15)",
        }}
      >
        <Space direction="vertical" style={{ width: "100%" }}>
          {updateProgress === 0 && (
            <Button onClick={handleDownload}>{t("updates.download")}</Button>
          )}
          <Progress
            percent={updateProgress}
            percentPosition={{ align: "center", type: "outer" }}
          />
          {!isUpdateComplete && formatSpeed(updateSpeed)}
          {isUpdateComplete && (
            <>
              <Button
                type="primary"
                loading={applyingUpdate}
                style={{ width: "100%" }}
                onClick={handleApply}
              >
                {applyingUpdate ? t("updates.applying") : t("updates.apply")}
              </Button>
              <Statistic.Countdown
                title="Auto update in:"
                format="mm:ss"
                style={{ width: "100%", textAlign: "center" }}
                value={Date.now() + 10 * 1000}
                onFinish={(): void => handleApply()}
              />
            </>
          )}
        </Space>
      </Card>
    </Affix>
  );
};

export default UpdateAvailable;

/**
 * Formats bytes into a human-readable string with appropriate units
 * @param bytes Number of bytes
 * @returns Formatted string with appropriate unit (B/KB/MB/GB)
 */
const formatSpeed = (bytes: number): string => {
  if (bytes === 0) return "0 B/s";

  const units = ["B/s", "KB/s", "MB/s", "GB/s"];
  const i = Math.floor(Math.log(bytes) / Math.log(1024));

  // Limit to available units and format with 2 decimal places (rounded)
  return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${units[i] || units[units.length - 1]}`;
};
