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

export interface Props {
  auth: auth[];
}

const AuthorityAllocation: React.FC<Props> = ({ auth }) => {
  const { t } = useTranslation();
  const {
    setValue,
    getValues,
    formState: { defaultValues },
    reset,
    resetField,
  } = useFormContext<CreateGroupInputs>();
  const initialAuths = auth.map((a) => ({ ...a })).sort((a, b) => a.id - b.id);
  const [filteredAuths, setFilteredAuths] = useState(initialAuths);
  const [selectedAuths, setSelectedAuths] = useState<typeof filteredAuths>(
    () => {
      return filteredAuths.filter(
        (s) => getValues("addAuthIds")?.includes(s.id)
      );
    }
  );

  // Adding / Removing Auth
  const addAuth = useCallback((auth: auth) => {
    setSelectedAuths((a) => [...a, auth]);
  }, []);
  const removeAuth = useCallback((auth: auth) => {
    setSelectedAuths((a) => a.filter((a) => a.id !== auth.id));
  }, []);

  const clearAuth = useCallback(() => {
    if (defaultValues !== undefined) {
      resetField("addAuthIds");
      setSelectedAuths(
        initialAuths.filter((s) => defaultValues.addAuthIds?.includes(s.id))
      );
    }
  }, [defaultValues]);

  // Sync with form
  useEffect(() => {
    setValue(
      "addAuthIds",
      selectedAuths.map((a) => a.id)
    );
  }, [selectedAuths, setValue]);

  const AuthPoolColumns = useMemo<Column<auth>[]>(
    () => [
      {
        label: t("Add"),
        name: "id",
        onClick: addAuth,
        buttonIcon: <Add />,
      },
      { label: t("Authority"), name: "authority" },
      { label: t("Description"), name: "name" },
      //   { label: t("Current Position"), name: "currentPosition" },
    ],
    [addAuth, t]
  );

  const allocatedAuthColumns = useMemo<Column<auth>[]>(
    () => [
      {
        label: t("Remove"),
        name: "id",
        onClick: removeAuth,
        buttonIcon: <Remove color="warning" />,
      },
      { label: t("Authority"), name: "authority" },
      { label: t("Description"), name: "name" },
    ],
    [removeAuth, selectedAuths, 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(() => {
    setFilteredAuths(
      initialAuths.filter(
        (a) =>
          a.authority.toLowerCase().includes(query.toLowerCase()) ||
          a.name?.toLowerCase().includes(query.toLowerCase())
      )
    );
  }, [auth, query]);

  const resetAuth = React.useCallback(() => {
    clearQueryInput();
    clearAuth();
  }, [clearQueryInput, clearAuth]);

  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("Authority")} */}
              </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("Authority") + " / " + t("Description")}
                    InputProps={{
                      endAdornment: query && (
                        <InputAdornment position="end">
                          <IconButton onClick={clearQueryInput}>
                            <Clear />
                          </IconButton>
                        </InputAdornment>
                      ),
                    }}
                  />
                </Grid>
              </Grid>
              <Tabs value={tabIndex} onChange={handleTabChange}>
                <Tab label={t("Authority Pool")} />
                <Tab
                  label={`${t("Allocated Authority")} (${
                    selectedAuths.length
                  })`}
                />
              </Tabs>
              <Box sx={{ marginInline: -3 }}>
                {tabIndex === 0 && (
                  <SearchResults
                    noWrapper
                    items={differenceBy(filteredAuths, selectedAuths, "id")}
                    columns={AuthPoolColumns}
                  />
                )}
                {tabIndex === 1 && (
                  <SearchResults
                    noWrapper
                    items={selectedAuths}
                    columns={allocatedAuthColumns}
                  />
                )}
              </Box>
            </Stack>
          </CardContent>
        </Card>
      </FormProvider>
    </>
  );
};

export default AuthorityAllocation;
