"use client";

import Container from "@mui/material/Container";
import Typography from "@mui/material/Typography";

import { paths } from "@/routes/paths";

import { useSettingsContext } from "@/shared/components/settings";
import CustomBreadcrumbs from "@/components/custom-breadcrumbs";
import Iconify from "@/shared/components/iconify";
import { useCallback, useEffect, useState } from "react";
import {
  Avatar,
  Button,
  Checkbox,
  IconButton,
  Stack,
  Tab,
  Tabs,
  Tooltip,
  useTheme,
} from "@mui/material";
import { IProjectItem, Project, collaborator } from "@/contexts/types/Project";
import { RouterLink } from "@/routes";
import AllTasksProjectView from "./tasks-project-list";
import { useSnackbar } from "@/components/snackbar";
import { useBoolean, useCopyToClipboard, useRouter } from "@/hooks";
import {
  ITaskItem,
  ITaskTableFilterValue,
  ITaskTableFilters,
} from "@/contexts/types/tasks";
import { isAfter, isBetween } from "@/utils/format-time";
import { getComparator } from "@/components/table/utils";
import {
  TASK_SORT_OPTIONS,
  TASK_TYPE_OPTIONS,
  _Participants,
  _managers,
  _tasks,
} from "@/shared/_mock";
import useTable from "@/components/table/use-table";
import TaskSearch from "../all-tasks/task-search";
import TaskFilters from "../all-tasks/task-filters";
import TaskSort from "../all-tasks/task-sort";
import TaskFiltersResult from "../all-tasks/task-filters-result";
import LocalizationProvider from "@/locales/localization-provider";
import ProjectShareDialog from "./project-share-dialog";
import OverviewProjectView from "./statistics/overview-project-view";

import { KanbanView } from "@/shared/sections/kanban/view";
import ProjectParticipantDialog from "./project-participants-dialog";
import AllTasksView from "./tasks-project-list";
import {
  favoriteProject,
  unfavoriteProject,
  useGetCollaborators,
  useGetTasksOfProject,
} from "@/shared/api/project";
import { axiosInstance } from "@/utils/axios";
// ----------------------------------------------------------------------
type Props = {
  project: Project;
};
const defaultFilters: ITaskTableFilters = {
  name: "",
  manager: [],
  column: {
    id: 0,
    name: "all",
    tasks: [],
    orderIndex: 0,
  },
  type: [],
  startDate: null,
  endDate: null,
};
export default function ProjectView({ project }: Props) {
  const settings = useSettingsContext();

  const [currentTab, setCurrentTab] = useState("statistics");

  const { enqueueSnackbar } = useSnackbar();

  const theme = useTheme();

  const openFilters = useBoolean();
  const router = useRouter();

  const table = useTable({ defaultOrderBy: "startDate" });

  const { copy } = useCopyToClipboard();

  const [inviteEmail, setInviteEmail] = useState("");

  const share = useBoolean();
  const confirm = useBoolean();

  const { tasks, tasksLoading } = useGetTasksOfProject(project.id);
  const [tableData, setTableData] = useState<ITaskItem[]>(tasks);

  useEffect(() => {
    if (tasks.length) {
      setTableData(tasks);
    }
  }, [tasks]);
  const { collaborators } = useGetCollaborators();
  const [collaboratorData, setCollaboratorData] =
    useState<collaborator[]>(collaborators);
  useEffect(() => {
    if (collaborators.length) {
      setCollaboratorData(collaborators);
    }
  }, [collaborators]);
  const addCollaboratorToProject = (newCollaboratorId: number) => {
    if (!project.collaboratorsIds.includes(newCollaboratorId)) {
      project.collaboratorsIds = [
        ...(project.collaboratorsIds || []),
        newCollaboratorId,
      ];
      const newCollaborator = collaborators.find(
        (c) => c.id === newCollaboratorId
      );
      if (
        newCollaborator &&
        !collaboratorData.some((c) => c.id === newCollaboratorId)
      ) {
        setCollaboratorData([...collaboratorData, newCollaborator]);
      }
    }
  };
  const [filters, setFilters] = useState(defaultFilters);
  const [favorite, setFavorite] = useState<boolean>(project?.itemState === "FAVORITE");



  const dateError = isAfter(filters.startDate, filters.endDate);

  const [sortBy, setSortBy] = useState("latest");

  const [search, setSearch] = useState<{ query: string; results: ITaskItem[] }>(
    {
      query: "",
      results: [],
    }
  );

  const dataFiltered = applyFilter({
    inputData: tableData,
    comparator: getComparator(table.order, table.orderBy || "startDate"), // Ensure a default key here
    filters,
    sortBy,
    dateError,
  });

  const handleChangeTab = useCallback(
    (event: React.SyntheticEvent, newValue: string) => {
      setCurrentTab(newValue);
    },
    []
  );
  const handleChangeInvite = useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      setInviteEmail(event.target.value);
    },
    []
  );
  const dataInPage = dataFiltered.slice(
    table.page * table.rowsPerPage,
    table.page * table.rowsPerPage + table.rowsPerPage
  );

  const denseHeight = table.dense ? 56 : 56 + 20;

  const canReset =
    !!filters.name ||
    filters.column.name !== "all" ||
    !!filters.type.length ||
    !!filters.manager.length ||
    (!!filters.startDate && !!filters.endDate);

  const notFound = (!dataFiltered.length && canReset) || !dataFiltered.length;

  const getTaskLength = (status: string) =>
    tableData.filter((item) => item.column.name === status).length;

  const handleFilters = useCallback(
    (name: string, value: ITaskTableFilterValue) => {
      table.onResetPage();
      setFilters((prevState) => ({
        ...prevState,
        [name]: value,
      }));
    },
    [table]
  );

  //----------------------------------------------------------------------------------
  const handleSortBy = useCallback((newValue: string) => {
    setSortBy(newValue);
  }, []);

  const handleResetFilters = useCallback(() => {
    setFilters(defaultFilters);
  }, []);

  const handleSearch = useCallback(
    (inputValue: string) => {
      setSearch((prevState) => ({
        ...prevState,
        query: inputValue,
      }));

      if (inputValue) {
        const results = _tasks.filter(
          (task) =>
            task.name.toLowerCase().indexOf(search.query.toLowerCase()) !== -1
        );

        setSearch((prevState) => ({
          ...prevState,
          results,
        }));
      }
    },
    [search.query]
  );
  const renderFilters = (
    <Stack
      spacing={3}
      justifyContent="space-between"
      alignItems={{ xs: "flex-end", sm: "center" }}
      direction={{ xs: "column", sm: "row" }}
    >
      <TaskSearch
        query={search.query}
        results={search.results}
        onSearch={handleSearch}
        hrefItem={(id: string) => paths.dashboard.tasks.details(id)}
      />

      <Stack direction="row" spacing={1} flexShrink={0}>
        <TaskFilters
          open={openFilters.value}
          onOpen={openFilters.onTrue}
          onClose={openFilters.onFalse}
          filters={filters}
          onFilters={handleFilters}
          canReset={canReset}
          onResetFilters={handleResetFilters}
          managerOptions={_managers}
          typeOptions={TASK_TYPE_OPTIONS.map((option) => option.label)}
          dateError={dateError}
        />

        <TaskSort
          sort={sortBy}
          onSort={handleSortBy}
          sortOptions={TASK_SORT_OPTIONS}
        />
      </Stack>
    </Stack>
  );

  const renderResults = (
    <TaskFiltersResult
      filters={filters}
      onResetFilters={handleResetFilters}
      canReset={canReset}
      onFilters={handleFilters}
      results={dataFiltered.length}
    />
  );
  //----------------------------------------------------------------------------------

  const handleToggleFavorite = async () => {
    try {
      if (favorite) {
        await unfavoriteProject(project.id);
        setFavorite(false);
        if (project) {
          project.itemState = "";
        }
      } else {
        await favoriteProject(project.id);
        setFavorite(true);
        if (project) {
          project.itemState = "FAVORITE";
        }
      }
    } catch (error) {
      console.error("An error occurred:", error);
      setFavorite((prev) => !prev);
      enqueueSnackbar("An error occurred. Please try again later.", {
        variant: "error",
      });
    }
  };

  const handleShare = async (email: string) => {
    try {
      const response = await axiosInstance.post(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/share/${project.id}`,
        null,
        {
          params: {
            clientEmail: email
          }
        }
      );

      if (response.status === 200) {
        enqueueSnackbar(response.data, { variant: 'success' });
        share.onFalse();
        setInviteEmail('');
      }
    } catch (error: any) {
      console.error('Error sharing project:', error);
      enqueueSnackbar(error.response?.data || 'Failed to share project', { 
        variant: 'error' 
      });
    }
  };

  const TABS = [
   
    {
      value: "tasks",
      label: "Tasks",
      icon: <Iconify icon="fluent:tasks-app-20-regular" width={20} />,
    },
    {
      value: "kanban",
      label: "Kanban",
      icon: <Iconify icon="ph:kanban" width={20} />,
    },
    {
      value: "statistics",
      label: "Statistics",
      icon: <Iconify icon="carbon:analytics" width={20} />,
    },
  ];

  return (
    <LocalizationProvider>
      <Container maxWidth={settings.themeStretch ? false : "lg"}>
        <CustomBreadcrumbs
          heading="Project Details"
          links={[
            {
              name: "Dashboard",
              href: paths.dashboard.root,
            },
            {
              name: "Projects",
              href: paths.dashboard.projects.all_projects,
            },
            {
              name: " Project Details",
            },
          ]}
          action={
            <Button
              component={RouterLink}
              href={`${paths.dashboard.tasks.add_task}?projectId=${project.id}`} 
              variant="contained"
              startIcon={<Iconify icon="mingcute:add-line" />}
            >
              New Task
            </Button>
          }
          sx={{
            mb: { xs: 3, md: 5 },
          }}
        />
        {(currentTab === "tasks" || currentTab === "kanban") && (
          <>
            <Stack
              spacing={2.5}
              sx={{
                mb: { xs: 3, md: 5 },
              }}
            >
              {renderFilters}

              {canReset && renderResults}
            </Stack>
          </>
        )}
        <Stack spacing={1} justifyContent="space-between" direction={"row"}>
          <Tabs
            value={currentTab}
            onChange={handleChangeTab}
            sx={{
              mb: { xs: 3, md: 5 },
            }}
          >
            {TABS.map((tab) => (
              <Tab
                key={tab.value}
                label={tab.label}
                icon={tab.icon}
                value={tab.value}
              />
            ))}
          </Tabs>

          <Stack spacing={1} direction={"row"} sx={{ ml: -1 }}>
            {currentTab !== "general" && (
              <>
                <Tooltip title="Add assignee">
                  <IconButton
                    size="small"
                    onClick={confirm.onTrue}
                    sx={{
                      height: 40,
                      width: 40,

                      border: (theme) => `dashed 1px ${theme.palette.divider}`,
                    }}
                  >
                    <Iconify icon="mingcute:add-line" />
                  </IconButton>
                </Tooltip>
                <ProjectParticipantDialog
                  assignee={collaborators.filter(
                    (participant: { id: number }) =>
                      project?.collaboratorsIds?.includes(participant.id)
                  )}
                  open={confirm.value}
                  onClose={confirm.onFalse}
                  projectId={project.id}
                  addCollaborator={addCollaboratorToProject}
                />
              </>
            )}
            {project.type === "EXTERNAL" ? (
              <IconButton
                size="small"
                color="primary"
                onClick={share.onTrue}
                sx={{
                  width: 40,
                  height: 40,
                }}
              >
                <Iconify icon="solar:share-bold" />
              </IconButton>
            ) : (
              <></>
            )}
            <Checkbox
              color="warning"
              icon={<Iconify icon="eva:star-outline" />}
              checkedIcon={<Iconify icon="eva:star-fill" />}
              checked={favorite}
              onChange={handleToggleFavorite}
              sx={{
                width: 40,
                height: 40,
              }}
            />
          </Stack>
        </Stack>
        <ProjectShareDialog
          open={share.value}
          onClose={() => {
            share.onFalse();
            setInviteEmail("");
          }}
          shared={collaborators.filter(
            (participant) => project?.collaboratorsIds?.includes(participant.id)
          )}
          inviteEmail={inviteEmail}
          onChangeInvite={handleChangeInvite}
          onCopyLink={() => console.log("copied")}
          onShare={handleShare}
        />

        {currentTab === "tasks" && (
          <>
            <AllTasksView projectId={project.id} />
          </>
        )}
        {currentTab === "statistics" && (
          project?.id ? (
            <OverviewProjectView projectId={project.id} />
          ) : (
            <Typography sx={{ p: 3 }}>No project selected</Typography>
          )
        )}
        {currentTab === "kanban" && <KanbanView projectId={project.id} />}
      </Container>
    </LocalizationProvider>
  );
}

function applyFilter({
  inputData,
  comparator,
  filters,
  sortBy,
  dateError,
}: {
  inputData: ITaskItem[];
  comparator: (a: any, b: any) => number;
  filters: ITaskTableFilters;
  // filTask;
  sortBy: string;
  dateError: boolean;
}) {
  const { name, type, manager, column, startDate, endDate } = filters; //
  const managerIds = manager.map((manager) => manager.id);
  const stabilizedThis = inputData.map((el, index) => [el, index] as const);

  stabilizedThis.sort((a, b) => {
    const order = comparator(a[0], b[0]);
    if (order !== 0) return order;
    return a[1] - b[1];
  });

  inputData = stabilizedThis.map((el) => el[0]);

  if (name) {
    inputData = inputData.filter(
      (task) => task.name.toLowerCase().indexOf(name.toLowerCase()) !== -1
    );
  }

  if (column.name !== "all") {
    inputData = inputData.filter((task) => task.column.name === column.name);
  }

  if (!dateError) {
    if (startDate && endDate) {
      inputData = inputData.filter((task) =>
        isBetween(task.startDate, startDate, endDate)
      );
    }
  }
  if (type.length) {
    inputData = inputData.filter((task) => type.includes(task.type));
  }
  if (managerIds.length) {
    inputData = inputData.filter(
      (task) => task.managerId && managerIds.includes(task.managerId)
    );
  }

  return inputData;
}
