import { SyncOutlined } from "@ant-design/icons";
import { PageHeader } from "@ant-design/pro-layout";
import { useApolloClient } from "@apollo/client/react";
import { Button, Skeleton, Space } from "antd";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { generate_UPDATE_JOB_KANBAN } from "../../graphql/jobs.queries";
import { insertAuditTrail } from "../../redux/application/application.actions";
import { selectBodyshop } from "../../redux/user/user.selectors";
import AuditTrailMapping from "../../utils/AuditTrailMappings";
import IndefiniteLoading from "../indefinite-loading/indefinite-loading.component";
import ProductionBoardFilters from "../production-board-filters/production-board-filters.component";
import ProductionListDetailComponent from "../production-list-detail/production-list-detail.component";
import ProductionListPrint from "../production-list-table/production-list-print.component.jsx";
import CardColorLegend from "./production-board-kanban-card-color-legend.component.jsx";
import "./production-board-kanban.styles.scss";
import { createBoardData } from "./production-board-kanban.utils.js";
import { defaultFilters, mergeWithDefaults } from "./settings/defaultKanbanSettings.js";
import ProductionBoardKanbanSettings from "./settings/production-board-kanban.settings.component.jsx";
import Board from "./trello-board/index";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

const mapDispatchToProps = (dispatch) => ({
  insertAuditTrail: ({ jobid, operation, type }) =>
    dispatch(
      insertAuditTrail({
        jobid,
        operation,
        type
      })
    )
});

function ProductionBoardKanbanComponent({ data, bodyshop, refetch, insertAuditTrail, associationSettings, statuses }) {
  const [boardLanes, setBoardLanes] = useState({ lanes: [] });
  const [filter, setFilter] = useState(defaultFilters);
  const [loading, setLoading] = useState(true);
  const [isMoving, setIsMoving] = useState(false);
  const [orientation, setOrientation] = useState("vertical");
  const notification = useNotification();

  const { t } = useTranslation();
  const client = useApolloClient();

  useEffect(() => {
    if (associationSettings) {
      setLoading(true);
      setOrientation(associationSettings?.kanban_settings?.orientation ? "vertical" : "horizontal");
      setLoading(false);
    }
  }, [associationSettings]);

  useEffect(() => {
    setIsMoving(true);
    const newBoardData = createBoardData({
      statuses,
      data,
      filter,
      cardSettings: associationSettings?.kanban_settings
    });

    newBoardData.lanes = newBoardData.lanes.map((lane) => ({
      ...lane,
      title: `${lane.title} (${lane.cards.length})`
    }));

    setBoardLanes(newBoardData);
    setIsMoving(false);
  }, [data, bodyshop.md_ro_statuses, filter, statuses, associationSettings?.kanban_settings]);

  const getCardByID = (data, cardId) => {
    for (const lane of data.lanes) {
      for (const card of lane.cards) {
        if (card.id === cardId) {
          return card;
        }
      }
    }
    return null;
  };

  const onDragEnd = async ({ type, source, destination, draggableId }) => {
    logImEXEvent("kanban_drag_end");

    if (!type || type !== "lane" || !source || !destination || isMoving) return;

    setIsMoving(true);

    const targetLane = boardLanes.lanes.find((lane) => lane.id === destination.droppableId);
    const sourceLane = boardLanes.lanes.find((lane) => lane.id === source.droppableId);

    if (!targetLane || !sourceLane) {
      setIsMoving(false);
      console.error("Invalid source or destination lane");
      return;
    }

    const sameColumnTransfer = source.droppableId === destination.droppableId;
    const sourceCard = getCardByID(boardLanes, draggableId);

    const movedCardWillBeFirst = destination.index === 0;
    const movedCardWillBeLast = destination.index >= targetLane.cards.length - 1;

    const lastCardInTargetLane = targetLane.cards[targetLane.cards.length - 1];
    const oldChildCard = sourceLane.cards[source.index + 1];

    const newChildCard = movedCardWillBeLast
      ? null
      : targetLane.cards[
          sameColumnTransfer
            ? source.index < destination.index
              ? destination.index + 1
              : destination.index
            : destination.index
        ];

    const oldChildCardNewParent = oldChildCard ? sourceCard.metadata.kanbanparent : null;

    let movedCardNewKanbanParent;
    if (movedCardWillBeFirst) {
      movedCardNewKanbanParent = "-1";
    } else if (movedCardWillBeLast) {
      movedCardNewKanbanParent = lastCardInTargetLane.id;
    } else if (newChildCard) {
      movedCardNewKanbanParent = newChildCard.metadata.kanbanparent;
    } else {
      console.error("==> !!!!!!Couldn't find a parent.!!!! <==");
    }

    const newChildCardNewParent = newChildCard ? draggableId : null;

    try {
      const update = await client.mutate({
        mutation: generate_UPDATE_JOB_KANBAN(
          oldChildCard ? oldChildCard.id : null,
          oldChildCardNewParent,
          draggableId,
          movedCardNewKanbanParent,
          targetLane.id,
          newChildCard ? newChildCard.id : null,
          newChildCardNewParent
        )
      });

      insertAuditTrail({
        jobid: draggableId,
        operation: AuditTrailMapping.jobstatuschange(targetLane.id),
        type: "jobstatuschange"
      });

      if (update.errors) {
        notification.error({
          title: t("production.errors.boardupdate", {
            message: JSON.stringify(update.errors)
          })
        });
      }
    } catch (error) {
      notification.error({
        title: t("production.errors.boardupdate", {
          message: error.message
        })
      });
    } finally {
      setIsMoving(false);
    }
  };

  const cardSettings = mergeWithDefaults(associationSettings?.kanban_settings);

  const handleSettingsChange = () => {
    setFilter(defaultFilters);
  };

  if (loading) {
    return <Skeleton active />;
  }

  return (
    <div>
      <IndefiniteLoading loading={isMoving} />
      <PageHeader
        title={cardSettings.cardcolor && <CardColorLegend cardSettings={cardSettings} bodyshop={bodyshop} />}
        style={{ paddingInline: 0, paddingBlock: 0 }}
        extra={
          <Space wrap>
            <Button onClick={() => refetch && refetch()} icon={<SyncOutlined />} />
            <ProductionBoardFilters filter={filter} setFilter={setFilter} loading={isMoving} />
            <ProductionBoardKanbanSettings
              parentLoading={setLoading}
              associationSettings={associationSettings}
              onSettingsChange={handleSettingsChange}
              bodyshop={bodyshop}
              data={data}
            />
            <ProductionListPrint />
          </Space>
        }
      />

      <ProductionListDetailComponent jobs={data} />

      <Board
        queryData={data}
        data={boardLanes}
        onDragEnd={onDragEnd}
        orientation={orientation}
        cardSettings={cardSettings}
      />
    </div>
  );
}

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