import {
  Box,
  Button,
  Divider,
  Grid,
  Paper,
  Stack,
  Typography,
} from "@mui/material";
import {
  ReceiptIssuingOrderHTCustom,
  getReceiptIssuingOrders,
} from "api/custom/hello-techno/receipt-issuing-order";
import { PageID } from "codes/page";
import { getPrefName } from "codes/prefcode";
import { SimpleDataList } from "components/table";
import useAPICall from "hooks/useAPICall";
import useBackDrop from "hooks/useBackDrop";
import useDashboard from "hooks/useDashBoard";
import useNavigateCustom from "hooks/useNavigateCustom";
import useSnackbarCustom from "hooks/useSnackbarCustom";
import { isNumber } from "lodash";
import { useEffect, useMemo, useState } from "react";
import { useParams } from "react-router-dom";
import { sprintf } from "sprintf-js";
import { formatDateStr, formatDateTimeStr } from "utils/datetime";
import useMailPostCompleteDialog from "./hooks/useMailPostCompleteDialog";
import { getFullUrl } from "api/url";
import { ApiId } from "api";
import useChangeHandlerDialog from "../../hooks/useChangeHandlerDialog";

export default function ReceiptIssuingOrderDetail() {
  const { setHeaderTitle, setTabs } = useDashboard(
    PageID.DASHBOARD_RECEIPT_ISSUING_ORDER_DETAIL_CUSTOM_HELLO_TECHNO
  );

  const { navigate } = useNavigateCustom();

  const { error } = useSnackbarCustom();

  const { id: receiptIssuingOrderId } = useParams();

  const { setShowBackDrop } = useBackDrop();

  const [order, setOrder] = useState<ReceiptIssuingOrderHTCustom | null>(null);

  const postCompleteDialog = useMailPostCompleteDialog(order, () => {
    fetch();
  });

  const changeHandlerDialog = useChangeHandlerDialog(order, () => {
    fetch();
  });

  const { callAPI, sending } = useAPICall({
    apiMethod: getReceiptIssuingOrders,
    onSuccess: (res) => {
      const target = res.data.records[0];
      if (target) {
        setOrder(target);
      }
    },
    onFailed: () => {
      error("情報取得失敗");
      navigate(-1);
    },
  });

  const fetch = () => {
    if (receiptIssuingOrderId) {
      callAPI({
        id: receiptIssuingOrderId,
      });
    }
  };

  const hasMailOrder = useMemo(() => {
    return !!order?.status_order_mail_datetime;
  }, [order]);
  const orderInfo = useMemo(() => {
    if (!order) return [];
    return [
      { title: "ステータス", value: order.status_name },
      {
        title: "担当者",
        value: order.handler_name,
        end: (
          <Button
            sx={{ minWidth: 80 }}
            onClick={() => {
              changeHandlerDialog.open();
            }}
          >
            担当変更
          </Button>
        ),
      },
      { title: "SMS送信先", value: order.sms_phone_number },
      { title: "依頼日", value: formatDateStr(order.order_datetime) },
      { title: "運営会社", value: order.customer_name },
      { title: "駐車場", value: order.parking_name },
      { title: "利用日", value: formatDateStr(order.receipt_use_date) },
      {
        title: "精算連番",
        value: isNumber(order.adjust_seq_no)
          ? sprintf("%06d", order.adjust_seq_no)
          : "-",
      },
      {
        title: "金額",
        value: isNumber(order.receipt_amount)
          ? order.receipt_amount.toLocaleString() + "円"
          : "-",
      },
      {
        title: "消費税(内税)",
        value:
          isNumber(order.tax_amount) && isNumber(order.tax_rate)
            ? order.tax_amount.toLocaleString() + "円(" + order.tax_rate + "%)"
            : "-",
      },
      { title: "備考", value: order.memo },
    ];
  }, [order]);

  const mailStatus1 = useMemo(() => {
    if (!order) return [];
    return [{ title: "郵送依頼", value: hasMailOrder ? "あり" : "なし" }];
  }, [order]);
  const mailStatus2 = useMemo(() => {
    if (!order || !hasMailOrder) return [];
    return [
      { title: "郵便番号", value: "〒" + order.mail_zip_code },
      { title: "都道府県", value: getPrefName(order.mail_pref_code ?? "") },
      { title: "市区町村", value: order.mail_address1 },
      { title: "番地等", value: order.mail_address2 },
      { title: "建物名/部屋番号等", value: order.mail_address3 },
      { title: "宛名", value: order.mail_name },
    ];
  }, [order]);

  const receiptInfo = useMemo(() => {
    if (!order) return [];
    return [
      { title: "領収証番号", value: order.receipt_no },
      {
        title: "宛名",
        value: order.receipt_name,
      },
    ];
  }, [order]);

  const actionDatetimes = useMemo(() => {
    if (!order) return [];
    return [
      {
        title: "SMS送信",
        value: formatDateTimeStr(order.status_sms_send_datetime),
      },
      {
        title: "初回アクセス",
        value: formatDateTimeStr(order.status_first_access_datetime),
      },
      {
        title: "領収証確定",
        value: formatDateTimeStr(order.status_receipt_confirm_datetime),
      },
      {
        title: "郵送依頼",
        value: formatDateTimeStr(order.status_order_mail_datetime),
      },
      { title: "郵送投函", value: formatDateStr(order.status_mail_post_date) },
      {
        title: "領収証ダウンロード",
        value: formatDateTimeStr(order.status_receipt_download_datetime),
      },
      {
        title: "メール配信依頼",
        value: formatDateTimeStr(
          order.status_receipt_email_send_order_datetime
        ),
      },
      {
        title: "メール配信完了",
        value: formatDateTimeStr(order.status_receipt_email_send_datetime),
      },
    ];
  }, [order]);

  const downloadUrl = useMemo(() => {
    return getFullUrl(ApiId.DOWNLOAD_RECEIPT_LETTER) + "?id=" + order?.id;
  }, [order]);

  useEffect(() => {
    setHeaderTitle("領収証発行依頼");
    setTabs(null);

    fetch();
  }, []);

  useEffect(() => {
    setShowBackDrop(sending);
  }, [sending]);

  return (
    <>
      <Box>
        <Grid container spacing={2}>
          <Grid item xs={12}>
            <Stack direction="row" spacing={2}>
              <Button onClick={() => navigate(-1)}>戻る</Button>
            </Stack>
          </Grid>
          <Grid item xs={4}>
            <Paper elevation={0} sx={{ border: "1px solid" }}>
              <Stack spacing={2}>
                <Typography
                  variant="h6"
                  fontWeight="bold"
                  sx={{ my: 2, textAlign: "center" }}
                >
                  依頼内容
                </Typography>
                <SimpleDataList data={orderInfo} />
                <Divider sx={{ my: 2 }} />
                <Typography
                  variant="subtitle1"
                  sx={{ my: 2, textAlign: "center" }}
                >
                  領収証情報
                </Typography>
                <SimpleDataList data={receiptInfo} />
              </Stack>
            </Paper>
          </Grid>
          <Grid item xs={4}>
            <Paper elevation={0} sx={{ pb: 2, border: "1px solid" }}>
              <Stack spacing={2}>
                <Typography
                  variant="h6"
                  fontWeight="bold"
                  sx={{ my: 2, textAlign: "center" }}
                >
                  郵送管理
                </Typography>
                <SimpleDataList data={mailStatus1} />
                {hasMailOrder && (
                  <>
                    <Divider sx={{ my: 2 }} />
                    <Typography
                      variant="subtitle1"
                      sx={{ my: 2, textAlign: "center" }}
                    >
                      郵送先
                    </Typography>
                    <SimpleDataList data={mailStatus2} />
                    <Divider />
                    <Stack direction="row" spacing={2} sx={{ px: 2 }}>
                      <Button
                        variant="contained"
                        href={downloadUrl}
                        target="_blank"
                      >
                        印字
                      </Button>

                      <Button
                        variant="contained"
                        onClick={postCompleteDialog.open}
                      >
                        投函完了
                      </Button>
                    </Stack>
                    {postCompleteDialog.element}
                  </>
                )}
              </Stack>
            </Paper>
          </Grid>
          <Grid item xs={4}>
            <Paper elevation={0} sx={{ border: "1px solid" }}>
              <Stack spacing={2}>
                <Typography
                  variant="h6"
                  fontWeight="bold"
                  sx={{ my: 2, textAlign: "center" }}
                >
                  各種アクション日時
                </Typography>
                <SimpleDataList data={actionDatetimes} />
              </Stack>
            </Paper>
          </Grid>
        </Grid>
      </Box>
      {changeHandlerDialog.element}
    </>
  );
}
