"use client";

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

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 Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';
import CircularProgress from '@mui/material/CircularProgress';
import Stack from '@mui/material/Stack';
import Avatar from '@mui/material/Avatar';
import Typography from '@mui/material/Typography';
import Container from "@mui/material/Container";

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 { checkManagerOrAdmin } from '@/utils/check-permissions';
import { useRouter } from '@/hooks';
import { useSettingsContext } from "@/shared/components/settings";

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 settings = useSettingsContext();

  const [tableData, setTableData] = useState<IUserItem[]>([]);
  const [filters, setFilters] = useState(defaultFilters);
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<IUserItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedAgencyId, setSelectedAgencyId] = useState<string | null>(null);

  useEffect(() => {
    const storedAgencyId = localStorage.getItem("selectedAgency");
    if (storedAgencyId) {
      setSelectedAgencyId(storedAgencyId);
    }
    const handleStorageChange = () => {
      const newAgencyId = localStorage.getItem("selectedAgency");
      setSelectedAgencyId(newAgencyId);
    };

    window.addEventListener('storage', handleStorageChange);

    return () => {
      window.removeEventListener('storage', handleStorageChange);
    };
  }, []);

  useEffect(() => {
    if (!checkManagerOrAdmin()) {
      router.push('/dashboard');
    }
  }, [router]);
  if (!checkManagerOrAdmin()) {
    return null;
  }

  const fetchAccountAgencies = async () => {
    try {
      const response = await axiosInstancee.get("/api/user/accountagency");
      return response.data;
    } catch (error) {
      enqueueSnackbar("Error fetching account agencies", { variant: "error" });
      console.error("Error fetching account agencies:", error);
      return [];
    }
  };

  useEffect(() => {
    const loadUsers = async () => {
      try {
        setLoading(true);

        // Get the user's role for the selected agency
        const agencyRoles = JSON.parse(localStorage.getItem("agency_role") || "{}");
        const isAdmin = selectedAgencyId ? agencyRoles[selectedAgencyId] === "ADMIN" : false;

        // Determine the endpoint based on role and selectedAgencyId
        const endpoint = isAdmin 
          ? "/api/user/accountagency"
          : `/api/user/accountagency?agencyId=${selectedAgencyId}`;

        const response = await axiosInstancee.get(endpoint);
        const accountAgencies = response.data;

        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(),
              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[]);
      } catch (error) {
        console.error("Error fetching users:", error);
        enqueueSnackbar("Failed to load users", { variant: "error" });
      } finally {
        setLoading(false);
      }
    };

    // Only load users if there's a selected agency
    if (selectedAgencyId) {
      loadUsers();
    }
  }, [selectedAgencyId, enqueueSnackbar]);

  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 {

        const endpoint = isBlocked
          ? `/api/user/${id}/unblock`
          : `/api/user/${id}/block`;

        const response = await axiosInstancee.put(endpoint);

        if (response.status === 200) {
          const updatedTableData = tableData.map((user) =>
            user.id === id
              ? { ...user, status: isBlocked ? "active" : "blocked" }
              : user
          );

          setTableData(updatedTableData);
          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 {
        const response = await axiosInstancee.delete(
          `/api/user/agencies/${id}`
        );

        if (response.status === 200) {

          const updatedTableData = tableData.filter((row) => row.id !== id);
          setTableData(updatedTableData);

          const agencyRoles = JSON.parse(localStorage.getItem("agency_role") || "{}");
          const selectedAgency = localStorage.getItem("selectedAgency");
          if (agencyRoles[id]) {
            delete agencyRoles[id];
            localStorage.setItem("agency_role", JSON.stringify(agencyRoles));
          }
          if (selectedAgency === id) {
            localStorage.removeItem("selectedAgency");
          }
          window.dispatchEvent(new Event('storage'));
          enqueueSnackbar("Agency deleted successfully!", {
            variant: "success",
          });
        }
      } catch (error) {
        enqueueSnackbar("Failed to delete the agency.", { variant: "error" });
        console.error("Error deleting agency:", error);
      }
    },
    [enqueueSnackbar, tableData]
  );

  // Fonction de recherche avec debounce
  const searchUsers = debounce(async (query: string) => {
    if (!query || query.length < 2) return;

    setLoading(true);
    try {
      const response = await axiosInstancee.get(`/api/user/search?query=${query}`);
      setSearchResults(response.data);
    } catch (error) {
      console.error('Search error:', error);
      enqueueSnackbar('Erreur lors de la recherche', { variant: 'error' });
    } finally {
      setLoading(false);
    }
  }, 300);

  return (
    <Container maxWidth={settings.themeStretch ? false : "lg"}>
      <Stack spacing={2.5}>
        {/* Status Tabs */}
        <Tabs
          value={filters.status}
          onChange={(e, newValue) => handleFilters("status", newValue)}
          sx={{
            mb: { xs: 3, md: 5 },
            px: 0,
            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"]}
          sx={{ px: 0 }}
        />

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

        {/* Table */}
        <TableContainer 
          sx={{ 
            position: "relative", 
            overflow: "unset",
            px: 0
          }}
        >
          <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")
                    } // Check current status
                    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}
          sx={{ px: 0 }}
        />
      </Stack>
    </Container>
  );
}


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

  let filteredData = inputData.slice();

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


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


  if (role.length) {
    const lowerCaseRoles = role.map((r) => r.toLowerCase());
    filteredData = filteredData.filter((user) =>
      lowerCaseRoles.includes(user.role.toLowerCase())
    );
  }



  filteredData.sort(comparator);

  return filteredData;
}
