/**
 * @deprecated 25/03/25 - moved back to Central - out of scope
 */
import React from "react";

import OSLabel from "../OSLabel/OSLabel";
import { Calendar } from "primereact/calendar";
import OSActionButton, {
  OSActionButtonType,
} from "../OSActionButton/OSActionButton";
import { Skeleton } from "primereact/skeleton";
import { useState, useEffect } from "react";
import { Nullable } from "primereact/ts-helpers";
import { goPost } from "../../utils/goFetch";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend,
} from "chart.js";
import { Bar } from "react-chartjs-2";
import { AccessEventDataSet, VisitDataSet } from "./types";

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
);

interface Props {
  users: string[];
}

/**
 * @deprecated 25/03/25 - moved back to Central - out of scope
 */
const AccessVisitGraphs: React.FC<Props> = ({ ...props }) => {
  const [dateRange, setDateRange] = useState<Nullable<Date[]>>([]);
  const [accessEventDataSet, setAccessEventDataSet] =
    useState<AccessEventDataSet[]>();
  const [visitDataSet, setVisitDataSet] = useState<VisitDataSet[]>();

  const getAccessEventsBody = () => {
    return {
      users: props.users,
      dateRange: dateRange,
    };
  };

  const getVisitStatsBody = () => {
    return {
      users: props.users,
      dateRange: dateRange,
    };
  };

  useEffect(() => {
    goPost(`/frontend/insights/access-event-stats`, getAccessEventsBody())
      .then((response) => {
        const responseData = response as { data: AccessEventDataSet[] };
        setAccessEventDataSet(responseData.data);
      })
      .catch((e) => {
        console.error(e);
      });
  }, [dateRange]);

  useEffect(() => {
    goPost(`/frontend/insights/visit-stats`, getVisitStatsBody())
      .then((response) => {
        const responseData = response as { data: VisitDataSet[] };
        setVisitDataSet(responseData.data);
      })
      .catch((e) => {
        console.error(e);
      });
  }, [dateRange]);

  const accessEventLabels = Array.from({ length: 25 }, (_, i) => {
    return `${i.toString().padStart(2, "0")}`;
  });

  const getAccessEventValue = (direction: number) => {
    return accessEventLabels.map((label) => {
      const exists = accessEventDataSet?.find((row) => {
        if (
          row.direction === direction &&
          row.time.toString().padStart(2, "0") === label
        ) {
          return row;
        }
      });
      if (exists !== undefined) {
        if (exists.direction === direction) {
          return exists.count;
        }
        return 0;
      } else {
        return 0;
      }
    });
  };

  const accessEventGraph = () => {
    const accessEventOptions = {
      plugins: {
        title: {
          display: false,
        },
      },
      responsive: true,
      scales: {
        x: {
          stacked: true,
          grid: {
            display: false,
          },
          ticks: {
            font: {
              family: "Poppins",
              size: 11,
            },
            color: "black",
            stepSize: 1,
          },
          title: {
            display: true,
            text: "Time of Day",
            font: {
              family: "Poppins",
              size: 14,
            },
            color: "black",
          },
        },
        y: {
          stacked: true,
          grid: {
            display: false,
          },
          ticks: {
            font: {
              family: "Poppins",
              size: 11,
            },
            color: "black",
          },
          title: {
            display: true,
            text: "Access Events",
            font: {
              family: "Poppins",
              size: 14,
            },
            color: "black",
          },
        },
      },
    };

    const entries = getAccessEventValue(0);
    const exits = getAccessEventValue(1);
    const unknown = getAccessEventValue(2);

    const accessEventData = {
      labels: accessEventLabels,
      datasets: [
        {
          label: "Entries",
          data: entries,
          backgroundColor: "rgba(153, 100, 250, 0.3)",
          borderColor: "rgb(153, 100, 250)",
          borderWidth: 1,
        },
        {
          label: "Unknown",
          data: unknown,
          backgroundColor: "rgba(252, 153, 202, 0.3)",
          borderColor: "rgb(252, 153, 202)",
          borderWidth: 1,
        },
        {
          label: "Exits",
          data: exits,
          borderColor: "rgb(156, 203, 252)",
          backgroundColor: "rgba(156, 203, 252, 0.3)",
          borderWidth: 1,
        },
      ],
    };

    return (
      <>
        <Bar options={accessEventOptions} data={accessEventData} />
      </>
    );
  };

  const visitGraph = () => {
    const visitLabels = visitDataSet?.map((visitData) => {
      return visitData.address;
    });

    const visitOptions = {
      indexAxis: "y" as const,
      responsive: true,
      plugins: {
        legend: {
          position: "right" as const,
        },
        title: {
          display: false,
        },
      },
      scales: {
        x: {
          ticks: {
            font: {
              family: "Poppins",
              size: 11,
            },
            color: "black",
            stepSize: 1,
          },
          title: {
            display: true,
            text: "Visits Generated",
            font: {
              family: "Poppins",
              size: 14,
            },
            color: "black",
          },
        },
        y: {
          ticks: {
            font: {
              family: "Poppins",
              size: 11,
            },
            color: "black",
          },
          title: {
            display: true,
            text: "Property",
            font: {
              family: "Poppins",
              size: 14,
            },
            color: "black",
          },
        },
      },
    };

    const visitData = {
      labels: visitLabels,
      datasets: [
        {
          label: "Visit Count",
          data: visitLabels?.map((visitLabel) => {
            const visits = visitDataSet?.find((visitData) => {
              if (visitData.address === visitLabel) {
                return visitData;
              }
            })?.count;
            return visits;
          }),
          borderColor: "rgb(108, 204, 110)",
          backgroundColor: "rgba(108, 204, 110, 0.2)",
          borderWidth: 1,
        },
      ],
    };

    return (
      <>
        <Bar options={visitOptions} data={visitData} />
      </>
    );
  };

  return (
    <div className="flex p-5 w-full">
      <div className="flex flex-col gap-10 w-full">
        <div className="flex flex-col justify-center gap-2">
          <OSLabel
            props={{
              label: "Filter by Date",
              labelColor: "var(--main-colour)",
              labelWeight: 500,
              labelFontSize: "1.4rem",
              primaryIcon: "calendar-range",
              width: "auto",
              style: { marginLeft: "0.5rem" },
            }}
          />
          <Calendar
            dateFormat="d MM yy"
            value={dateRange}
            onChange={(e) => setDateRange(e.value as Date[])}
            selectionMode="range"
            readOnlyInput
            hideOnRangeSelection
            onSelect={() => {}}
            className="md:w-3/10 xs:w-8/10"
          />
        </div>
        <div className="flex">
          <div className="grid grid-cols-2 gap-10 w-full">
            {accessEventDataSet !== undefined ? (
              <div className="flex flex-col justify-center gap-10 xs:col-span-2 xl:col-span-1">
                {accessEventGraph()}
                <div className="flex justify-center">
                  <OSActionButton
                    props={{
                      type: OSActionButtonType.Secondary,
                      label: "Generate Access Report",
                      primaryIconEnabled: true,
                      primaryIcon: "file-invoice",
                      onClick: () => {},
                    }}
                  />
                </div>
              </div>
            ) : (
              <Skeleton height="25rem" />
            )}
            {visitDataSet !== undefined ? (
              <div className="flex flex-col justify-center gap-10 xs:col-span-2 xl:col-span-1">
                {visitGraph()}
                <div className="flex justify-center">
                  <OSActionButton
                    props={{
                      type: OSActionButtonType.Secondary,
                      label: "Generate Visit Report",
                      primaryIconEnabled: true,
                      primaryIcon: "file-invoice",
                      onClick: () => {},
                    }}
                  />
                </div>
              </div>
            ) : (
              <Skeleton height="25rem" />
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default AccessVisitGraphs;
