"use client";

import sumBy from "lodash/sumBy";
import { useState, useCallback, useEffect } from "react";

import Tab from "@mui/material/Tab";
import Tabs from "@mui/material/Tabs";
import Card from "@mui/material/Card";
import Table from "@mui/material/Table";
import Stack from "@mui/material/Stack";
import Button from "@mui/material/Button";
import Divider from "@mui/material/Divider";
import Tooltip from "@mui/material/Tooltip";
import Container from "@mui/material/Container";
import TableBody from "@mui/material/TableBody";
import IconButton from "@mui/material/IconButton";
import { alpha, useTheme } from "@mui/material/styles";
import TableContainer from "@mui/material/TableContainer";
import LocalizationProvider from "@/shared/locales/localization-provider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { paths } from "@/routes/paths";
import { useRouter } from "@/hooks";
import RouterLink from "@/routes/router-link";

import { useBoolean } from "@/hooks";

import { isAfter, isBetween } from "@/utils/format-time";

import {
  TASK_SORT_OPTIONS,
  TASK_TYPE_OPTIONS,
  _managers,
} from "@/shared/_mock";

import Label from "@/shared/components/label";
import Iconify from "@/shared/components/iconify";
import Scrollbar from "@/shared/components/scrollbar";
import { useSnackbar } from "@/components/snackbar";
import { ConfirmDialog } from "@/shared/components/custom-dialog";
import { useSettingsContext } from "@/shared/components/settings";
import CustomBreadcrumbs from "@/components/custom-breadcrumbs";
import {
  useTable,
  emptyRows,
  TableNoData,
  getComparator,
  TableHeadCustom,
  TableSelectedAction,
  TablePaginationCustom,
  TableEmptyRows,
} from "@/shared/components/table";

import {
  ITaskItem,
  ITaskTableFilterValue,
  ITaskTableFilters,
} from "@/contexts/types/tasks";
import TaskDeletedTableRow from "./task-deleted-table-row";
import TaskSearch from "./task-search";
import TaskSort from "./task-sort";
import TaskFilters from "./task-filters";
import TaskFiltersResult from "./task-filters-result";
import { orderBy } from "lodash";
import { useGetTasks } from "@/shared/api/task";

// ----------------------------------------------------------------------

const TABLE_HEAD = [
  { id: "name", label: "Name" },
  { id: "startDate", label: "Create" },
  { id: "endDate", label: "Due" },
  { id: "type", label: "Type" },
  { id: "manager", label: "Manager", align: "center" },
  { id: "column", label: "Status" },
  { id: "deletedAt", label: "Deletion At" },
];

const defaultFilters: ITaskTableFilters = {
  name: "",
  manager: [],
  column: {
    id: 0,
    name: "all",
    orderIndex: 0,
    tasks: []
  },
  type: [],
  startDate: null,
  endDate: null,
};

// ----------------------------------------------------------------------

export default function TaskDeletedList() {
  const { enqueueSnackbar } = useSnackbar();

  const theme = useTheme();

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

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

  const confirm = useBoolean();

  const { tasks, tasksLoading } = useGetTasks(1, "DELETED");

  const [tableData, setTableData] = useState<ITaskItem[]>(tasks);

  const [filters, setFilters] = useState(defaultFilters);

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

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

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

  //----------------------Integration-----------------

  useEffect(() => {
    if (tasks.length) {
      setTableData(tasks);
    }
  }, [tasks]);
  //--------------------------------------------------

  const dataFiltered = applyFilter({
    inputData: tableData,
    comparator: getComparator(table.order, table.orderBy),
    filters,
    sortBy,
    dateError,
  });

  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 TABS = [
    { value: "all", label: "All", color: "default", count: tableData.length },
    {
      value: "to do",
      label: "To Do",
      color: "error",
      count: getTaskLength("to do"),
    },
    {
      value: "in progress",
      label: "In Progress",
      color: "warning",
      count: getTaskLength("in progress"),
    },
    {
      value: "validation",
      label: "Validation",
      color: "default",
      count: getTaskLength("validation"),
    },
    {
      value: "done",
      label: "Done",
      color: "success",
      count: getTaskLength("done"),
    },
  ] as const;

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

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

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

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

        setSearch((prevState) => ({
          ...prevState,
          results,
        }));
      }
    },
    [search.query]
  );
  //----------------------------------------------------------------------------------

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

  const handleDeleteRow = useCallback(
    (id: number) => {
      const deleteRow = tableData.filter((row) => row.id !== id);

      enqueueSnackbar("Delete success!");

      setTableData(deleteRow);

      table.onUpdatePageDeleteRow(dataInPage.length);
    },
    [dataInPage.length, enqueueSnackbar, table, tableData]
  );

  const handleDeleteRows = useCallback(() => {
    const deleteRows = tableData.filter(
      (row) => !table.selected.includes(row.id.toString())
    );

    enqueueSnackbar("Delete success!");

    setTableData(deleteRows);

    table.onUpdatePageDeleteRows({
      totalRowsInPage: dataInPage.length,
      totalRowsFiltered: dataFiltered.length,
    });
  }, [
    dataFiltered.length,
    dataInPage.length,
    enqueueSnackbar,
    table,
    tableData,
  ]);

  const handleFilterStatus = useCallback(
    (event: React.SyntheticEvent, newValue: string) => {
      handleFilters("column", newValue);
    },
    [handleFilters]
  );

  //----------------view details--------------

  const [selectedTask, setSelectedTask] = useState<ITaskItem | null>(null);
  const handelSelectedTask = (task: any) => {
    setSelectedTask(task);
  };
  const handleViewRow = useCallback(
    (id: number) => {
      const task = tableData.find((t) => t.id === id);
      handelSelectedTask(task);
    },
    [tableData]
  );

  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>
      <Button
        component={RouterLink}
        href={paths.dashboard.tasks.add_task}
        variant="contained"
        startIcon={<Iconify icon="mingcute:add-line" />}
        sx={{
          backgroundColor: '#144dd5',
          '&:hover': {
            backgroundColor: '#144dd5',
          },
          width: '19.2%',
          height: '100%',
          textTransform: 'none',
        }}
      >
        New Task
      </Button>
    </Stack>
  );

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

  /////////////////////////////

  return (
    <>
      <LocalizationProvider>
        <Stack
          spacing={2.5}
          sx={{
            mb: { xs: 3, md: 5 },
          }}
        >
          {renderFilters}

          {canReset && renderResults}
        </Stack>

        <Card>
          <TableContainer sx={{ position: "relative", overflow: "unset" }}>
            <Scrollbar>
              <Table
                size={table.dense ? "small" : "medium"}
                sx={{ minWidth: 800 }}
              >
                <TableHeadCustom
                  order={table.order}
                  orderBy={table.orderBy}
                  headLabel={TABLE_HEAD}
                  rowCount={dataFiltered.length}
                  numSelected={table.selected.length}
                  onSort={table.onSort}
                />

                <TableBody>
                  {dataFiltered
                    .slice(
                      table.page * table.rowsPerPage,
                      table.page * table.rowsPerPage + table.rowsPerPage
                    )
                    .map((row) => (
                      <TaskDeletedTableRow
                        key={row.id}
                        row={row}
                        selected={table.selected.includes(row.id.toString())}
                        onSelectRow={() => table.onSelectRow(row.id.toString())}
                        onViewRow={() => handleViewRow(row.id)}
                        selectedTask={selectedTask}
                        onDeleteRow={() => handleDeleteRow(row.id)}
                      />
                    ))}

                  <TableEmptyRows
                    height={denseHeight}
                    emptyRows={emptyRows(
                      table.page,
                      table.rowsPerPage,
                      dataFiltered.length
                    )}
                  />

                  <TableNoData notFound={notFound} />
                </TableBody>
              </Table>
            </Scrollbar>
          </TableContainer>

          <TablePaginationCustom
            count={dataFiltered.length}
            page={table.page}
            rowsPerPage={table.rowsPerPage}
            onPageChange={table.onChangePage}
            onRowsPerPageChange={table.onChangeRowsPerPage}
            dense={table.dense}
            onChangeDense={table.onChangeDense}
          />
        </Card>
      </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) //manager.id
    );
  }

  // SORT BY
  if (sortBy === "latest") {
    inputData = orderBy(inputData, ["createdAt"], ["desc"]);
  }

  if (sortBy === "oldest") {
    inputData = orderBy(inputData, ["createdAt"], ["asc"]);
  }

  if (sortBy === "popular") {
    inputData = orderBy(inputData, ["totalViews"], ["desc"]);
  }

  return inputData;
}
