import {
  Box,
  Button,
  Paper,
  Stack,
  Step,
  StepLabel,
  Stepper,
  Table,
  TableBody,
  TableCell,
  TableRow,
  Typography,
} from "@mui/material";
import { HasChildren } from "@types";
import { mailRequest } from "api/app/receipt-issuing-order";
import { getPrefName } from "codes/prefcode";
import useAPICall from "hooks/useAPICall";
import useApp from "hooks/useApp";
import useSnackbarCustom from "hooks/useSnackbarCustom";
import { useMemo, useState } from "react";
import useInputMailStep from "./hooks/useInputMailStep";

type TableRowCustomProps = {
  title: string;
  value: string;
};
const TableRowCustom = ({ title, value }: TableRowCustomProps) => {
  return (
    <TableRow>
      <TableCell sx={{ borderRight: "1px solid rgba(224, 224, 224, 1)" }}>
        {title}
      </TableCell>
      <TableCell>{value}</TableCell>
    </TableRow>
  );
};

type SectionProps = {
  title: string;
  subtitle?: string;
} & HasChildren;
const Section = ({ title, subtitle, children }: SectionProps) => {
  return (
    <Paper
      sx={{ py: 2, border: "1px solid  rgba(224, 224, 224, 1)" }}
      elevation={0}
    >
      <Box>
        <Typography variant="subtitle1">{title}</Typography>
        {subtitle && <Typography variant="body2">{subtitle}</Typography>}
      </Box>
      <Box sx={{ mt: 2 }}>{children}</Box>
    </Paper>
  );
};

export default function MailOrder() {
  const {
    tokenResult,
    token,
    navigateToHome,
    fetch,
    receiptIssuingOrder: order,
  } = useApp();

  const { error } = useSnackbarCustom();

  const [mode, setMode] = useState<"input" | "confirm" | "done">("input");

  const input = useInputMailStep({
    onNext: () => {
      setMode("confirm");
    },
    onPrev: () => {
      navigateToHome();
    },
  });

  const requestMailAPI = useAPICall({
    apiMethod: mailRequest,
    onSuccess: () => {
      fetch();
      setMode("done");
    },
    onFailed: () => {
      error("登録失敗");
    },
  });

  const currentStep = useMemo(() => {
    if (mode === "input") return 0;
    if (mode === "confirm") return 1;
    if (mode === "done") return 2;
  }, [mode]);

  const handleConfirm = () => {
    if (!order) return;
    requestMailAPI.callAPI({
      access_token: token,
      timestamp: order.updated_at,
      ...input.values(),
    });
  };

  if (tokenResult !== "ok") {
    return null;
  }

  return (
    <>
      <Box sx={{ p: 3, pt: 5, mx: "auto", maxWidth: 500 }} textAlign="center">
        <Stack spacing={3}>
          <Box>
            <Typography variant="h5">領収証郵送依頼</Typography>
          </Box>

          <Section title="">
            <Stepper activeStep={currentStep}>
              <Step>
                <StepLabel>郵送先情報入力</StepLabel>
              </Step>
              <Step>
                <StepLabel>確認</StepLabel>
              </Step>
              <Step>
                <StepLabel>完了</StepLabel>
              </Step>
            </Stepper>
            {mode === "input" && input.element}
            {mode === "confirm" && (
              <Stack spacing={2} sx={{ p: 1, py: 3, m: 1 }}>
                <Typography variant="h5">郵送先情報確認</Typography>
                <Table>
                  <TableBody>
                    <TableRowCustom
                      title="都道府県"
                      value={getPrefName(input.values("mail_pref_code"))}
                    />
                    <TableRowCustom
                      title="郵便番号"
                      value={"〒" + input.values("mail_zip_code")}
                    />
                    <TableRowCustom
                      title="市区町村"
                      value={input.values("mail_address1")}
                    />
                    <TableRowCustom
                      title="番地等"
                      value={input.values("mail_address2")}
                    />
                    <TableRowCustom
                      title="建物名・部屋番号等"
                      value={input.values("mail_address3")}
                    />
                    <TableRowCustom
                      title="宛名"
                      value={input.values("mail_name")}
                    />
                  </TableBody>
                </Table>
                <Box>
                  <Stack>
                    <Box>郵送先に間違いがないか確認してください。</Box>
                    <Box>投函まで数営業日を要しますのでご了承ください。</Box>
                  </Stack>
                </Box>
                <Stack direction="row" spacing={2}>
                  <Button
                    variant="text"
                    onClick={() => {
                      setMode("input");
                    }}
                  >
                    戻る
                  </Button>
                  <Button variant="contained" onClick={handleConfirm}>
                    確定
                  </Button>
                </Stack>
              </Stack>
            )}
            {mode === "done" && (
              <Stack spacing={2} sx={{ p: 1, py: 3, m: 1 }}>
                <Box>郵送依頼を受付いたしました。</Box>
                <Box>到着までしばらくお待ちください。</Box>
                <Button onClick={navigateToHome}>戻る</Button>
              </Stack>
            )}
          </Section>
        </Stack>
      </Box>
    </>
  );
}
