import { Button, Card, Col, notification, Row, Select, Space } from "antd";
import React, { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import SocketIO from "socket.io-client";
import DmsAllocationsSummaryApComponent from "../../components/dms-allocations-summary-ap/dms-allocations-summary-ap.component";
import DmsLogEvents from "../../components/dms-log-events/dms-log-events.component";
import { auth } from "../../firebase/firebase.utils";
import { setBreadcrumbs, setSelectedHeader } from "../../redux/application/application.actions";
import { selectBodyshop } from "../../redux/user/user.selectors";
import InstanceRenderManager from "../../utils/instanceRenderMgr";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});

const mapDispatchToProps = (dispatch) => ({
  setBreadcrumbs: (breadcrumbs) => dispatch(setBreadcrumbs(breadcrumbs)),
  setSelectedHeader: (key) => dispatch(setSelectedHeader(key))
});

export default connect(mapStateToProps, mapDispatchToProps)(DmsContainer);

export const socket = SocketIO(import.meta.env.PROD ? import.meta.env.VITE_APP_AXIOS_BASE_API_URL : "", {
  path: "/ws",
  withCredentials: true,
  auth: async (callback) => {
    const token = auth.currentUser && (await auth.currentUser.getIdToken());
    callback({ token });
  }
});

export function DmsContainer({ bodyshop, setBreadcrumbs, setSelectedHeader }) {
  const { t } = useTranslation();
  const [logLevel, setLogLevel] = useState("DEBUG");
  const history = useNavigate();
  const [logs, setLogs] = useState([]);

  const { state } = useLocation();

  const logsRef = useRef(null);

  useEffect(() => {
    document.title = t("titles.dms", {
      app: InstanceRenderManager({
        imex: "$t(titles.imexonline)",
        rome: "$t(titles.romeonline)",
        promanager: "$t(titles.promanager)"
      })
    });
    setSelectedHeader("dms");
    setBreadcrumbs([
      {
        link: "/manage/accounting/payables",
        label: t("titles.bc.accounting-payables")
      },
      {
        link: "/manage/dms",
        label: t("titles.bc.dms")
      }
    ]);
  }, [t, setBreadcrumbs, setSelectedHeader]);

  useEffect(() => {
    socket.on("connect", () => socket.emit("set-log-level", logLevel));
    socket.on("reconnect", () => {
      setLogs((logs) => {
        return [
          ...logs,
          {
            timestamp: new Date(),
            level: "WARNING",
            message: "Reconnected to CDK Export Service"
          }
        ];
      });
    });

    socket.on("log-event", (payload) => {
      setLogs((logs) => {
        return [...logs, payload];
      });
    });

    socket.on("ap-export-complete", (payload) => {
      notification.open({
        type: "success",
        message: t("jobs.labels.dms.apexported")
      });
    });

    if (socket.disconnected) socket.connect();
    return () => {
      socket.removeAllListeners();
      socket.disconnect();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (!state?.billids) {
    history(`/manage/accounting/payables`);
  }

  return (
    <Row gutter={[16, 16]}>
      <Col md={24} lg={12}>
        <DmsAllocationsSummaryApComponent socket={socket} billids={state?.billids} />
      </Col>

      <Col md={24} lg={12}>
        <div ref={logsRef}>
          <Card
            title={t("jobs.labels.dms.logs")}
            extra={
              <Space wrap>
                <Select
                  placeholder="Log Level"
                  value={logLevel}
                  onChange={(value) => {
                    setLogLevel(value);
                    socket.emit("set-log-level", value);
                  }}
                >
                  <Select.Option key="TRACE">TRACE</Select.Option>
                  <Select.Option key="DEBUG">DEBUG</Select.Option>
                  <Select.Option key="INFO">INFO</Select.Option>
                  <Select.Option key="WARNING">WARNING</Select.Option>
                  <Select.Option key="ERROR">ERROR</Select.Option>
                </Select>
                <Button onClick={() => setLogs([])}>Clear Logs</Button>
                <Button
                  onClick={() => {
                    setLogs([]);

                    socket.disconnect();
                    socket.connect();
                  }}
                >
                  Reconnect
                </Button>
              </Space>
            }
          >
            <DmsLogEvents socket={socket} logs={logs} />
          </Card>
        </div>
      </Col>
    </Row>
  );
}

export const determineDmsType = (bodyshop) => {
  if (bodyshop.cdk_dealerid) return "cdk";
  else {
    return "pbs";
  }
};
