"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';
import Container from "@mui/material/Container";

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 {
      // Get the current user's email and roles from localStorage
      const userString = localStorage.getItem("user");
      const currentUser = userString ? JSON.parse(userString) : {};
      const userEmail = currentUser?.email;
      const roleString = localStorage.getItem("role");
      const userRoles = roleString ? JSON.parse(roleString) : [];

      if (!userEmail) {
        enqueueSnackbar("User information not found", { variant: "error" });
        return;
      }
      
      // Determine if user is an admin
      const isAdmin = userRoles.includes("ADMIN");
      
      // Choose endpoint based on admin status
      let endpoint = isAdmin 
        ? "/api/user/with-users" 
        : `/api/user/my-agencies/email/${encodeURIComponent(userEmail)}`;
      
      const response = await axiosInstancee.get<IAgency[]>(endpoint);
      
      // Filter only active agencies
      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 (!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 (
    <Container maxWidth={settings.themeStretch ? false : "lg"}>
      <Stack spacing={2.5}>
        {!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,
                }}
              >
                New Agency
              </Button>
            }
            sx={{ mb: { xs: 3, md: 5 }, px: 0 }}
          />
        )}

        <Card sx={{ boxShadow: 'none' }}>
          {admin && <CardHeader title="List Agency Account" sx={{ px: 0 }} />}
          
          <AgencyTableToolbar 
            filters={filters} 
            onFilters={handleFilters}
            sx={{ px: 0 }}
          />

          {canReset && (
            <AgencyTableFiltresResult
              filters={filters}
              onFilters={handleFilters}
              onResetFilters={() => setFilters(defaultFilters)}
              results={dataFiltered.length}
              sx={{ p: 2.5, pt: 0, px: 0 }}
            />
          )}

          <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)
                );
              }}
              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}
            sx={{ px: 0 }}
          />
        </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>
          }
        />
      </Stack>
    </Container>
  );
}

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