import {
  Box,
  Button,
  Grid,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TablePagination,
  TableRow,
  Typography,
} from "@mui/material";
import {
  UseSummary,
  getUseSummaries,
  getUseSummaryYYYYMMs,
} from "api/custom/hello-techno/use-summary";
import { PageID, TabID } from "codes/page";
import { FormProvider } from "components/hook-form";
import RHFSelect, { SelectOptionProps } from "components/hook-form/RHFSelect";
import { TableHeadCustom } from "components/table";
import { SearchConditionContextProvider } from "contexts/SearchConditionContext";
import useAPICall from "hooks/useAPICall";
import useDashboard from "hooks/useDashBoard";
import useNavigateCustom from "hooks/useNavigateCustom";
import useSearchConditionContext from "hooks/useSearchConditionContext";
import useTable, { UseTableReturn } from "hooks/useTable";
import { useEffect, useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { sprintf } from "sprintf-js";

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

  const { navigateWhenChanged } = useNavigateCustom();

  useEffect(() => {
    setHeaderTitle("利用実績一覧");
    setTabs(null);
  }, []);

  return (
    <SearchConditionContextProvider>
      <Page />
    </SearchConditionContextProvider>
  );
}

function Page() {
  const table = useTable<UseSummary>();
  return (
    <Box>
      <SearchBox table={table} />
      <TableBox table={table} />
    </Box>
  );
}

type FormProps = {
  summary_yyyymm: string;
};

type CommonProps = {
  table: UseTableReturn<UseSummary>;
};
function SearchBox({ table }: CommonProps) {
  const {
    condition,
    initialized,
    get,
    addCondition: add,
  } = useSearchConditionContext();

  const form = useForm<FormProps>({
    defaultValues: {
      summary_yyyymm: "",
    },
  });

  const selectedYYYYMM = form.watch("summary_yyyymm");

  const [yyyymm, setYYYYMM] = useState<string[] | null>(null);

  const yyyymmOptions: SelectOptionProps[] = useMemo(() => {
    if (yyyymm === null) return [];
    return yyyymm.map((ele) => {
      return {
        value: ele,
        label: sprintf("%s/%s", ele.substring(0, 4), ele.substring(4, 6)),
      };
    });
  }, [yyyymm]);

  const downloadCsvUrl = useMemo(() => {
    if (!selectedYYYYMM) return "";
    const param = new URLSearchParams({
      summary_yyyymm: selectedYYYYMM,
    });

    return (
      process.env.REACT_APP_HOST_API_KEY +
      "/custom/hello-techno/use-summary/csv?" +
      param.toString()
    );
  }, [selectedYYYYMM]);

  const { callAPI: callGetUseSummaryYYYYMMs } = useAPICall({
    apiMethod: getUseSummaryYYYYMMs,
    backDrop: true,
    onSuccess: ({ data: { records } }) => {
      setYYYYMM(records);
    },
  });

  const {
    callAPI: callGetContracts,
    makeSendData,
    sending,
  } = useAPICall({
    apiMethod: getUseSummaries,
    backDrop: true,
    onSuccess: ({ data }) => {
      table.setRowData(data.records);
    },
  });

  const handleSubmit = async (data: FormProps) => {
    addCondition(data);
  };

  const addCondition = (data: FormProps) => {
    add({
      ...data,
    });
  };
  const fetch = async () => {
    const sendData = {
      ...condition,
      ...form.getValues(),
    };

    if (sendData.summary_yyyymm) {
      callGetContracts(sendData);
    }
  };

  // 初期値設定
  useEffect(() => {
    if (initialized && yyyymm !== null) {
      form.setValue(
        "summary_yyyymm",
        get("summary_yyyymm", yyyymm.find(() => true) ?? "")
      );
      addCondition(form.getValues());
    }
  }, [initialized, condition, yyyymm]);

  // Fetchアクション
  useEffect(() => {
    if (initialized) {
      fetch();
    }
  }, [condition, initialized, selectedYYYYMM]);

  useEffect(() => {
    callGetUseSummaryYYYYMMs({});
  }, []);

  return (
    <FormProvider methods={form} onSubmit={form.handleSubmit(handleSubmit)}>
      <Box sx={{ p: 1, m: 1 }}>
        <Grid container spacing={2}>
          <Grid item xs={3} lg={2}>
            <Typography>年月</Typography>
            <RHFSelect
              options={yyyymmOptions}
              name="summary_yyyymm"
              size="small"
            />
          </Grid>
          {!!selectedYYYYMM && (
            <Grid item xs={3} lg={2}>
              <Typography>CSV</Typography>
              <Button variant="contained" color="info" href={downloadCsvUrl}>
                ダウンロード
              </Button>
            </Grid>
          )}
        </Grid>
      </Box>
    </FormProvider>
  );
}

function TableBox({ table }: CommonProps) {
  const TABLE_HEAD = [
    { id: "customer_name", label: "運営会社名", align: "left" },
    { id: "parking_name", label: "駐車場名", align: "left" },
    { id: "receipt_order_count", label: "領収証発行件数", align: "left" },
    { id: "mail_order_count", label: "郵送依頼件数", align: "left" },
    { id: "sms_send_count", label: "SMS送信件数", align: "left" },
  ];
  const {
    order,
    page,
    sort,
    rowsPerPage,
    fetched,
    fillteredRow,
    isNotFound,
    dataLength,
    //
    onSort,
    onChangePage,
    onChangeRowsPerPage,
    //
    setRowData,
    //
    ROWS_PER_PAGES,
  } = table;

  return (
    <>
      <TableContainer
        sx={{
          //  minWidth: 800,
          position: "relative",
        }}
      >
        <Table size="small">
          <TableHeadCustom
            order={order}
            orderBy={sort}
            headLabel={TABLE_HEAD}
            rowCount={1}
            numSelected={0}
            onSort={onSort}
          />

          <TableBody>
            {fillteredRow.map((row, index) => (
              <Row data={row} key={index} />
            ))}
          </TableBody>
        </Table>
      </TableContainer>

      <Box sx={{ position: "relative" }}>
        <TablePagination
          rowsPerPageOptions={ROWS_PER_PAGES}
          component="div"
          count={dataLength}
          rowsPerPage={rowsPerPage}
          page={page}
          onPageChange={onChangePage}
          onRowsPerPageChange={onChangeRowsPerPage}
        />
      </Box>
    </>
  );
}

type RowProps = {
  data: UseSummary;
};
function Row({ data }: RowProps) {
  return (
    <TableRow>
      <TableCell>{data.customer_name}</TableCell>
      <TableCell>{data.parking_name}</TableCell>
      <TableCell>{data.receipt_order_count}件</TableCell>
      <TableCell>{data.mail_order_count}件</TableCell>
      <TableCell>{data.sms_send_count}件</TableCell>
    </TableRow>
  );
}
