"use client";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  FieldErrors,
  FormProvider,
  SubmitErrorHandler,
  SubmitHandler,
  useForm,
  useFormContext,
} from "react-hook-form";
import {
  Box,
  Card,
  CardContent,
  Grid,
  IconButton,
  InputAdornment,
  Stack,
  Tab,
  Tabs,
  TabsProps,
  TextField,
  Typography,
} from "@mui/material";
import { differenceBy } from "lodash";
import { CreateGroupInputs, auth } from "@/app/api/group/actions";
import SearchResults, { Column } from "../SearchResults";
import { Add, Clear, Remove, Search } from "@mui/icons-material";
import { UserResult } from "@/app/api/user";

export interface Props {
  users: UserResult[];
}

const UserAllocation: React.FC<Props> = ({ users }) => {
  const { t } = useTranslation();
  const {
    setValue,
    getValues,
    formState: { defaultValues },
    reset,
    resetField,
  } = useFormContext<CreateGroupInputs>();
  const initialUsers = users.map((u) => ({ ...u })).sort((a, b) => a.id - b.id);
  const [filteredUsers, setFilteredUsers] = useState(initialUsers);
  const [selectedUsers, setSelectedUsers] = useState<typeof filteredUsers>(
    () => {
      return filteredUsers.filter(
        (s) => getValues("addUserIds")?.includes(s.id)
      );
    }
  );
  const [deletedUserIds, setDeletedUserIds] = useState<number[]>([]);

  // Adding / Removing Auth
  const addUser = useCallback((users: UserResult) => {
    setSelectedUsers((a) => [...a, users]);
  }, []);

  const removeUser = useCallback((users: UserResult) => {
    setSelectedUsers((a) => a.filter((a) => a.id !== users.id));
    setDeletedUserIds((prevIds) => [...prevIds, users.id]);
  }, []);

  const clearUser = useCallback(() => {
    if (defaultValues !== undefined) {
      resetField("addUserIds");
      setSelectedUsers(
        initialUsers.filter((s) => defaultValues.addUserIds?.includes(s.id))
      );
    }
  }, [defaultValues]);

  // Sync with form
  useEffect(() => {
    setValue(
      "addUserIds",
      selectedUsers.map((u) => u.id)
    );
    setValue(
      "removeUserIds",
      deletedUserIds
    );
  }, [selectedUsers, deletedUserIds, setValue]);

  const UserPoolColumns = useMemo<Column<UserResult>[]>(
    () => [
      {
        label: t("Add"),
        name: "id",
        onClick: addUser,
        buttonIcon: <Add />,
      },
      { label: t("Username"), name: "username" },
      { label: t("Staff Name"), name: "name" },
    ],
    [addUser, t]
  );

  const allocatedUserColumns = useMemo<Column<UserResult>[]>(
    () => [
      {
        label: t("Remove"),
        name: "id",
        onClick: removeUser,
        buttonIcon: <Remove color="warning" />,
      },
      { label: t("Username"), name: "username" },
      { label: t("Staff Name"), name: "name" },
    ],
    [removeUser, selectedUsers, t]
  );

  const [query, setQuery] = React.useState("");
  const onQueryInputChange = React.useCallback<
    React.ChangeEventHandler<HTMLInputElement>
  >((e) => {
    setQuery(e.target.value);
  }, []);
  const clearQueryInput = React.useCallback(() => {
    setQuery("");
  }, []);

  React.useEffect(() => {
    const q = query.toLowerCase();
    setFilteredUsers(
      initialUsers.filter((item) => (
        item.username.toLowerCase().includes(q) ||
        item.name.toLowerCase().includes(q)
      ))
    );
  }, [users, query]);

  const resetUser = React.useCallback(() => {
    clearQueryInput();
    clearUser();
  }, [clearQueryInput, clearUser]);

  const formProps = useForm({});

  // Tab related
  const [tabIndex, setTabIndex] = React.useState(0);
  const handleTabChange = React.useCallback<NonNullable<TabsProps["onChange"]>>(
    (_e, newValue) => {
      setTabIndex(newValue);
    },
    []
  );

  return (
    <>
      <FormProvider {...formProps}>
        <Card sx={{ display: "block" }}>
          <CardContent
            sx={{ display: "flex", flexDirection: "column", gap: 1 }}
          >
            <Stack gap={2}>
              <Typography variant="overline" display="block">
                {t("User")}
              </Typography>
              <Grid container spacing={2} columns={{ xs: 6, sm: 12 }}>
                <Grid item xs={6} display="flex" alignItems="center">
                  <Search sx={{ marginInlineEnd: 1 }} />
                  <TextField
                    variant="standard"
                    fullWidth
                    onChange={onQueryInputChange}
                    value={query}
                    placeholder={t("Search by ") + t("Username") + " / " + t("Staff Name")}
                    InputProps={{
                      endAdornment: query && (
                        <InputAdornment position="end">
                          <IconButton onClick={clearQueryInput}>
                            <Clear />
                          </IconButton>
                        </InputAdornment>
                      ),
                    }}
                  />
                </Grid>
              </Grid>
              <Tabs value={tabIndex} onChange={handleTabChange}>
                <Tab label={t("User Pool")} />
                <Tab
                  label={`${t("Allocated Users")} (${selectedUsers.length})`}
                />
              </Tabs>
              <Box sx={{ marginInline: -3 }}>
                {tabIndex === 0 && (
                  <SearchResults
                    noWrapper
                    items={differenceBy(filteredUsers, selectedUsers, "id")}
                    columns={UserPoolColumns}
                  />
                )}
                {tabIndex === 1 && (
                  <SearchResults
                    noWrapper
                    items={selectedUsers}
                    columns={allocatedUserColumns}
                  />
                )}
              </Box>
            </Stack>
          </CardContent>
        </Card>
      </FormProvider>
    </>
  );
};

export default UserAllocation;
