import { yupResolver } from "@hookform/resolvers/yup";
import { Box, Button, Stack, Typography } from "@mui/material";
import { HasChildren } from "@types";
import { getHTCustomers, getHTParkings } from "api/custom/hello-techno";
import {
  FormProvider,
  RHFAutoComplete,
  RHFTextField,
} from "components/hook-form";
import {
  AutoCompleteOption,
  AutoCompleteOptionType,
} from "components/hook-form/RHFAutoComplete";
import useAPICall from "hooks/useAPICall";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import * as Yup from "yup";

type AreaBoxProps = {
  title: string;
} & HasChildren;
function AreaBox({ title, children }: AreaBoxProps) {
  return (
    <Box sx={{ maxWidth: 500 }}>
      <Typography variant="subtitle1">{title}</Typography>
      {children}
    </Box>
  );
}

type FormProps = {
  customerCode: AutoCompleteOptionType;
  parkingManagementCode: AutoCompleteOptionType;
  adjustSeqNo: string;
};

type Props = {
  onNext?: VoidFunction;
};
export default function useSelectParkingStep({ onNext }: Props) {
  const [customers, setCustomers] = useState<AutoCompleteOption[]>([]);
  const [parkings, setParkings] = useState<AutoCompleteOption[]>([]);

  const customerAPI = useAPICall({
    apiMethod: getHTCustomers,
    onSuccess: ({ data }) => {
      const options: AutoCompleteOption[] = data.records.map(
        ({ customer_code, name }) => {
          return {
            label: name,
            value: customer_code,
          };
        }
      );
      setCustomers(options);
    },
  });

  const parkingAPI = useAPICall({
    apiMethod: getHTParkings,
    onSuccess: ({ data }) => {
      const options: AutoCompleteOption[] = data.records.map(
        ({ parking_management_code, name }) => {
          return {
            label: name,
            value: parking_management_code,
          };
        }
      );
      setParkings(options);
    },
  });

  const form = useForm<FormProps>({
    defaultValues: {
      customerCode: null,
      parkingManagementCode: null,
      adjustSeqNo: "",
    },
    resolver: yupResolver(
      Yup.object().shape({
        customerCode: Yup.object().required("必須項目です"),
        parkingManagementCode: Yup.object().required("必須項目です"),
        adjustSeqNo: Yup.number()
          .nullable()
          .transform((value, originalValue) =>
            String(originalValue).trim() === "" ? null : value
          )
          .typeError("数値を入力してください"),
      })
    ),
  });

  const customerCode = form.watch("customerCode.value");

  const handleSubmit = () => {
    if (onNext) {
      onNext();
    }
  };

  // 顧客一覧取得
  useEffect(() => {
    customerAPI.callAPI({});
  }, []);

  // 駐車場一覧取得
  useEffect(() => {
    setParkings([]);
    form.setValue("parkingManagementCode", null);

    if (customerCode) {
      parkingAPI.callAPI({ customer_code: customerCode });
    }
  }, [customerCode]);

  const element = (
    <FormProvider methods={form} onSubmit={form.handleSubmit(handleSubmit)}>
      <Stack spacing={2} sx={{ p: 1, m: 1 }}>
        <AreaBox title="運営会社">
          <RHFAutoComplete
            name="customerCode"
            options={customers}
            size="small"
          />
        </AreaBox>
        <AreaBox title="駐車場">
          <RHFAutoComplete
            name="parkingManagementCode"
            options={parkings}
            size="small"
          />
        </AreaBox>
        <AreaBox title="精算連番">
          <RHFTextField name="adjustSeqNo" size="small" />
        </AreaBox>
        <Stack direction="row" spacing={2}>
          <Button variant="contained" type="submit">
            次へ
          </Button>
        </Stack>
      </Stack>
    </FormProvider>
  );

  return { element, values: form.getValues, setValue: form.setValue };
}
