"use client";

import { useState, useCallback, useEffect } from "react";
import Stack from "@mui/material/Stack";
import Button from "@mui/material/Button";
import Container from "@mui/material/Container";
import ToggleButton from "@mui/material/ToggleButton";
import ToggleButtonGroup from "@mui/material/ToggleButtonGroup";
import { useBoolean } from "@/hooks";
import { isAfter, isBetween } from "@/utils/format-time";
import Iconify from "@/shared/components/iconify";
import { useSnackbar } from "@/components/snackbar";
import EmptyContent from "@/components/empty-content";
import { ConfirmDialog } from "@/components/custom-dialog";
import { useSettingsContext } from "@/shared/components/settings";
import useTable from "@/components/table/use-table";
import {
  IProjectFilters,
  IProjectFilterValue,
  Project,
} from "@/contexts/types/Project";
import ProjectTable from "./project-table";
import CustomBreadcrumbs from "@/components/custom-breadcrumbs";
import { paths } from "@/routes/paths";
import RouterLink from "@/routes/router-link";
import {
  Card,
  IconButton,
  InputAdornment,
  Tab,
  Tabs,
  TextField,
  Tooltip,
} from "@mui/material";
import Label from "@/components/label";
import { alpha, useTheme } from "@mui/material/styles";
import ProjectFilters from "./project-filters";
import { PROJECT_TYPE_OPTIONS } from "@/shared/_mock/_projects";
import LocalizationProvider from "@/shared/locales/localization-provider";
import ProjectFiltersResult from "./project-filters-result";
import ProjectListHorizontal from "./project-carte";
import ProjectFavoriteTable from "./project-favoris-list";
import ProjectDeletedTable from "./project-deleted-list";
import ProjectArchivedTable from "./project-archived-list";
import { LoadingScreen } from "@/shared/components/loading-screen";
import { axiosInstance, endpoints } from "@/utils/axios";
import {
  archiveListProject,
  archiveProject,
  deleteListProject,
  deleteProject,
  recoverListProject,
  recoverProject,
  unfavoritListProject,
  unfavoriteProject,
  useGetProject,
  useGetProjects,
} from "@/shared/api/project";
import { usePathname, useRouter } from "next/navigation";
import ConditionalComponent from "@/shared/components/ConditionalComponent/ConditionalComponent";

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

const defaultFilters: IProjectFilters = {
  name: "",
  status: "all",
  type: [],
  startDate: null,
  endDate: null,
};

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

export default function AllProjectsView() {
  const { enqueueSnackbar } = useSnackbar();
  const table = useTable({ defaultRowsPerPage: 10 });
  const openFilters = useBoolean();
  const [filters, setFilters] = useState(defaultFilters);
  const settings = useSettingsContext();
  const theme = useTheme();
  const confirm1 = useBoolean();
  const confirm2 = useBoolean();
  const confirm = useBoolean();
  const confirm3 = useBoolean();
  const [view, setView] = useState("CURRENT");
  const [projectsLoading, setProjectsLoading] = useState(false);
  const [tableData, setTableData] = useState<Project[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const agencyId = localStorage.getItem("selectedAgency");
  const router = useRouter();
  const currentPath = usePathname();

  useEffect(() => {
    const email = localStorage.getItem("email");
    const agencyId = localStorage.getItem("selectedAgency");
    if (!email || !agencyId) {
      return;
    }

    const fetchProjects = async () => {
      setLoading(true);
      try {
        const accountAgencyResponse = await axiosInstance.get(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/accountagency/${email}/${agencyId}`
        );

        const userId = accountAgencyResponse.data.id;
        const role = accountAgencyResponse.data.role.name;

        const queryParams = new URLSearchParams({
          userId: userId.toString(),
          role: role,
          agencyId: agencyId,
        });

        // Add type parameter only for internal/external
        if (currentPath.includes('/internal')) {
          queryParams.append('type', 'INTERNAL');
        } else if (currentPath.includes('/external')) {
          queryParams.append('type', 'EXTERNAL');
        }
        // No special params for recent - it will show all projects

        const apiEndpoint = '/api/projects/get/projects/for/user';

        const projectResponse = await axiosInstance.get(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}${apiEndpoint}?${queryParams}`
        );

        setTableData(projectResponse.data);
      } catch (err) {
        console.error("Failed to fetch projects:", err);
        setTableData([]);
      } finally {
        setLoading(false);
      }
    };

    fetchProjects();
  }, [agencyId, currentPath]);

  // Filtering and view management
  const dateError = isAfter(filters.startDate, filters.endDate);
  const getProjectLength = (status: string) => {
    return tableData?.filter((item) => {
      if (view !== "grid") {
        return item.status === status && item.itemState === view;
      } else {
        return item.status === status && item.itemState === "CURRENT";
      }
    }).length;
  };
  const getTypeProjectLength = () => {
    return tableData?.filter((item) => {
      if (view !== "grid") {
        return item.itemState === view;
      } else {
        return item.itemState === "CURRENT";
      }
    }).length;
  };

  const TABS = [
    {
      value: "all",
      label: "All",
      color: "default",
      count: getTypeProjectLength(),
    },
    {
      value: "COMPLETED",
      label: "Completed",
      color: "success",
      count: getProjectLength("COMPLETED"),
    },
    {
      value: "IN_PROGRESS",
      label: "In progress",
      color: "warning",
      count: getProjectLength("IN_PROGRESS"),
    },
    {
      value: "PENDING",
      label: "Pending",
      color: "error",
      count: getProjectLength("PENDING"),
    },
  ] as const;

  const dataFiltered = applyFilter({
    inputData: tableData,
    filters,
    view,
    dateError,
  });
  const dataInPage = dataFiltered.slice(
    table.page * table.rowsPerPage,
    table.page * table.rowsPerPage + table.rowsPerPage
  );
  const handleUnfavoriteRows = useCallback(async () => {
    try {
      const response = await unfavoritListProject(
        table.selected.map((id) => Number(id))
      );
      const updatedTableData = tableData?.map((project) =>
        table.selected.includes(project.id.toString())
          ? { ...project, itemState: "CURRENT" }
          : project
      );
      setTableData(updatedTableData);

      table.onUpdatePageDeleteRows({
        totalRowsInPage: dataInPage.length,
        totalRowsFiltered: dataFiltered.length,
      });
      enqueueSnackbar("Projects recovred successfully", { variant: "success" });
    } catch (error) {
      enqueueSnackbar("recover projects Error", { variant: "error" });
    }
  }, [
    dataFiltered.length,
    dataInPage.length,
    enqueueSnackbar,
    table,
    tableData,
  ]);

  const canReset =
    filters.status !== "all" ||
    !!filters.type.length ||
    (!!filters.startDate && !!filters.endDate);
  const notFound = !dataFiltered.length && canReset;

  const handleChangeView = useCallback(
    (event: React.MouseEvent<HTMLElement>, newView: string | null) => {
      if (newView !== null) {
        setView(newView);
      }
    },
    []
  );

  // Handle project actions without API calls
  const handleDelete = useCallback(
    (id: number) => {
      const updatedTableData = tableData?.map((project) =>
        project.id === id ? { ...project, itemState: "DELETED" } : project
      );
      setTableData(updatedTableData);
      confirm.onFalse();
      enqueueSnackbar("Project deleted successfully", { variant: "success" });
    },
    [tableData, enqueueSnackbar]
  );

  const handleArchive = useCallback(
    (id: number) => {
      const updatedTableData = tableData?.map((project) =>
        project.id === id ? { ...project, itemState: "ARCHIVED" } : project
      );
      setTableData(updatedTableData);
      enqueueSnackbar("Project archived successfully", { variant: "success" });
    },
    [tableData, enqueueSnackbar]
  );

  const handleUnFavoriteClick = useCallback(
    (id: number) => {
      const updatedTableData = tableData?.map((project) =>
        project.id === id ? { ...project, itemState: "CURRENT" } : project
      );
      setTableData(updatedTableData);
      confirm.onFalse();
      enqueueSnackbar("Project un-favorited successfully", {
        variant: "success",
      });
    },
    [tableData, enqueueSnackbar]
  );

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

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

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

  const handleDeleteRows = useCallback(async () => {
    const updatedTableData = tableData?.map((project) =>
      table.selected.includes(project.id.toString())
        ? { ...project, itemState: "DELETED" }
        : project
    );
    setTableData(updatedTableData);
    table.onUpdatePageDeleteRows({
      totalRowsInPage: dataInPage.length,
      totalRowsFiltered: dataFiltered.length,
    });
    enqueueSnackbar("Projects deleted successfully", { variant: "success" });
  }, [
    dataFiltered.length,
    dataInPage.length,
    enqueueSnackbar,
    table,
    tableData,
  ]);

  const handleArchiveRows = useCallback(async () => {
    const updatedTableData = tableData?.map((project) =>
      table.selected.includes(project.id.toString())
        ? { ...project, itemState: "ARCHIVED" }
        : project
    );
    setTableData(updatedTableData);
    table.onUpdatePageDeleteRows({
      totalRowsInPage: dataInPage.length,
      totalRowsFiltered: dataFiltered.length,
    });
    enqueueSnackbar("Projects archived successfully", { variant: "success" });
  }, [
    dataFiltered.length,
    dataInPage.length,
    enqueueSnackbar,
    table,
    tableData,
  ]);

  const handleRecoverRows = useCallback(async () => {
    const updatedTableData = tableData?.map((project) =>
      table.selected.includes(project.id.toString())
        ? { ...project, itemState: "CURRENT" }
        : project
    );
    setTableData(updatedTableData);
    table.onUpdatePageDeleteRows({
      totalRowsInPage: dataInPage.length,
      totalRowsFiltered: dataFiltered.length,
    });
    enqueueSnackbar("Projects recovered successfully", { variant: "success" });
  }, [
    dataFiltered.length,
    dataInPage.length,
    enqueueSnackbar,
    table,
    tableData,
  ]);

  const renderFilterTitle = (
    <TextField
      value={filters.name}
      onChange={(event) => handleFilters("name", event.target.value)}
      placeholder="Search..."
      InputProps={{
        startAdornment: (
          <InputAdornment position="start">
            <Iconify icon="eva:search-fill" sx={{ color: "text.disabled" }} />
          </InputAdornment>
        ),
      }}
      sx={{
        width: { xs: 1, md: 260 },
      }}
    />
  );

  const renderFilters = (
    <Stack
      spacing={1}
      direction={{ xs: "column", md: "row" }}
      alignItems={{ xs: "flex-end", md: "center" }}
      sx={{ width: 1 }}
    >
      {renderFilterTitle}
      <Stack
        spacing={1}
        direction={{ xs: "column", md: "row" }}
        alignItems="flex-end"
        justifyContent="flex-end"
        flexGrow={1}
      >
        <ProjectFilters
          open={openFilters.value}
          onOpen={openFilters.onTrue}
          onClose={openFilters.onFalse}
          //
          filters={filters}
          onFilters={handleFilters}
          //
          canReset={canReset}
          onResetFilters={handleResetFilters}
          type={PROJECT_TYPE_OPTIONS}
          dateError={dateError}
        />

        <ToggleButtonGroup
          size="small"
          value={view}
          exclusive
          onChange={handleChangeView}
        >
          <ToggleButton value="CURRENT">
            <Iconify icon="solar:list-bold" />
          </ToggleButton>
          <ToggleButton value="grid">
            <Iconify icon="mingcute:dot-grid-fill" />
          </ToggleButton>

          <ToggleButton value="FAVORITE">
            <Tooltip title="Check the favorite projects">
              <Iconify icon="f7:square-favorites-alt" />
            </Tooltip>
          </ToggleButton>
          <ToggleButton value="ARCHIVED">
            <Tooltip title="Check the archived projects">
              <Iconify icon="ri:inbox-archive-line" />
            </Tooltip>
          </ToggleButton>
          <ToggleButton value="DELETED">
            <Tooltip title="Check the deleted projects">
              <Iconify icon="ic:round-delete-sweep" />
            </Tooltip>
          </ToggleButton>
        </ToggleButtonGroup>
      </Stack>
    </Stack>
  );

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

  const renderTabs = (
    <Tabs
      value={filters.status}
      onChange={handleFilterStatus}
      sx={{
        px: 2.5,
        boxShadow: `inset 0 -2px 0 0 ${alpha(theme.palette.grey[500], 0.08)}`,
      }}
    >
      {TABS.map((tab) => (
        <Tab
          key={tab.value}
          value={tab.value}
          label={tab.label}
          iconPosition="end"
          icon={
            <Label
              variant={
                ((tab.value === "all" || tab.value === filters.status) &&
                  "filled") ||
                "soft"
              }
              color={tab.color}
            >
              {tab.count}
            </Label>
          }
        />
      ))}
    </Tabs>
  );

  return (
    <LocalizationProvider>
      <Container maxWidth={settings.themeStretch ? false : "lg"}>
        <ConditionalComponent
          isValid={!loading}
          defaultComponent={<LoadingScreen />}
        >
          <>
            {view === "CURRENT" && (
              <>
                {renderTabs}
                <Stack width="100%" sx={{ justifyContent: "space-around", flexDirection:"row",alignItems:"center"}} display="flex">
                  <Stack spacing={1} width='60%' sx={{ my: { xs: 3, md: 1 } }}>
                    {renderFilters}
                    {canReset && renderResults}
                  </Stack>
                  <Button
                    component={RouterLink}
                    href={paths.dashboard.projects.add_project}
                    variant="contained"
                    startIcon={<Iconify icon="mingcute:add-line" />}
                    sx={{
                      backgroundColor: '#144dd5',
                      '&:hover': {
                        backgroundColor: '#144dd5',
                      },
                      width: '19.2%',
                      height: '100%',
                      textTransform: 'none',
                    }}
                  >
                    New Project
                  </Button>
                </Stack>
                
                <ConditionalComponent 
                  isValid={!notFound}
                  defaultComponent={
                    <EmptyContent
                      title="No Data"
                      description="No projects found for this status"
                      sx={{
                        borderRadius: 1.5,
                        border: `dashed 1px ${theme.palette.divider}`,
                        bgcolor: 'background.paper'
                      }}
                    />
                  }
                >
                  <ProjectTable
                    table={table}
                    dataFiltered={dataFiltered}
                    notFound={notFound}
                    onOpenConfirm={confirm.onTrue}
                    onDeleteRow={handleDelete}
                    onArchiveRow={handleArchive}
                    projectsLoading={projectsLoading}
                    onOpenConfirm1={confirm3.onTrue}
                  />
                </ConditionalComponent>
              </>
            )}

            {view === "FAVORITE" && (
              <>
                {renderTabs}
                <Stack spacing={2.5} sx={{ my: { xs: 3, md: 5 } }}>
                  {renderFilters}
                  {canReset && renderResults}
                </Stack>
                <ConditionalComponent 
                  isValid={!notFound}
                  defaultComponent={
                    <EmptyContent
                      title="No Data"
                      description="No favorite projects found"
                      sx={{
                        borderRadius: 1.5,
                        border: `dashed 1px ${theme.palette.divider}`,
                        bgcolor: 'background.paper'
                      }}
                    />
                  }
                >
                  <ProjectFavoriteTable
                    table={table}
                    dataFiltered={dataFiltered}
                    notFound={notFound}
                    onOpenConfirm={confirm.onTrue}
                    onOpenConfirm1={confirm2.onTrue}
                    onDeleteRow={handleDelete}
                    onFavoriteRow={handleUnFavoriteClick}
                  />
                </ConditionalComponent>
              </>
            )}

            {view === "DELETED" && (
              <>
                <Stack spacing={2.5} sx={{ my: { xs: 3, md: 5 } }}>
                  {renderFilters}
                  {canReset && renderResults}
                </Stack>
                <ConditionalComponent 
                  isValid={!notFound}
                  defaultComponent={
                    <EmptyContent
                      title="No Data"
                      description="No deleted projects found"
                      sx={{
                        borderRadius: 1.5,
                        border: `dashed 1px ${theme.palette.divider}`,
                        bgcolor: 'background.paper'
                      }}
                    />
                  }
                >
                  <ProjectDeletedTable
                    table={table}
                    dataFiltered={dataFiltered}
                    notFound={notFound}
                  />
                </ConditionalComponent>
              </>
            )}

            {view === "ARCHIVED" && (
              <>
                {renderTabs}
                <Stack spacing={2.5} sx={{ my: { xs: 3, md: 5 } }}>
                  {renderFilters}
                  {canReset && renderResults}
                </Stack>
                <ConditionalComponent 
                  isValid={!notFound}
                  defaultComponent={
                    <EmptyContent
                      title="No Data"
                      description="No archived projects found"
                      sx={{
                        borderRadius: 1.5,
                        border: `dashed 1px ${theme.palette.divider}`,
                        bgcolor: 'background.paper'
                      }}
                    />
                  }
                >
                  <ProjectArchivedTable
                    table={table}
                    dataFiltered={dataFiltered}
                    notFound={notFound}
                    onOpenConfirm={confirm.onTrue}
                    onOpenConfirm1={confirm1.onTrue}
                    onDeleteRow={handleDelete}
                    onRecoverRow={handleRecoverRows}
                  />
                </ConditionalComponent>
              </>
            )}

            {view !== "CURRENT" &&
              view !== "FAVORITE" &&
              view !== "DELETED" &&
              view !== "ARCHIVED" && (
                <>
                  {renderTabs}
                  <Stack spacing={2.5} sx={{ my: { xs: 3, md: 5 } }}>
                    {renderFilters}
                    {canReset && renderResults}
                  </Stack>
                  <ConditionalComponent 
                    isValid={!notFound}
                    defaultComponent={
                      <EmptyContent
                        title="No Data"
                        description="No projects found"
                        sx={{
                          borderRadius: 1.5,
                          border: `dashed 1px ${theme.palette.divider}`,
                          bgcolor: 'background.paper'
                        }}
                      />
                    }
                  >
                    <ProjectListHorizontal
                      project={dataFiltered}
                      onDeleteRow={handleDelete}
                      onArchiveRow={handleArchive}
                      loading={projectsLoading}
                    />
                  </ConditionalComponent>
                </>
              )}
          </>
        </ConditionalComponent>
      </Container>

      <ConfirmDialog
        open={confirm.value}
        onClose={confirm.onFalse}
        title="Delete"
        content={
          <>
            Are you sure you want to delete{" "}
            <strong>{table.selected.length}</strong> items?
          </>
        }
        action={
          <Button
            variant="contained"
            color="error"
            onClick={() => {
              handleDeleteRows();
              confirm.onFalse();
            }}
          >
            Delete
          </Button>
        }
      />

      <ConfirmDialog
        open={confirm3.value}
        onClose={confirm3.onFalse}
        title="Archive"
        content={
          <>
            Are you sure you want to archive{" "}
            <strong>{table.selected.length}</strong> items?
          </>
        }
        action={
          <Button
            variant="contained"
            color="error"
            onClick={() => {
              handleArchiveRows();
              confirm3.onFalse();
            }}
          >
            Archive
          </Button>
        }
      />

      <ConfirmDialog
        open={confirm1.value}
        onClose={confirm1.onFalse}
        title="Recover"
        content={
          <>
            Are you sure you want to recover{" "}
            <strong>{table.selected.length}</strong> items?
          </>
        }
        action={
          <Button
            variant="contained"
            color="success"
            onClick={() => {
              handleRecoverRows();
              confirm1.onFalse();
            }}
          >
            Recover
          </Button>
        }
      />

      <ConfirmDialog
        open={confirm2.value}
        onClose={confirm2.onFalse}
        title="Turn Off Favoriting"
        content={
          <>
            Are you sure you want to turn off favoriting{" "}
            <strong>{table.selected.length}</strong> items?
          </>
        }
        action={
          <Button
            variant="contained"
            color="warning"
            onClick={() => {
              handleUnfavoriteRows();
              confirm2.onFalse();
            }}
          >
            Turn Off
          </Button>
        }
      />
    </LocalizationProvider>
  );
}

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

function applyFilter({
  inputData,
  filters,
  view,
  dateError,
}: {
  inputData: Project[];
  filters: IProjectFilters;
  view: string;
  dateError: boolean;
}) {
  const { name, status, type, startDate, endDate } = filters;

  if (status !== "all") {
    inputData = inputData.filter((project) => project.status === status);
  }
  if (type.length) {
    inputData = inputData.filter((project) => type.includes(project.type));
  }
  if (name) {
    inputData = inputData.filter(
      (project) => project.name.toLowerCase().indexOf(name.toLowerCase()) !== -1
    );
  }
  if (startDate && endDate) {
    inputData = inputData.filter((project) =>
      isBetween(startDate, project.startDate, project.endDate)
    );
  }
  if (view === "FAVORITE") {
    inputData = inputData.filter((project) => project.itemState === "FAVORITE");
  }
  if (view === "ARCHIVED") {
    inputData = inputData.filter((project) => project.itemState === "ARCHIVED");
  }
  if (view === "DELETED") {
    inputData = inputData.filter((project) => project.itemState === "DELETED");
  }
  return inputData;
}
