"use client";

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

import Tab from "@mui/material/Tab";
import Tabs from "@mui/material/Tabs";
import Table from "@mui/material/Table";
import Button from "@mui/material/Button";
import Tooltip from "@mui/material/Tooltip";
import { alpha } from "@mui/material/styles";
import TableBody from "@mui/material/TableBody";
import IconButton from "@mui/material/IconButton";
import TableContainer from "@mui/material/TableContainer";

import { useSnackbar } from "@/components/snackbar";
import Scrollbar from "@/components/scrollbar";
import {
  useTable,
  emptyRows,
  TableNoData,
  getComparator,
  TableEmptyRows,
  TableHeadCustom,
  TableSelectedAction,
  TablePaginationCustom,
} from "@/shared/components/table";

import {
  IUserItem,
  IUserTableFilters,
  IUserTableFilterValue,
} from "@/shared/types/user";

import UserTableRow from "./user-table-row";
import UserTableToolbar from "./user-table-toolbar";
import UserTableFiltersResult from "./user-table-filters-result";
import Label from "@/components/label";
import Iconify from "@/shared/components/iconify";
import { useBoolean } from "@/hooks";
import axiosInstancee from "@/utils/axios";
import { Box, Typography } from "@mui/material";
import { useRouter } from "@/hooks";
import { paths } from "@/routes/paths";
import { checkManagerOrAdmin } from '@/utils/check-permissions';

const STATUS_OPTIONS = [
  { value: "all", label: "All" },
  { value: "blocked", label: "Blocked" },
  { value: "active", label: "Active" },
];

const TABLE_HEAD = [
  { id: "name", label: "Name", width: 150 },
  { id: "email", label: "Email", width: 200 },
  { id: "phoneNumber", label: "Phone Number", width: 150 },
  { id: "role", label: "Role", width: 150 },
  { id: "agency", label: "Agency Name", width: 150 },
  { id: "status", label: "Status", width: 100 },
];

const defaultFilters: IUserTableFilters = {
  name: "",
  role: [],
  status: "all",
};

export default function AllUserView() {
  const { enqueueSnackbar } = useSnackbar();
  const table = useTable();
  const confirm = useBoolean();
  const router = useRouter();

  const [tableData, setTableData] = useState<IUserItem[]>([]);
  const [filters, setFilters] = useState(defaultFilters);

  useEffect(() => {
    // Redirect if user doesn't have permission
    if (!checkManagerOrAdmin()) {
      router.push('/dashboard');
    }
  }, [router]);

  // If user doesn't have permission, don't render anything
  if (!checkManagerOrAdmin()) {
    return null;
  }

  // Function to fetch account agencies from the API
  const fetchAccountAgencies = async () => {
    try {
      const selectedAgency = localStorage.getItem("selectedAgency");
      if (!selectedAgency) {
        enqueueSnackbar("No agency selected. Please select an agency.", {
          variant: "warning",
        });
        return [];
      }
  
      // Pass the `selectedAgency` as a query parameter
      const response = await axiosInstancee.get(`/api/user/accountagency`, {
        params: { agencyId: selectedAgency },
      });
      return response.data;
    } catch (error) {
      enqueueSnackbar("Error fetching account agencies", { variant: "error" });
      console.error("Error fetching account agencies:", error);
      return [];
    }
  };

  // useEffect to call the API on component mount
  useEffect(() => {
    const loadUsers = async () => {
      const accountAgencies = await fetchAccountAgencies();

      const formattedData = Array.isArray(accountAgencies)
        ? accountAgencies.map((item: any) => ({
            id: item.id,
            firstName: item.user?.firstName || "N/A",
            lastName: item.user?.lastName || "N/A",
            email: item.user?.email || "N/A",
            phoneNumber: item.user?.phoneNumber || "N/A",
            role: item.role?.name || "N/A",
            agency: item.agency?.name || "N/A",
            status: item.state.toLowerCase(),

            // Add fields from IUserItem, with fallback values if not available
            city: item.city || "N/A",
            country: item.country || "N/A",
            zipCode: item.zipCode || "N/A",
            company: item.company || "N/A",
            avatarUrl: item.avatarUrl || "/static/default-avatar.png",
            isVerified: item.isVerified || false,
            streetName: item.streetName || "N/A",
            streetNumber: item.streetNumber || "N/A",
          }))
        : [];

      setTableData(formattedData as IUserItem[]); // Type assertion to match IUserItem[]
    };

    loadUsers();
  }, []);

  // Filtering, sorting, and pagination logic
  const dataFiltered = applyFilter({
    inputData: tableData,
    comparator: getComparator(table.order, table.orderBy),
    filters,
  });

  const dataInPage = dataFiltered.slice(
    table.page * table.rowsPerPage,
    table.page * table.rowsPerPage + table.rowsPerPage
  );
  const denseHeight = table.dense ? 56 : 56 + 20;
  const canReset = !isEqual(defaultFilters, filters);
  const notFound = (!dataFiltered.length && canReset) || !dataFiltered.length;

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

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

  const handleBlockRow = useCallback(
    async (id: string, isBlocked: boolean) => {
      try {
        // Decide the API endpoint based on the current status
        const endpoint = isBlocked
          ? `/api/user/${id}/unblock` // API endpoint to unblock the user
          : `/api/user/${id}/block`; // API endpoint to block the user

        const response = await axiosInstancee.put(endpoint);

        if (response.status === 200) {
          // Update the local state to reflect the new status
          const updatedTableData = tableData.map((user) =>
            user.id === id
              ? { ...user, status: isBlocked ? "active" : "blocked" }
              : user
          );

          setTableData(updatedTableData); // Update table data
          enqueueSnackbar(
            `User ${isBlocked ? "unblocked" : "blocked"} successfully!`,
            { variant: "success" }
          );
        }
      } catch (error) {
        enqueueSnackbar(
          `Failed to ${isBlocked ? "unblock" : "block"} the user.`,
          { variant: "error" }
        );
        console.error(
          `Error ${isBlocked ? "unblocking" : "blocking"} user:`,
          error
        );
      }
    },
    [enqueueSnackbar, tableData]
  );

  const handleDeleteRow = useCallback(
    async (id: string) => {
      try {
        // Call the delete API to remove the agency
        const response = await axiosInstancee.delete(
          `/api/user/agencies/${id}`
        );

        if (response.status === 200) {
          // Remove the deleted agency from the local table data
          const updatedTableData = tableData.filter((row) => row.id !== id);
          setTableData(updatedTableData);
          enqueueSnackbar("Agency deleted successfully!", {
            variant: "success",
          });
        }
      } catch (error) {
        enqueueSnackbar("Failed to delete the agency.", { variant: "error" });
        console.error("Error deleting agency:", error);
      }
    },
    [enqueueSnackbar, tableData]
  );
 

  return (
    <>
      {/* Status Tabs */}
      <Tabs
        value={filters.status}
        onChange={(e, newValue) => handleFilters("status", newValue)}
        sx={{
          px: 2.5,
          boxShadow: (theme) =>
            `inset 0 -2px 0 0 ${alpha(theme.palette.grey[500], 0.08)}`,
        }}
      >
        {STATUS_OPTIONS.map((tab) => (
          <Tab
            key={tab.value}
            value={tab.value}
            label={tab.label}
            icon={
              <Label
                variant={
                  tab.value === "all" || tab.value === filters.status
                    ? "filled"
                    : "soft"
                }
                color={
                  tab.value.toLowerCase() === "active"
                    ? "success"
                    : tab.value.toLowerCase() === "blocked"
                    ? "error"
                    : "default"
                }
              >
                {tab.value === "all"
                  ? tableData.length
                  : tableData.filter((user) => user.status === tab.value)
                      .length}
              </Label>
            }
          />
        ))}
      </Tabs>

      {/* Filters and Toolbar */}
      <UserTableToolbar
        filters={filters}
        onFilters={handleFilters}
        roleOptions={["COLLABORATOR", "MANAGER", "ADMIN","CLIENT"]}
      />

      {canReset && (
        <UserTableFiltersResult
          filters={filters}
          onFilters={handleFilters}
          onResetFilters={handleResetFilters}
          results={dataFiltered.length}
        />
      )}

      {/* Conditional Rendering for No Users */}
      {dataFiltered.length === 0 ? (
        <Box
          sx={{
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            justifyContent: "center",
            height: "400px",
            textAlign: "center",
            backgroundColor: "#F9FAFB",
            borderRadius: 2,
            border: "1px dashed #D1D5DB",
          }}
        >
          <Iconify
            icon="eva:people-outline"
            sx={{ fontSize: 64, color: "#9CA3AF", mb: 2 }}
          />
          <Typography variant="h6" sx={{ color: "text.secondary", mb: 1 }}>
            No users found in this agency
          </Typography>
          <Typography variant="body2" sx={{ color: "text.secondary", mb: 3 }}>
            Looks like there are no users in the selected agency. Add users to
            manage this agency more effectively.
          </Typography>
        </Box>
      ) : (
        <TableContainer sx={{ position: "relative", overflow: "unset" }}>
          <TableSelectedAction
            dense={table.dense}
            numSelected={table.selected.length}
            rowCount={dataFiltered.length}
            onSelectAllRows={(checked) =>
              table.onSelectAllRows(
                checked,
                dataFiltered.map((row) => row.id)
              )
            }
          />
          <Scrollbar>
            <Table size={table.dense ? "small" : "medium"} sx={{ minWidth: 960 }}>
              <TableHeadCustom
                order={table.order}
                orderBy={table.orderBy}
                headLabel={TABLE_HEAD}
                rowCount={dataFiltered.length}
                numSelected={table.selected.length}
                onSort={table.onSort}
                onSelectAllRows={(checked) =>
                  table.onSelectAllRows(
                    checked,
                    dataFiltered.map((row) => row.id)
                  )
                }
              />
              <TableBody>
                {dataInPage.map((row) => (
                  <UserTableRow
                    key={row.id}
                    row={row}
                    selected={table.selected.includes(row.id)}
                    onSelectRow={() => table.onSelectRow(row.id)}
                    onDeleteRow={() => handleDeleteRow(row.id)}
                    onBlock={() =>
                      handleBlockRow(row.id, row.status === "blocked")
                    }
                    onEditRow={() => console.log("Edit user", row.id)}
                  />
                ))}
              </TableBody>
            </Table>
          </Scrollbar>
        </TableContainer>
      )}

      {/* Pagination */}
      <TablePaginationCustom
        count={dataFiltered.length}
        page={table.page}
        rowsPerPage={table.rowsPerPage}
        onPageChange={table.onChangePage}
        onRowsPerPageChange={table.onChangeRowsPerPage}
        dense={table.dense}
        onChangeDense={table.onChangeDense}
      />
    </>
  );
}

// Filtering logic remains the same
function applyFilter({
  inputData,
  comparator,
  filters,
}: {
  inputData: IUserItem[];
  comparator: (a: any, b: any) => number;
  filters: IUserTableFilters;
}) {
  const { name, status, role } = filters;

  let filteredData = inputData.slice();

  // Filter by name
  if (name) {
    filteredData = filteredData.filter((user) => {
      const fullName = `${user.firstName} ${user.lastName}`.toLowerCase();
      return fullName.includes(name.toLowerCase());
    });
  }

  // Filter by status
  if (status !== "all") {
    filteredData = filteredData.filter(
      (user) => user.status.toLowerCase() === status.toLowerCase()
    );
  }

  // Filter by role
  if (role.length) {
    const lowerCaseRoles = role.map((r) => r.toLowerCase()); // Convert roles in the filter to lowercase
    filteredData = filteredData.filter((user) =>
      lowerCaseRoles.includes(user.role.toLowerCase())
    );
  }

  // Sorting
  filteredData.sort(comparator);

  return filteredData;
}