"use client";

import { useRef } from "react";
import { DashboardCards } from "./dashboardCards";
import { ExportButton } from "./ExportButton";
import { GenericChart, ChartDataItem } from "./GenericChart";
import { IncomingReportSection } from "./IncomingReportSection";
import UseDashboard from "../hooks/useDashboard";
import Loader from "../../components/Loader/loader";
import { useTranslation } from "react-i18next";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import DelegationView from "@/record-management/common/DelegationView";
import { useReportByHooks } from "../hooks/useReportByHooks";

// Color palettes
const APPROVAL_COLORS = {
  "In Progress": "var(--primary)",
  Accepted: "var(--primary-400)",
  Adjustment: "var(--primary)",
  Rejected: "var(--primary-300)",
  Approved: "var(--primary-400)",
};

const INCOMING_COLORS = {
  "In Progress": "var(--primary)",
  Accepted: "var(--primary-500)",
  Reassigned: "var(--primary-300)",
  Rejected: "var(--primary-300)",
};

const INTERNAL_COLORS = {
  "In Progress": "var(--primary)",
  Accepted: "var(--primary-500)",
  Reassigned: "var(--primary-300)",
  Rejected: "var(--primary-300)",
};

const EXTERNAL_COLORS = {
  "In Progress": "var(--primary)",
  Accepted: "var(--primary-500)",
  Reassigned: "var(--primary-300)",
  Rejected: "var(--primary-300)",
};

const OUTGOING_COLORS = {
  Draft: "var(--primary)",
  Submitted: "var(--primary-300)",
  Accepted: "var(--primary-500)",
  Approved: "var(--primary-400)",
  Rejected: "var(--primary-300)",
  Adjusted: "var(--primary)",
  Sent: "var(--primary-300)",
};

export function UserDashboard() {
  const { t } = useTranslation();
  const { userDetails } = useAuthUser();
  useReportByHooks();
  const dashboardRef = useRef<HTMLDivElement>(null);

  // Get current position ID from user details
  const currentPositionId = userDetails?.employee?.[0]?.positions?.[0]?.id;
  const {
    totalInternalAcceptedRecords,
    totalInProgressRecords,
    totalAcceptedRecords,
    totalInternalInProgressRecords,
    totalInternalReassignedRecords,
    totalInternalRejectedRecords,
    totalReassignedRecords,
    totalRejectedRecords,
    totalApproval,
    totalIncoming,
    totalOutgoing,
    isLoading,
  } = UseDashboard();

  const getTranslatedData = (
    data: Record<string, number>,
    colors: Record<string, string>,
  ) => {
    return Object.entries(data || {}).map(([name, value]) => ({
      name: t(`statusBar.${name}`),
      value,
      fill: colors[name as keyof typeof colors] || "var(--primary-400)",
    }));
  };

  const outgoingData = getTranslatedData(
    Object.fromEntries(
      (totalOutgoing || []).map((item) => [item.name, item.value]),
    ),
    OUTGOING_COLORS,
  );

  const incomingData = getTranslatedData(
    Object.fromEntries(
      (totalIncoming || []).map((item) => [item.name, item.value]),
    ),
    INCOMING_COLORS,
  );

  const approvalData = getTranslatedData(
    Object.fromEntries(
      (totalApproval || []).map((item) => [item.name, item.value]),
    ),
    APPROVAL_COLORS,
  );

  const internalData: ChartDataItem[] = [
    {
      name: t("statusBar.In Progress"),
      value: totalInternalInProgressRecords || 0,
      fill: INTERNAL_COLORS["In Progress"],
    },
    {
      name: t("statusBar.Accepted"),
      value: totalInternalAcceptedRecords || 0,
      fill: INTERNAL_COLORS["Accepted"],
    },
    {
      name: t("statusBar.Reassigned"),
      value: totalInternalReassignedRecords || 0,
      fill: INTERNAL_COLORS["Reassigned"],
    },
    {
      name: t("statusBar.Rejected"),
      value: totalInternalRejectedRecords || 0,
      fill: INTERNAL_COLORS["Rejected"],
    },
  ];

  const externalData: ChartDataItem[] = [
    {
      name: t("statusBar.In Progress"),
      value: totalInProgressRecords || 0,
      fill: EXTERNAL_COLORS["In Progress"],
    },
    {
      name: t("statusBar.Accepted"),
      value: totalAcceptedRecords || 0,
      fill: EXTERNAL_COLORS["Accepted"],
    },
    {
      name: t("statusBar.Reassigned"),
      value: totalReassignedRecords || 0,
      fill: EXTERNAL_COLORS["Reassigned"],
    },
    {
      name: t("statusBar.Rejected"),
      value: totalRejectedRecords || 0,
      fill: EXTERNAL_COLORS["Rejected"],
    },
  ];

  if (isLoading) {
    return (
      <div className="w-full h-full">
        <Loader />
      </div>
    );
  }
  const isDelegated = userDetails?.employee?.some((emp) =>
    emp.positions.some((pos) => pos.hasDelegated),
  );
  return isDelegated ? (
    <DelegationView />
  ) : (
    <div className="mt-5 bg-background text-foreground">
      <div className="mb-3 mt-3 flex w-full flex-wrap items-center justify-end gap-2 overflow-visible">
        <ExportButton dashboardRef={dashboardRef} />
      </div>

      <div ref={dashboardRef} className="flex flex-col w-full gap-4 sm:gap-6">
        <div className="chart-container">
          <DashboardCards />
        </div>

        <div className="w-full">
          <IncomingReportSection positionId={currentPositionId} />
        </div>

        <div className="grid w-full grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
          <GenericChart
            title={t("dashboard.approvalStats")}
            data={approvalData}
            colorLegend={APPROVAL_COLORS}
          />
          <GenericChart
            title={t("dashboard.externalIncomingRecords")}
            data={externalData}
            colorLegend={EXTERNAL_COLORS}
          />
        </div>

        <div className="grid w-full grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
          <GenericChart
            title={t("dashboard.internalIncomingRecords")}
            data={internalData}
            colorLegend={INTERNAL_COLORS}
          />
          <GenericChart
            title={t("dashboard.incomingStats")}
            data={incomingData}
            colorLegend={INCOMING_COLORS}
          />
        </div>

        <div className="grid w-full grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
          <GenericChart
            title={t("dashboard.outgoingStats")}
            data={outgoingData}
            colorLegend={OUTGOING_COLORS}
          />
        </div>
      </div>
    </div>
  );
}
