import { Box, Button, Stack, Typography } from "@mui/material";
import { HasChildren } from "@types";
import {
  uploadOtherLicenseImages,
  uploadStudentLicenseImages,
} from "api/season-ticket-contract";
import RequireChip from "components/chip/RequireChip";
import { FormProvider } from "components/hook-form";
import { RHFUpload } from "components/hook-form/RHFUpload";
import StackRow from "components/stack/StackRow";
import { useSeasonTicketContractContext } from "contexts/dashboard/SeasonTicketContractContext";
import useAPICall from "hooks/useAPICall";
import useAuth from "hooks/useAuth";
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 = {
  file1: File[];
  file2: File[];
  file3: File[];
};

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

  const { navigateWhenChanged, navigate } = useNavigateCustom();
  const { selectedseasonTicketContract, initialized } =
    useSeasonTicketContractContext();

  const [done, setDone] = useState(false);
  const { error } = useSnackbarCustom();

  const form = useForm<FormProps>({
    defaultValues: {
      file1: [],
      file2: [],
      file3: [],
    },
  });

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

  const file1 = form.watch("file1");
  const file2 = form.watch("file2");
  const file3 = form.watch("file3");

  const canSend = useMemo(() => {
    return file1.length !== 0;
  }, [file1]);

  const handleSubmit = (data: FormProps) => {
    if (!selectedseasonTicketContract) return;
    const files = [...file1, ...file2, ...file3];
    callUploadOtherLicenseImages({
      images: files,
      season_ticket_contract_record_no:
        selectedseasonTicketContract.season_ticekt_contract_record_no ?? "",
    });
  };

  useEffect(() => {
    if (file1.length === 0) {
      if (file2.length !== 0) {
        form.setValue("file2", []);
      }
      if (file3.length !== 0) {
        form.setValue("file3", []);
      }
    }
    if (file2.length === 0) {
      if (file3.length !== 0) {
        form.setValue("file3", []);
      }
    }
  }, [file1, file2, file3]);

  useEffect(() => {
    if (initialized && !selectedseasonTicketContract) {
      navigateWhenChanged(
        getPath(PageID.DASHBOARD_SEASON_TICKET_CONTRACT_LIST)
      );
    }
  }, [initialized, selectedseasonTicketContract]);

  useEffect(() => {
    setHeaderTitle("障害者手帳アップロード");
    setTabs(null);
  }, []);

  if (!selectedseasonTicketContract) {
    return null;
  }

  if (done) {
    return (
      <Stack spacing={2}>
        <Box>アップロードしました</Box>
        <Box>
          <Button
            onClick={() => {
              navigate(-1);
            }}
          >
            戻る
          </Button>
        </Box>
      </Stack>
    );
  }

  return (
    <FormProvider methods={form} onSubmit={form.handleSubmit(handleSubmit)}>
      <Stack spacing={2}>
        <Box>
          <Button
            onClick={() => {
              navigate(-1);
            }}
          >
            戻る
          </Button>
        </Box>
        <AreaBox label="前回アップロード日時">
          <Typography>
            {selectedseasonTicketContract.student_license_images_upload_datetime ??
              "-"}
          </Typography>
        </AreaBox>
        <AreaBox label="１枚目">
          <RHFUpload name="file1" />
        </AreaBox>
        {file1.length !== 0 && (
          <AreaBox label="２枚目">
            <RHFUpload name="file2" />
          </AreaBox>
        )}
        {file2.length !== 0 && (
          <AreaBox label="３枚目">
            <RHFUpload name="file3" />
          </AreaBox>
        )}
        <Box>
          <Button type="submit" variant="contained" disabled={!canSend}>
            送信
          </Button>
        </Box>
      </Stack>
    </FormProvider>
  );
}
