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

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 EmailOrder() {
  const {
    tokenResult,
    token,
    navigateToHome,
    fetch,
    receiptIssuingOrder: order,
  } = useApp();

  const { error } = useSnackbarCustom();

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

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

  const requestEmailAPI = useAPICall({
    apiMethod: emailRequest,
    backDrop: true,
    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;
    requestEmailAPI.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">領収証Email送付依頼</Typography>
          </Box>

          <Section title="">
            <Stepper activeStep={currentStep}>
              <Step>
                <StepLabel>Email送信先入力</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">Email送信先情報確認</Typography>
                <Table>
                  <TableBody>
                    <TableRowCustom
                      title="Email"
                      value={input.values("email")}
                    />
                  </TableBody>
                </Table>
                <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>
                <Button onClick={navigateToHome}>戻る</Button>
              </Stack>
            )}
          </Section>
        </Stack>
      </Box>
    </>
  );
}
