import { Box, Button, Stack, Typography } from "@mui/material";
import { HasChildren } from "@types";
import {
  getSeasonTicketContractTerminateOptions,
  orderSeasonTicketContractTerminate,
  reOrderSticker,
} from "api/season-ticket-contract";
import RequireChip from "components/chip/RequireChip";
import {
  FormProvider,
  RHFCheckbox,
  RHFMultiCheckbox,
  RHFSelect,
  RHFTextField,
} from "components/hook-form";
import RHFDatePicker from "components/hook-form/RHFDatePicker";
import { SelectOptionProps } from "components/hook-form/RHFSelect";
import StackRow from "components/stack/StackRow";
import { useSeasonTicketContractContext } from "contexts/dashboard/SeasonTicketContractContext";
import useAPICall from "hooks/useAPICall";
import useDashboard from "hooks/useDashBoard";
import useNavigateCustom from "hooks/useNavigateCustom";
import useSnackbarCustom from "hooks/useSnackbarCustom";
import { PageID, TabID } from "pages";
import { useEffect, useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { getPath } from "routes/path";

type AreaBoxProps = {
  label: string;
  require?: boolean;
} & HasChildren;
function AreaBox({ label, children, require }: AreaBoxProps) {
  return (
    <Box>
      <StackRow>
        <Typography variant="subtitle1">〇{label}</Typography>
        <RequireChip require={require ?? false} />
      </StackRow>
      {children}
    </Box>
  );
}

type FormProps = {
  date: string;
  reason: string[];
  other_reason: string;
  opinion: string;
  memo: string;
};

export default function TerminateOrder() {
  const { setHeaderTitle, setTabs } = useDashboard(
    PageID.DASHBOARD_SEASON_TICKET_CONTRACT_TERMINATE_ORDER,
    TabID.NONE
  );

  const form = useForm<FormProps>({
    defaultValues: {
      date: "",
      reason: [],
      other_reason: "",
      opinion: "",
      memo: "",
    },
  });

  const { navigateWhenChanged, navigate } = useNavigateCustom();

  const { error } = useSnackbarCustom();

  const { selectedseasonTicketContract } = useSeasonTicketContractContext();

  const [monthes, setMonthes] = useState<string[]>([]);

  const monthOptions: SelectOptionProps[] = useMemo(() => {
    return monthes.map((ele) => ({
      value: ele,
      label: ele,
    }));
  }, [monthes]);

  const [done, setDone] = useState(false);

  const { callAPI: callOrderSeasonTicketContractTerminate } = useAPICall({
    apiMethod: orderSeasonTicketContractTerminate,
    backDrop: true,
    onSuccess: () => {
      setDone(true);
    },
    onFailed: () => {
      error("依頼失敗しました");
    },
  });

  const { callAPI: callGetSeasonTicketContractTerminateOptions } = useAPICall({
    apiMethod: getSeasonTicketContractTerminateOptions,
    backDrop: true,
    onSuccess: ({ data }) => {
      setMonthes(data.monthes);
    },
  });

  const handleSubmit = (data: FormProps) => {
    console.log(data);

    if (selectedseasonTicketContract === null) return;

    callOrderSeasonTicketContractTerminate({
      ...data,
      season_ticket_contract_record_no:
        selectedseasonTicketContract.season_ticekt_contract_record_no ?? "",
      reason: data.reason.join(","),
    });
  };

  const reasons = useMemo(() => {
    return [
      "転居／転勤のため",
      "就職／進学／卒業のため",
      "料金が高いため",
      "支払いが困難なため",
      "車／バイク／自転車に乗らなくなったため",
      "より良い駐車場／駐輪場が見つかったため",
      "駐車場／駐輪場に不満があるため（詳細）",
      "その他（詳細）",
    ].map((ele, index) => ({
      label: String(index + 1) + "." + String(ele),
      value: ele,
    }));
  }, []);

  useEffect(() => {
    setHeaderTitle("解約依頼申請");
    setTabs(null);
  }, [setHeaderTitle, setTabs]);

  useEffect(() => {
    if (selectedseasonTicketContract === null) {
      navigateWhenChanged(
        getPath(PageID.DASHBOARD_SEASON_TICKET_CONTRACT_LIST)
      );
      return;
    }
    callGetSeasonTicketContractTerminateOptions({
      season_ticket_contract_record_no:
        selectedseasonTicketContract.season_ticekt_contract_record_no ?? "",
    });
  }, [selectedseasonTicketContract]);

  if (selectedseasonTicketContract === null) {
    return null;
  }
  if (done) {
    return (
      <Box sx={{ mt: 1 }}>
        <Stack spacing={2}>
          <Box>依頼しました</Box>
          <Box>
            <Button
              onClick={() => {
                navigate(-1);
              }}
            >
              戻る
            </Button>
          </Box>
        </Stack>
      </Box>
    );
  }

  return (
    <FormProvider methods={form} onSubmit={form.handleSubmit(handleSubmit)}>
      <Box sx={{ mt: 1 }}>
        <Stack spacing={2}>
          <Box>
            <Button
              onClick={() => {
                navigate(-1);
              }}
            >
              戻る
            </Button>
          </Box>

          <AreaBox label="解約希望日" require>
            <RHFSelect name="date" size="small" options={monthOptions} />
          </AreaBox>
          <AreaBox label="解約理由(複数選択可)" require>
            <Typography variant="body2">
              解約の理由についてお聞かせ下さい（複数選択可）
            </Typography>

            <RHFMultiCheckbox name="reason" options={reasons} />
          </AreaBox>
          <AreaBox label="解約理由詳細">
            <Typography variant="body2">
              前質問 7・8を選択された方　詳細を詳しくお聞かせください。
            </Typography>
            <RHFTextField
              name="reason_other"
              size="small"
              multiline
              minRows={3}
              maxRows={10}
            />
          </AreaBox>
          <AreaBox label="ご意見">
            <Typography variant="body2">
              今後の管理運営に生かすため、ご意見がありましたらご記入ください。
            </Typography>
            <RHFTextField
              name="opinion"
              size="small"
              multiline
              minRows={3}
              maxRows={10}
            />
          </AreaBox>
          <AreaBox label="備考">
            <Typography variant="body2">
              ご不明点等がございましたらご入力ください。お電話またはメールにて回答させていただきます。
            </Typography>
            <RHFTextField
              name="memo"
              size="small"
              multiline
              minRows={3}
              maxRows={10}
            />
          </AreaBox>

          <Box>
            <Button variant="contained" type="submit">
              確定
            </Button>
          </Box>
        </Stack>
      </Box>
    </FormProvider>
  );
}
