"use client";
import { useCallback, useState, useEffect } from "react";
import axiosInstancee from "@/utils/axios";
import CustomBreadcrumbs from "@/components/custom-breadcrumbs";
import { paths } from "@/routes/paths";
import RouterLink from "@/routes/router-link";
import Iconify from "@/shared/components/iconify";
import { useSettingsContext } from "@/shared/components/settings";
import {
  Button,
  Card,
  CardHeader,
  IconButton,
  Stack,
  Table,
  TableBody,
  TableContainer,
  Tooltip,
} from "@mui/material";
import AgencyTableToolbar from "./agency-table-toolbar";
import {
  IAgency,
  IAgencyTableFilterValue,
  IAgencyTableFilters,
} from "@/shared/types/agency";
import useTable from "@/shared/components/table/use-table";
import AgencyTableFiltresResult from "./agency-table-filters";
import {
  TableEmptyRows,
  TableHeadCustom,
  TableNoData,
  TablePaginationCustom,
  TableSelectedAction,
  emptyRows,
  getComparator,
} from "@/shared/components/table";
import { useBoolean, useRouter } from "@/hooks";
import Scrollbar from "@/components/scrollbar";
import AgencyTableRow from "./agency-table-row";
import { useSnackbar } from "@/components/snackbar";
import { ConfirmDialog } from "@/components/custom-dialog";
import { useAgencyUpdates } from "@/contexts/agency-updates-context";
import { checkManagerOrAdmin } from '@/utils/check-permissions';

const defaultFilters: IAgencyTableFilters = {
  name: "",
};

const TABLE_HEAD = [
  { id: "nameAgency", label: "Name" },
  { id: "createDate", label: "Create" },
  { id: "phoneNumber", label: "Phone Number" },
  { id: "participant", label: "Users" },
  { id: "" },
];

type Props = {
  admin?: boolean;
};

export default function AgencyListView({ admin }: Props) {
  const settings = useSettingsContext();
  const table = useTable({ defaultOrderBy: "createDate" });
  const confirm = useBoolean();
  const router = useRouter();
  const { enqueueSnackbar } = useSnackbar();
  const denseHeight = table.dense ? 56 : 56 + 20;
  const { setRefreshAgencyList } = useAgencyUpdates();

  // Fetch data from API
  const [tableData, setTableData] = useState<IAgency[]>([]);

  const fetchApprovedAgencies = async () => {
    try {
      const response = await axiosInstancee.get<IAgency[]>("/api/user/with-users");
      const approvedAgencies = response.data.filter(
        (agency: IAgency) => agency.status === "ACTIVE"
      );
      setTableData(approvedAgencies);
    } catch (error) {
      enqueueSnackbar("Failed to fetch agencies", { variant: "error" });
    }
  };

  useEffect(() => {
    fetchApprovedAgencies();
    setRefreshAgencyList(() => fetchApprovedAgencies);
  }, [setRefreshAgencyList]);

  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;
  }

  // Filter state
  const [filters, setFilters] = useState(defaultFilters);
  const canReset = !!filters.name;

  // Filtered and sorted data
  const dataFiltered = applyFilter({
    inputData: tableData,
    comparator: getComparator(table.order, table.orderBy),
    filters,
  });

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

  // Paginated data
  const dataInPage = dataFiltered.slice(
    table.page * table.rowsPerPage,
    table.page * table.rowsPerPage + table.rowsPerPage
  );

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

  const handleDeleteRow = useCallback(
    async (id: string) => {
      try {
        // Call the backend delete API
        await axiosInstancee.delete(`/api/user/agency/${id}`);
        enqueueSnackbar("Delete success!");
  
        // Update the table data
        const updatedData = tableData.filter((row) => row.id !== id);
        setTableData(updatedData);
        table.onUpdatePageDeleteRow(dataInPage.length);
      } catch (error) {
        enqueueSnackbar("Failed to delete agency", { variant: "error" });
      }
    },
    [dataInPage.length, enqueueSnackbar, table, tableData]
  );

  const handleDeleteRows = useCallback(async () => {
    try {
      // Delete selected agencies
      await Promise.all(
        table.selected.map((id) => axiosInstancee.delete(`/api/user/agency/${id}`))
      );
      enqueueSnackbar("Delete success!");
  
      // Update the table data
      const updatedData = tableData.filter(
        (row) => !table.selected.includes(row.id)
      );
      setTableData(updatedData);
      table.onUpdatePageDeleteRows({
        totalRowsInPage: dataInPage.length,
        totalRowsFiltered: dataFiltered.length,
      });
    } catch (error) {
      enqueueSnackbar("Failed to delete selected agencies", { variant: "error" });
    }
  }, [
    dataFiltered.length,
    dataInPage.length,
    enqueueSnackbar,
    table,
    tableData,
  ]);

  const handleEditRow = useCallback(
    (id: string) => {
      router.push(paths.dashboard.agency.edit(id));
    },
    [router]
  );

  const handleViewRow = useCallback(
    (id: string) => {
      router.push(paths.dashboard.agency.details(id));
    },
    [router]
  );

  return (
    <>
      {!admin && (
        <CustomBreadcrumbs
          heading="List"
          links={[
            { name: "Dashboard", href: paths.dashboard.root },
            { name: "Agency", href: paths.dashboard.agency.list },
            { name: "List" },
          ]}
          action={
            <Button
              component={RouterLink}
              href={paths.dashboard.agency.create}
              variant="contained"
              startIcon={<Iconify icon="mingcute:add-line" />}
              sx={{
                backgroundColor: '#144dd5',
                '&:hover': {
                  backgroundColor: '#144dd5',
                },
            
                textTransform: 'none',
                px: 2,
                marginLeft: 2,
              }}
            >
              New Agency
            </Button>
          }
          sx={{ mb: { xs: 3, md: 5 } }}
        />
      )}
      <Card sx={{boxShadow: 'none'  }}>
        {admin && <CardHeader title="List Agency Account" />}
        <AgencyTableToolbar filters={filters} onFilters={handleFilters} />
        {canReset && (
          <AgencyTableFiltresResult
            filters={filters}
            onFilters={handleFilters}
            onResetFilters={() => setFilters(defaultFilters)}
            results={dataFiltered.length}
            sx={{ p: 2.5, pt: 0 }}
          />
        )}
        <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)
              );
            }}
            action={
              <Stack direction="row">
                <Tooltip title="Delete">
                  <IconButton color="primary" onClick={confirm.onTrue}>
                    <Iconify icon="solar:trash-bin-trash-bold" />
                  </IconButton>
                </Tooltip>
              </Stack>
            }
          />
          <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}
                onSelectAllRows={(checked) =>
                  table.onSelectAllRows(
                    checked,
                    dataFiltered.map((row) => row.id)
                  )
                }
              />
              <TableBody>
                {dataInPage.map((row) => (
                  <AgencyTableRow
                    key={row.id}
                    row={row}
                    selected={table.selected.includes(row.id)}
                    onSelectRow={() => table.onSelectRow(row.id)}
                    onViewRow={() => handleViewRow(row.id)}
                    onEditRow={() => handleEditRow(row.id)}
                    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>
      <ConfirmDialog
        open={confirm.value}
        onClose={confirm.onFalse}
        title="Delete"
        content={
          <>
            Are you sure want to delete <strong>{table.selected.length}</strong>{" "}
            items?
          </>
        }
        action={
          <Button
            variant="contained"
            color="error"
            onClick={() => {
              handleDeleteRows();
              confirm.onFalse();
            }}
          >
            Delete
          </Button>
        }
      />
    </>
  );
}

function applyFilter({
  inputData,
  comparator,
  filters,
}: {
  inputData: IAgency[];
  comparator: (a: any, b: any) => number;
  filters: IAgencyTableFilters;
}) {
  const { name } = filters;

  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((agency) => {
      const agencyName = agency.name.toLowerCase();
      const searchName = name.toLowerCase();

      // Check if the name matches exactly or starts with the prefix
      return agencyName === searchName || agencyName.startsWith(searchName);
    });
  }

  return inputData;
}
