import { Box, Grid, Stack, Typography } from "@mui/material";
import { Dictionary } from "@types";
import {
  運営会社ログインユーザ,
  顧客ログインユーザ一覧取得,
} from "api/login-user";
import { FormProvider, RHFTextField } from "components/hook-form";
import useAPICall from "hooks/useAPICall";
import useSearchConditionContext from "hooks/useSearchConditionContext";
import { UseTableReturn } from "hooks/useTable";
import { isEqual } from "lodash";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";

type FormProps = {
  name: string;
  email: string;
};

type CommonProps = {
  table: UseTableReturn<運営会社ログインユーザ>;
};
export default function SearchBox({ table }: CommonProps) {
  const [lastSendSearchCondition, setLastSendSearchCondition] =
    useState<object>({ default: false });
  const { condition, initialized, get, addCondition } =
    useSearchConditionContext();
  const form = useForm<FormProps>({
    defaultValues: {
      name: "",
      email: "",
    },
  });

  const { callAPI: call顧客一覧取得, makeSendData } = useAPICall({
    apiMethod: 顧客ログインユーザ一覧取得,
    form,
    backDrop: true,
    onSuccess: ({ data }) => {
      table.setRowData(data.list);
    },
  });

  const handleBlur = () => {
    addCondition(form.getValues());
  };
  const handleSubmit = async (data: FormProps) => {
    addCondition(data);
  };

  const fetch = async (data: Dictionary) => {
    const sendData = makeSendData(data);
    console.log({ sendData });
    if (!isEqual(sendData, lastSendSearchCondition)) {
      setLastSendSearchCondition(sendData);
      call顧客一覧取得(sendData);
    }
  };

  useEffect(() => {
    console.log({ initialized, condition });
    if (initialized) {
      fetch(condition);
    }
  }, [condition, initialized]);

  return (
    <FormProvider methods={form} onSubmit={form.handleSubmit(handleSubmit)}>
      <Box sx={{ p: 1, m: 1 }}>
        <Grid container spacing={2} mt={-1}>
          <Grid item xs={12} lg={6}>
            <Stack>
              <Typography>名前</Typography>
              <RHFTextField name="name" onBlur={handleBlur} />
            </Stack>
          </Grid>
          <Grid item xs={12} lg={6}>
            <Stack>
              <Typography>Email</Typography>
              <RHFTextField name="email" onBlur={handleBlur} />
            </Stack>
          </Grid>
        </Grid>
      </Box>
    </FormProvider>
  );
}
