import LiveDateTime from "Components/LiveDateTime/LiveDateTime";
import { getAllDashboardDataAPI } from "Src/services/dashboardService";
import { updateProducerWorkOrderAPI } from "Src/services/producerWorkOrderService";
import { updateSurveyNotificationAPI } from "Src/services/surveyService";
import { getUserDetailsByIdAPI } from "Src/services/userService";
import { updateWorkOrderAPI } from "Src/services/workOrderService";
import {
  downloadAsZipFilesByWebLinks,
  downloadAsZipFilesGroupByFolder,
} from "Utils/utils";
import moment from "moment";
import React from "react";
import { useNavigate, Link } from "react-router-dom";
import { ClipLoader } from "react-spinners";
import { AuthContext, tokenExpireError } from "../authContext";
import { GlobalContext, showToast } from "../globalContext";
import { Download, DownloadIcon } from "lucide-react";
import MkdSDK from "Utils/MkdSDK";

const DashboardPage = () => {
  const navigate = useNavigate();
  const sdk = new MkdSDK();
  const { dispatch, state: authState } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const [isLoading, setIsLoading] = React.useState(true);
  const [openWorkOrders, setOpenWorkOrders] = React.useState([]);
  const [waitingWorkOrders, setWaitingWorkOrders] = React.useState([]);
  const [completedWorkOrders, setCompletedWorkOrders] = React.useState([]);
  const [currentWeekProjects, setCurrentWeekProjects] = React.useState([]);
  const [producerWorkOrderNotifications, setProducerWorkOrderNotifications] =
    React.useState([]);

  const [currentWeekProjectUrls, setCurrentWeekProjectUrls] = React.useState(
    []
  );

  const [
    currentWeekProjectUrlsGroupedByProgram,
    setCurrentWeekProjectUrlsGroupedByProgram,
  ] = React.useState([]);

  const [surveyNotifications, setSurveyNotifications] = React.useState([]);

  const statusMapping = [
    {
      id: 1,
      name: "Writer",
    },
    {
      id: 2,
      name: "Artist",
    },
    {
      id: 3,
      name: "Engineer",
    },
    {
      id: 4,
      name: "Rejected",
    },
    {
      id: 5,
      name: "Completed",
    },
    {
      id: 6,
      name: "Inactive",
    },
  ];

  const getAllDashboardData = async () => {
    try {
      const result = await getAllDashboardDataAPI();
      if (!result.error) {
        let openWorkOrders = [];
        let waitingWorkOrders = [];
        let completedWorkOrders = [];
        let currentWeekProjects = [];

        if (result.list.length > 0) {
          result.list.forEach((item) => {
            if (
              Number(item.status) === 1 &&
              Number(item.writer_submit_status) === 1 &&
              Number(item.is_viewed) === 0
            ) {
              waitingWorkOrders.push(item);
            }
            if (
              Number(item.status) === 1 ||
              Number(item.status) === 2 ||
              Number(item.status) === 3
            ) {
              openWorkOrders.push(item);
            }

            if (Number(item.status) === 5 && Number(item.is_viewed) === 0) {
              completedWorkOrders.push(item);
            }
          });

          // sort openWorkOrders by due_date asc and keep 10
          openWorkOrders = openWorkOrders
            .sort((a, b) => {
              return (
                new Date(a.due_date).getTime() - new Date(b.due_date).getTime()
              );
            })
            .slice(0, 10);

          setOpenWorkOrders(openWorkOrders);
          setWaitingWorkOrders(waitingWorkOrders);
          setCompletedWorkOrders(completedWorkOrders);
        }

        if (result.producer_work_orders.length > 0) {
          let producerWorkOrderNotifications =
            result.producer_work_orders.filter(
              (row) =>
                row.is_viewed === 0 ||
                (!row.is_viewed && row.producer_submit_status === 1)
            );
          setProducerWorkOrderNotifications(producerWorkOrderNotifications);
        }

        if (result.current_week_projects.length > 0) {
          const currentWeek = moment().week();
          //
          result.current_week_projects.forEach((item) => {
            const itemWeek = moment(item.mix_date).week();
            //
            if (itemWeek === currentWeek) {
              currentWeekProjects.push(item);
            }
          });

          // sort the currentWeekProjects by mix_date asc
          currentWeekProjects = currentWeekProjects.sort((a, b) => {
            return (
              new Date(a.mix_date).getTime() - new Date(b.mix_date).getTime()
            );
          });

          // item.urls is already an array
          let allUrls = currentWeekProjects.map((item) => item.urls).flat();
          setCurrentWeekProjectUrls(allUrls);
          setCurrentWeekProjects(currentWeekProjects);

          let allUrlsGroupedByProgram = [];
          currentWeekProjects.forEach((row) => {
            allUrlsGroupedByProgram.push({
              file_name: row.program_name + "_" + row.team_name,
              urls: row.urls,
            });
          });
          setCurrentWeekProjectUrlsGroupedByProgram(allUrlsGroupedByProgram);
        }

        // TODO: survey notifications
        if (result.survey_notifications.length > 0) {
          setSurveyNotifications(result.survey_notifications);
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleDownloadFiles = async (urlsArr, fileName) => {
    try {
      if (urlsArr.length > 0) {
        let urls = urlsArr.map((item) => item.url);
        showToast(globalDispatch, "File download has started", 5000);
        await downloadAsZipFilesByWebLinks(urls, fileName);
      } else {
        showToast(globalDispatch, "No files found", 5000, "error");
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  const handleDownloadAllFiles = async () => {
    try {
      if (currentWeekProjectUrls.length > 0) {
        const zipFileName = `All_files_${moment().format(
          "HH:mm:ss_DD-MM-YYYY"
        )}`;
        showToast(globalDispatch, "File download has been started", 5000);
        if (currentWeekProjectUrlsGroupedByProgram.length > 0) {
          await downloadAsZipFilesGroupByFolder(
            currentWeekProjectUrlsGroupedByProgram,
            zipFileName
          );
        } else {
          showToast(globalDispatch, "No files found", 5000, "info");
        }
      } else {
        showToast(globalDispatch, "No files found", 5000, "error");
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  const handleWaitingWorkOrderClick = async (workOrderId) => {
    try {
      setIsLoading(true);
      const result = await updateWorkOrderAPI({
        id: workOrderId,
        is_viewed: 1,
      });
      if (!result.error) {
        setIsLoading(false);
        navigate(`/${authState.role}/edit-work-order/${workOrderId}`);
      } else {
        setIsLoading(false);
        showToast(globalDispatch, result.message, 5000, "error");
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleCompletedWorkOrderClick = async (workOrderId) => {
    try {
      setIsLoading(true);
      const result = await updateWorkOrderAPI({
        id: workOrderId,
        is_viewed: 1,
      });
      if (!result.error) {
        setIsLoading(false);
        navigate(`/${authState.role}/edit-work-order/${workOrderId}`);
      } else {
        setIsLoading(false);
        showToast(globalDispatch, result.message, 5000, "error");
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleCompletedProducerWorkOrderClick = async (id, projectId) => {
    try {
      setIsLoading(true);
      const result = await updateProducerWorkOrderAPI({
        id,
        is_viewed: 1,
      });
      if (!result.error) {
        setIsLoading(false);
        localStorage.setItem("projectClientId", "");
        localStorage.setItem("projectTeamName", "");
        localStorage.setItem("projectMixTypeId", "");
        localStorage.setItem("projectMixDateStart", "");
        localStorage.setItem("projectMixDateEnd", "");
        localStorage.setItem("projectPageSize", "");

        navigate(`/${authState.role}/view-project/${projectId}`);
      } else {
        setIsLoading(false);
        showToast(globalDispatch, result.message, 5000, "error");
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleSeenSurveyClick = async (id, projectId) => {
    try {
      setIsLoading(true);
      const result = await updateSurveyNotificationAPI({
        id: id,
        is_seen: 1,
      });
      if (!result.error) {
        setIsLoading(false);
        localStorage.setItem("projectClientId", "");
        localStorage.setItem("projectTeamName", "");
        localStorage.setItem("projectMixTypeId", "");
        localStorage.setItem("projectMixDateStart", "");
        localStorage.setItem("projectMixDateEnd", "");
        localStorage.setItem("projectPageSize", "");
        navigate(`/${authState.role}/view-project/${projectId}`);
      } else {
        setIsLoading(false);
        showToast(globalDispatch, result.message, 5000, "error");
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "dashboard",
      },
    });

    const userId = localStorage.getItem("user");

    if (userId) {
      (async function () {
        setIsLoading(true);
        try {
          // Check subscription status first
          const result = await getUserDetailsByIdAPI(userId);
          if (!result.error && result.model) {
            dispatch({
              type: "SET_PROFILE",
              payload: {
                photo: result.model.photo,
                companyName: result.model.company_name,
              },
            });

            // Store subscription status
            localStorage.setItem("UserSubscription", result.model.subscription);
          }

          // If no subscription, redirect to onboarding

          // Only fetch dashboard data if user has subscription
          localStorage.setItem("subscribed", "");
          await getAllDashboardData();
        } catch (error) {
          tokenExpireError(dispatch, error.message);
        } finally {
          setIsLoading(false);
        }
      })();
    }
  }, []);

  return (
    <>
      {isLoading ? (
        <div className="flex h-[calc(100vh-160px)] w-full items-center justify-center">
          <ClipLoader color="#fff" size={30} />
        </div>
      ) : (
        <div className="p-4 h-full max-w-screen xl:p-8">
          <div className="flex flex-row justify-between items-center p-5 mb-8 w-full rounded-md border shadow border-boxdark bg-boxdark">
            <h5 className="mb-2 text-2xl font-bold text-white">
              Welcome, {authState.userName ?? "User"}!
            </h5>
            <LiveDateTime />
          </div>
          {/* Waiting Work Orders */}
          {waitingWorkOrders && waitingWorkOrders.length > 0 && (
            <div className="flex overflow-x-auto gap-4 mb-8 w-full custom-overflow">
              {waitingWorkOrders.map((item, index) => (
                <div
                  key={index}
                  className="shadow-default min-w-[300px] flex-shrink-0 rounded border border-warning bg-warning/10 p-5 dark:border-warning"
                >
                  <h3 className="mb-2 text-lg font-semibold text-white">
                    To-Do:
                  </h3>
                  <p className="mb-2 text-base text-gray-300">
                    Waiting Approval
                  </p>
                  <p className="text-base text-white">
                    Work Order:{" "}
                    <button
                      onClick={(e) => {
                        e.preventDefault();
                        handleWaitingWorkOrderClick(item.id);
                      }}
                      className="font-medium text-blue-500 hover:text-blue-500/80"
                    >
                      {item.workorder_code}
                    </button>
                  </p>
                </div>
              ))}
            </div>
          )}

          {/* Completed Work Orders */}
          {completedWorkOrders && completedWorkOrders.length > 0 && (
            <div className="mb-8">
              <div className="flex justify-between items-center mb-2">
                <h3 className="text-lg font-semibold text-white">
                  Completed Work Orders
                </h3>
                <span className="rounded-full bg-success/10 px-2.5 py-0.5 text-xs font-medium text-success">
                  {completedWorkOrders.length} New
                </span>
              </div>
              <div className="flex overflow-x-auto gap-2 w-full custom-overflow">
                {completedWorkOrders.map((item, index) => (
                  <div
                    key={index}
                    className="shadow-default h-[84px] min-w-[160px] flex-shrink-0 rounded border border-strokedark bg-boxdark p-3 dark:border-strokedark"
                  >
                    <p className="mb-1 text-sm text-gray-300">
                      {item?.writer_name} for {item?.artist_name}
                    </p>
                    <button
                      onClick={(e) => {
                        e.preventDefault();
                        handleCompletedWorkOrderClick(item.id);
                      }}
                      className="text-sm font-medium text-blue-500 hover:text-blue-500/80"
                    >
                      {item.workorder_code}
                    </button>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Producer Work Order Notifications */}
          {producerWorkOrderNotifications &&
            producerWorkOrderNotifications.length > 0 && (
              <div className="mb-8">
                <div className="flex justify-between items-center mb-2">
                  <h3 className="text-lg font-semibold text-white">
                    Producer Work Orders
                  </h3>
                  <span className="rounded-full bg-success/10 px-2.5 py-0.5 text-xs font-medium text-success">
                    {producerWorkOrderNotifications.length} New
                  </span>
                </div>
                <div className="flex overflow-x-auto gap-2 w-full custom-overflow">
                  {producerWorkOrderNotifications.map((row, index) => (
                    <div
                      key={index}
                      className="shadow-default h-[84px] min-w-[160px] flex-shrink-0 rounded border border-strokedark bg-boxdark p-3 dark:border-strokedark"
                    >
                      <p className="mb-1 text-sm text-gray-300">
                        Producer Review
                      </p>
                      <button
                        onClick={(e) => {
                          e.preventDefault();
                          handleCompletedProducerWorkOrderClick(
                            row.id,
                            row.project_id
                          );
                        }}
                        className="text-sm font-medium text-blue-500 hover:text-blue-500/80"
                      >
                        {row.workorder_code}
                      </button>
                    </div>
                  ))}
                </div>
              </div>
            )}

          {/* Survey Notifications */}
          {surveyNotifications && surveyNotifications.length > 0 && (
            <div className="mb-8">
              <div className="flex justify-between items-center mb-2">
                <h3 className="text-lg font-semibold text-white">
                  Survey Submissions
                </h3>
                <span className="rounded-full bg-success/10 px-2.5 py-0.5 text-xs font-medium text-success">
                  {surveyNotifications.length} New
                </span>
              </div>
              <div className="flex overflow-x-auto gap-2 w-full custom-overflow">
                {surveyNotifications.map((row, index) => (
                  <div
                    key={index}
                    className="shadow-default h-[84px] min-w-[160px] flex-shrink-0 rounded border border-strokedark bg-boxdark p-3 dark:border-strokedark"
                  >
                    <button
                      onClick={(e) => {
                        e.preventDefault();
                        handleSeenSurveyClick(row.id, row.project_id);
                      }}
                      className="text-sm font-medium text-blue-500 hover:text-blue-500/80"
                    >
                      {row.program_name} - {row.team_name}
                    </button>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Main Dashboard Content */}
          <div className="flex flex-col gap-4 mb-4 w-full md:flex-row">
            {/* Open Work Orders */}
            <div className="overflow-y-auto p-5 w-full h-96 rounded border custom-overflow shadow-default border-strokedark bg-boxdark md:w-1/2 dark:border-strokedark">
              <div className="flex justify-between items-center mb-4">
                <h3 className="text-lg font-semibold text-white">
                  Pending Work Orders
                </h3>
              </div>
              <table className="w-full table-auto">
                <thead className="bg-meta-4">
                  <tr>
                    <th className="px-4 py-2.5 text-left text-xs font-medium uppercase tracking-wider text-bodydark1">
                      ID
                    </th>
                    <th className="px-4 py-2.5 text-left text-xs font-medium uppercase tracking-wider text-bodydark1">
                      Due Date
                    </th>
                    <th className="px-4 py-2.5 text-center text-xs font-medium uppercase tracking-wider text-bodydark1">
                      Status
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {openWorkOrders && openWorkOrders.length > 0 ? (
                    openWorkOrders.map((row, index) => {
                      let dueDateCount = 0;
                      if (row.due_date) {
                        const dueDate = moment(row.due_date);
                        const today = moment();
                        dueDateCount = dueDate.diff(today, "days");
                      }

                      let statusStr = "";
                      if (
                        row.writer_submit_status === 1 &&
                        row.artist_id === row.engineer_id
                      ) {
                        statusStr = "Artist/Engineer";
                      } else if (
                        row.auto_approve &&
                        row.auto_approve === 1 &&
                        row.writer_id === row.artist_id &&
                        row.writer_id !== row.engineer_id
                      ) {
                        if (row.status === 1) {
                          statusStr = "Writer/Artist";
                        } else if (row.status === 3) {
                          statusStr = "Engineer";
                        } else if (row.status === 5) {
                          statusStr = "Completed";
                        }
                      } else if (
                        row.auto_approve &&
                        row.auto_approve === 1 &&
                        row.writer_id === row.artist_id &&
                        row.writer_id === row.engineer_id
                      ) {
                        if (row.status === 1) {
                          statusStr = "Wri/Art/Eng";
                        } else if (row.status === 5) {
                          statusStr = "Completed";
                        }
                      } else {
                        statusMapping.map((statusItem) => {
                          if (Number(statusItem.id) === Number(row.status)) {
                            statusStr = statusItem.name;
                          }
                        });
                      }

                      return (
                        <tr key={index} className="border-b border-strokedark">
                          <td className="px-4 py-4">
                            <Link
                              to={`/${authState.role}/edit-work-order/${row.id}`}
                              className="font-medium text-blue-500 hover:text-blue-500/80"
                            >
                              {row.workorder_code}
                            </Link>
                            <p className="mt-1 text-sm text-gray-400">
                              {row.writer_name} for {row.artist_name}
                            </p>
                          </td>
                          <td className="px-4 py-4">
                            <p className="text-white">
                              {moment(row.due_date).format("MM/DD/YYYY")}
                            </p>
                            <p className="mt-1 text-sm text-gray-400">
                              ({dueDateCount} days)
                            </p>
                          </td>
                          <td className="px-4 py-4 text-center">
                            <span className="rounded-md bg-meta-4 px-2.5 py-0.5 text-sm font-medium text-white">
                              {statusStr}
                            </span>
                          </td>
                        </tr>
                      );
                    })
                  ) : (
                    <tr>
                      <td
                        colSpan="3"
                        className="px-4 py-4 text-center text-gray-400"
                      >
                        No pending work orders found
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>

            <div className="overflow-y-auto p-5 w-full h-96 rounded border custom-overflow shadow-default border-strokedark bg-boxdark md:w-1/2 dark:border-strokedark">
              <div className="flex justify-between items-center mb-4">
                <h3 className="text-lg font-semibold text-white">
                  This Week's Projects
                </h3>
                <button
                  className="text-base font-medium text-white hover:text-blue-500"
                  onClick={handleDownloadAllFiles}
                >
                  Download all
                </button>
              </div>
              <table className="w-full table-auto">
                <thead className="bg-meta-4">
                  <tr>
                    <th className="px-4 py-2.5 text-left text-xs font-medium uppercase tracking-wider text-bodydark1">
                      Date
                    </th>
                    <th className="px-4 py-2.5 text-left text-xs font-medium uppercase tracking-wider text-bodydark1">
                      Program/Team
                    </th>
                    <th className="px-4 py-2.5 text-center text-xs font-medium uppercase tracking-wider text-bodydark1">
                      Action
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {currentWeekProjects && currentWeekProjects.length > 0 ? (
                    currentWeekProjects.map((item, index) => (
                      <tr key={index} className="border-b border-strokedark">
                        <td className="px-4 py-4">
                          <div className="flex items-center">
                            <span className="text-white">
                              {moment(item.mix_date).format("M.DD")}
                            </span>
                            <span className="ml-2 text-sm text-gray-400 uppercase">
                              {moment(item.mix_date).format("ddd")}
                            </span>
                          </div>
                        </td>
                        <td className="px-4 py-4">
                          <Link
                            to={`/${authState.role}/view-project/${item.id}`}
                            className="font-medium text-blue-500 hover:text-blue-500/80"
                            onClick={() => {
                              localStorage.setItem("projectClientId", "");
                              localStorage.setItem("projectTeamName", "");
                              localStorage.setItem("projectMixTypeId", "");
                              localStorage.setItem("projectMixDateStart", "");
                              localStorage.setItem("projectMixDateEnd", "");
                              localStorage.setItem("projectPageSize", "");
                            }}
                          >
                            <p className="text-gray-400">{item.program_name}</p>
                            <p className="text-white">{item.team_name}</p>
                          </Link>
                        </td>
                        <td className="px-4 py-4 text-center">
                          <button
                            onClick={(e) => {
                              e.preventDefault();
                              handleDownloadFiles(
                                item.urls,
                                `${item.program_name}_${
                                  item.team_name
                                }_files_${moment().format(
                                  "HH:mm:ss_DD-MM-YYYY"
                                )}`
                              );
                            }}
                            className="inline-flex items-center text-white hover:text-blue-500"
                          >
                            <DownloadIcon className="w-5 h-5" />
                          </button>
                        </td>
                      </tr>
                    ))
                  ) : (
                    <tr>
                      <td
                        colSpan="3"
                        className="px-4 py-4 text-center text-gray-400"
                      >
                        No current week projects found
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default DashboardPage;
