import {
  TimelineConnector,
  TimelineContent,
  TimelineDot,
  TimelineItem,
  TimelineOppositeContent,
  TimelineSeparator,
} from "@mui/lab";
import {
  Button,
  ButtonGroup,
  TextField,
  ToggleButton,
  ToggleButtonGroup,
  Typography,
} from "@mui/material";
import React, { useEffect, useState } from "react";
import { PropTypes } from "prop-types";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { AnimatePresence, motion } from "framer-motion";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { useDispatch, useSelector } from "react-redux";
import { financialCheckRequest } from "../../services/financial-check-request";
import { useContext } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { avicultureGetChickenPrice } from "../../../aviculture/services/aviculture-get-chicken-price";
import { provinceFinancialGetPendingRequestsService } from "../../../province-finacial/services/province-financial-get-pending-requests";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import { formatJustDate } from "../../../../utils/formatTime";

export const FinancialCheckRequestOperation = ({ item }) => {
  const [openNotif, , selectedDate1, , selectedDate2] = useContext(AppContext);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(avicultureGetChickenPrice());
    formik.validateForm();
    formik2.validateForm();
  }, []);

  const { avicultureChickenPrice } = useSelector(
    (state) => state.avicultureSlice
  );

  const liveChickenPrice = avicultureChickenPrice?.liveChickenPrice;
  // calc suggest price
  // const chickenWeight = parseFloat(
  //   file.poultry.poultryIndexWeight.split(" ")[0]
  // );

  const chickenWeight = parseFloat(
    (item.barInfo.killHouseNetWeight / item.barInfo.realQuantity).toFixed(2)
  );
  // let suggestPrice = liveChickenPrice;
  //buildchange
  // hamedan & arak & bushehr
  const standardChicken = 2.5;
  // kermanshah
  // const standardChicken = 2.7;
  // const checkStep = 0.05;
  // const costPerStep = 500;

  if (chickenWeight < standardChicken) {
    // const howMuchToReduce =
    //   ((standardChicken - chickenWeight).toFixed(2) / checkStep) * costPerStep;
    // suggestPrice = liveChickenPrice - howMuchToReduce;
  }

  const formik = useFormik({
    initialValues: {
      rejectText: "",
      // wage: "1000",
    },
    validationSchema: Yup.object({
      rejectText: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا دلیل خود را بیان کنید."),
    }),
  });

  const [activeButtonIndex, setActiveButtonIndex] = useState(false);

  const handleButtonClick = (index) => {
    setActiveButtonIndex(index);
    if (!activeButtonIndex) {
      formik2.setFieldValue("reason", "");
      formik2.setFieldValue("amount", "");
    }
  };

  const formik2 = useFormik({
    initialValues: {
      fee: "",
      paymentType: "together",
      wage: 0,
      amount: "",
      reason: "",
    },
    validationSchema: Yup.object({
      fee: Yup.number().required("این فیلد اجباری است!"),
      amount: Yup.number(),
      paymentType: Yup.string().required("این فیلد اجباری است!"),
      reason: activeButtonIndex
        ? Yup.string().required("این فیلد اجباری است!")
        : Yup.string(),
      wage: Yup.number().required("این فیلد اجباری است!"),
    }),
  });

  let totalFactorPrice =
    (formik2.values.fee + formik2.values.wage) * item.killHouseNetWeight;
  if (activeButtonIndex === "plus") {
    totalFactorPrice += Number(formik2.values.amount);
  } else if (activeButtonIndex === "decrease") {
    totalFactorPrice -= Number(formik2.values.amount);
  }

  let finalTotalFactorPrice =
    totalFactorPrice - item.killRequestPaymentRemainAmount;

  if (item.smsPayment) {
    finalTotalFactorPrice += 50000;
  }

  const [isDenyed, setisDenyed] = useState(false);
  const btnValidation = !formik2.isValid;

  const [paymentType, setPaymentType] = React.useState("union");

  const handleChange = (event, newAlignment) => {
    if (newAlignment) {
      setPaymentType(newAlignment);
    }
  };

  return (
    <TimelineItem sx={{ alignSelf: "flex-start", width: "100%" }}>
      <TimelineSeparator>
        <TimelineDot color="secondary" />
        <TimelineConnector />
      </TimelineSeparator>
      <Grid container direction="column" flexWrap="nowrap" flex="1">
        <>
          <Grid container justifyContent="space-between">
            <Grid container>
              <Grid>
                <TimelineOppositeContent
                  variant="body1"
                  fontWeight="bold"
                  color="secondary"
                >
                  انجام عملیات
                </TimelineOppositeContent>
              </Grid>
              <Grid>
                <TimelineContent color="textSecondary">
                  <Typography variant="body2">
                    درخواست را بررسی و سپس تایید یا رد کنید.
                  </Typography>
                </TimelineContent>
              </Grid>
            </Grid>
            <Grid
              container
              gap={SPACING.SMALL}
              mb={SPACING.TINY}
              justifyContent="space-between"
            >
              <Grid
                container
                mt={SPACING.TINY}
                gap={SPACING.TINY}
                alignItems="center"
              >
                <Typography
                  color={(prop) => prop.palette.grey["A700"]}
                  variant={"caption"}
                >
                  موجودی کیف پول کشتارگاه:
                </Typography>
                <Typography variant={"button"} color="primary">
                  {`${item.killHouseWalletAmount?.toLocaleString()} ﷼`}
                </Typography>
              </Grid>
            </Grid>
          </Grid>
          <Grid container width="100%">
            <Grid
              container
              alignItems="start"
              direction="row-reverse"
              justifyContent="start"
            >
              <Grid
                container
                gap={SPACING.TINY}
                mt={SPACING.TINY}
                alignItems="center"
                ml={SPACING.LARGE}
              >
                <Typography variant={"caption"} color="error">
                  صدور فاکتور بنام:
                </Typography>
                <ToggleButtonGroup
                  color="primary"
                  value={paymentType}
                  orientation="vertical"
                  exclusive
                  onChange={handleChange}
                  aria-label="Platform"
                >
                  <ToggleButton value="union">اتحادیه</ToggleButton>
                  <ToggleButton value="poultry">مرغدار</ToggleButton>
                </ToggleButtonGroup>
                <Grid ml={SPACING.MEDIUM}>
                  {paymentType === "union" && (
                    <Grid container alignItems="center" gap={SPACING.SMALL}>
                      <Grid>
                        <Typography>اطلاعات حساب اتحادیه</Typography>
                      </Grid>
                      <Grid
                        style={{
                          border: "1px solid #ccc",
                          padding: "10px",
                          borderRadius: "4px",
                        }}
                      >
                        <Typography>
                          شماره کارت: {item?.provinceBank?.card}
                        </Typography>
                        <Typography>
                          شماره شبا: {item?.provinceBank?.shaba}
                        </Typography>
                        <Typography>
                          شماره حساب: {item?.provinceBank?.account}
                        </Typography>
                        <Typography>
                          بانک {item?.provinceBank?.bankName} - بنام{" "}
                          {item.provinceBank?.nameOfBankUser}
                        </Typography>
                      </Grid>
                    </Grid>
                  )}
                  {paymentType === "poultry" && (
                    <Grid container alignItems="center" gap={SPACING.SMALL}>
                      <Grid>
                        <Typography>اطلاعات حساب مرغدار</Typography>
                      </Grid>
                      <Grid
                        style={{
                          border: "1px solid #ccc",
                          padding: "10px",
                          borderRadius: "4px",
                        }}
                      >
                        <Typography>
                          شماره کارت:{" "}
                          {item?.poultryBank?.card
                            ? item?.poultryBank?.card
                            : "ندارد"}
                        </Typography>
                        <Typography>
                          شماره شبا:{" "}
                          {item?.poultryBank?.shaba
                            ? item?.poultryBank?.shaba
                            : "ندارد"}
                        </Typography>
                        <Typography>
                          شماره حساب:{" "}
                          {item?.poultryBank?.account
                            ? item?.poultryBank?.account
                            : "ندارد"}
                        </Typography>
                        <Typography>
                          بانک{" "}
                          {item?.poultryBank?.bankName
                            ? item?.poultryBank?.bankName
                            : "نامشخص"}{" "}
                          - بنام{" "}
                          {item.poultryBank?.nameOfBankUser
                            ? item.poultryBank?.nameOfBankUser
                            : "نامشخص"}
                        </Typography>
                      </Grid>
                    </Grid>
                  )}
                </Grid>
              </Grid>

              <Grid
                container
                direction="column"
                gap={SPACING.SMALL}
                mt={SPACING.TINY}
                alignItems="start"
              >
                <Grid container gap={SPACING.SMALL}>
                  <Grid>
                    <NumberInput
                      allowLeadingZeros
                      thousandSeparator=","
                      id="fee"
                      label="قیمت (﷼)"
                      variant="outlined"
                      error={
                        formik2.touched.fee ? Boolean(formik2.errors.fee) : null
                      }
                      onChange={formik2.handleChange}
                      onBlur={formik2.handleBlur}
                      helperText={
                        formik2.touched.fee && Boolean(formik2.errors.fee)
                          ? formik2.errors.fee
                          : null
                      }
                    />
                  </Grid>
                  <Grid>
                    <NumberInput
                      allowLeadingZeros
                      thousandSeparator=","
                      id="wage"
                      label="تعرفه  استان (﷼)"
                      variant="outlined"
                      value={formik2.values.wage}
                      error={
                        formik2.touched.wage
                          ? Boolean(formik2.errors.wage)
                          : null
                      }
                      onChange={formik2.handleChange}
                      onBlur={formik2.handleBlur}
                      helperText={
                        formik2.touched.wage && Boolean(formik2.errors.wage)
                          ? formik2.errors.wage
                          : null
                      }
                    />
                  </Grid>
                </Grid>
                <Grid>
                  <Grid container gap={SPACING.SMALL}>
                    <Grid
                      container
                      direction="column"
                      gap={SPACING.SMALL}
                      alignItems="start"
                    >
                      <Typography>اضافه یا کسر از فاکتور</Typography>
                      <ButtonGroup
                        color="primary"
                        aria-label="outlined primary button group"
                      >
                        <Button
                          onClick={() => handleButtonClick("plus")}
                          variant={
                            activeButtonIndex === "plus"
                              ? "contained"
                              : "outlined"
                          }
                          color="primary"
                        >
                          +
                        </Button>
                        <Button
                          onClick={() => handleButtonClick("decrease")}
                          variant={
                            activeButtonIndex === "decrease"
                              ? "contained"
                              : "outlined"
                          }
                          color="primary"
                        >
                          -
                        </Button>
                        <Button
                          onClick={() => handleButtonClick(false)}
                          color="error"
                        >
                          حذف
                        </Button>
                      </ButtonGroup>
                    </Grid>
                    <Grid>
                      {!!activeButtonIndex && (
                        <Grid container gap={SPACING.SMALL}>
                          <Grid>
                            <TextField
                              id="amount"
                              label="مبلغ اضافه/کسر از فاکتور"
                              variant="outlined"
                              error={
                                formik2.touched.amount
                                  ? Boolean(formik2.errors.amount)
                                  : null
                              }
                              onChange={formik2.handleChange}
                              onBlur={formik2.handleBlur}
                              helperText={
                                formik2.touched.amount &&
                                Boolean(formik2.errors.amount)
                                  ? formik2.errors.amount
                                  : null
                              }
                            />
                          </Grid>
                          <Grid>
                            <TextField
                              id="reason"
                              label="شرح موضوع"
                              variant="outlined"
                              error={
                                formik2.touched.reason
                                  ? Boolean(formik2.errors.reason)
                                  : null
                              }
                              multiline
                              rows={2} // Specify the number of rows to display at once
                              onChange={formik2.handleChange}
                              onBlur={formik2.handleBlur}
                              helperText={
                                formik2.touched.reason &&
                                Boolean(formik2.errors.reason)
                                  ? formik2.errors.reason
                                  : null
                              }
                            />
                          </Grid>
                        </Grid>
                      )}
                    </Grid>
                  </Grid>
                </Grid>
              </Grid>

              <Grid width="100%">
                <Grid container gap={SPACING.TINY} my={SPACING.TINY}>
                  <Grid container gap={SPACING.TINY} alignItems="center">
                    <Typography color="green" variant={"caption"}>
                      قیمت مرغ:
                    </Typography>
                    <Typography variant={"button"}>
                      {liveChickenPrice?.toLocaleString()} ﷼
                    </Typography>
                  </Grid>
                  <Grid container gap={SPACING.TINY} alignItems="center">
                    <Typography variant={"caption"} color="green">
                      آخرین تاریخ قیمت گذاری:
                    </Typography>
                    <Typography variant={"button"}>
                      {avicultureChickenPrice?.createDate &&
                        formatJustDate(avicultureChickenPrice?.createDate)}
                    </Typography>
                  </Grid>

                  {/* <Grid
                    container
                    mt={SPACING.TINY}
                    gap={SPACING.TINY}
                    alignItems="center"
                  >
                    <Typography
                      color={(prop) => prop.palette.grey["A700"]}
                      variant={"caption"}
                    >
                      قیمت پیشنهادی:
                    </Typography>
                    <Typography variant={"button"}>
                      {suggestPrice > 0
                        ? `${suggestPrice?.toLocaleString()} ﷼`
                        : "نامعتبر"}
                    </Typography>
                  </Grid> */}
                </Grid>
                <SimpleTable
                  columns={[
                    "قیمت کل",
                    "هزینه پیامک اطلاع رسانی",
                    "مبلغ خالص بار",
                    "مبلغ کل فاکتور",
                    "سهم مرغدار",
                    "سهم استان",
                    "مانده واریزی اولیه",
                    "مبلغ فاکتور نهایی",
                  ]}
                  data={[
                    [
                      (
                        formik2.values.fee + formik2.values.wage
                      )?.toLocaleString() + " ﷼",
                      item.smsPayment ? "دارد : 50,000 ﷼" : "ندارد",
                      (
                        (formik2.values.fee + formik2.values.wage) *
                        item.killHouseNetWeight
                      ).toLocaleString() + " ﷼",
                      totalFactorPrice?.toLocaleString() + " ﷼",
                      (
                        formik2.values.fee * item.killHouseNetWeight
                      )?.toLocaleString() + " ﷼",
                      (
                        formik2.values.wage * item.killHouseNetWeight
                      )?.toLocaleString() + " ﷼",
                      item.killRequestPaymentRemainAmount?.toLocaleString() +
                        " ﷼",
                      finalTotalFactorPrice < 0
                        ? 0
                        : finalTotalFactorPrice?.toLocaleString() + " ﷼",
                    ],
                  ]}
                />
              </Grid>
              {/* <Grid container mt={SPACING.SMALL} textAlign="start">
                <FormControl>
                  <Typography variant="body1" fontWeight="bold">
                    نحوه پرداخت
                  </Typography>
                  <RadioGroup
                    aria-labelledby="demo-controlled-radio-buttons-group"
                    name="controlled-radio-buttons-group"
                    value={formik2.values.paymentType}
                    onChange={(e) => {
                      formik2.setFieldValue("paymentType", e.target.value);
                    }}
                  >
                    <FormControlLabel
                      value="separate"
                      control={<Radio />}
                      label="پرداخت جداگانه به اتحادیه و مرغدار"
                    />
                    <FormControlLabel
                      value="together"
                      control={<Radio />}
                      label="پرداخت یکجا به حساب اتحادیه"
                    />
                  </RadioGroup>
                </FormControl>
              </Grid> */}
              <Grid xs={12}>
                <Grid container gap={SPACING.SMALL} padding={SPACING.SMALL}>
                  <AnimatePresence>
                    {isDenyed ? (
                      <motion.div
                        animate={{ x: -10, opacity: 1 }}
                        transition={{ duration: 0.3 }}
                        initial={{ opacity: 0 }}
                        exit={{ opacity: 0 }}
                      >
                        <Grid
                          flexDirection={"column"}
                          container
                          gap={SPACING.SMALL}
                        >
                          <Grid>
                            <TextField
                              multiline
                              rows={4}
                              fullWidth
                              id="rejectText"
                              label="پیام خود را وارد کنید"
                              variant="outlined"
                              value={formik.values.rejectText}
                              error={
                                formik.touched.rejectText
                                  ? Boolean(formik.errors.rejectText)
                                  : null
                              }
                              onChange={formik.handleChange}
                              onBlur={formik.handleBlur}
                              helperText={
                                formik.touched.rejectText &&
                                Boolean(formik.errors.rejectText)
                                  ? formik.errors.rejectText
                                  : null
                              }
                            />
                          </Grid>

                          <Grid container gap={SPACING.SMALL}>
                            <Grid>
                              <Button
                                variant="outlined"
                                color="secondary"
                                onClick={() => {
                                  setisDenyed(false);
                                }}
                              >
                                لغو
                              </Button>
                            </Grid>
                            <Grid>
                              <Button
                                variant="outlined"
                                onClick={() => {
                                  dispatch(LOADING_START());
                                  dispatch(
                                    financialCheckRequest({
                                      message: formik.values.rejectText,
                                      kill_house_info_key:
                                        item.barInfo.killHouseAssignmentKey,
                                      state: "rejected",
                                    })
                                  ).then((r) => {
                                    if (r.error) {
                                      openNotif({
                                        vertical: "top",
                                        horizontal: "center",
                                        msg: "مشکلی پیش آمده است!",
                                        severity: "error",
                                      });
                                    } else {
                                      dispatch(
                                        DRAWER({
                                          right: false,
                                          bottom: false,
                                          content: null,
                                        })
                                      );
                                      dispatch(
                                        provinceFinancialGetPendingRequestsService(
                                          {
                                            selectedDate1,
                                            selectedDate2,
                                          }
                                        )
                                      );
                                      // getFileFromApi(roles, id, dispatch);
                                      openNotif({
                                        vertical: "top",
                                        horizontal: "center",
                                        msg: "عملیات با موفقیت انجام شد.",
                                        severity: "success",
                                      });
                                    }
                                    dispatch(LOADING_END());
                                  });
                                }}
                              >
                                رد درخواست
                              </Button>
                            </Grid>
                          </Grid>
                        </Grid>
                      </motion.div>
                    ) : (
                      <Grid container gap={SPACING.SMALL}>
                        <Button
                          variant="outlined"
                          color="secondary"
                          onClick={() => {
                            setisDenyed(true);
                          }}
                        >
                          رد درخواست
                        </Button>
                        <Button
                          disabled={btnValidation}
                          variant="outlined"
                          onClick={() => {
                            if (totalFactorPrice < 0) {
                              // openNotif({
                              //   vertical: "top",
                              //   horizontal: "center",
                              //   msg: `آیتم کسر مبلغ ${formik2.values.reason} نمی تواند بیشتر از مبلغ کل فاکتور باشد.`,
                              //   severity: "error",
                              // });
                              formik2.setFieldError(
                                "amount",
                                "مبلغ کسر نمی تواند بزرگتر از مبلغ کل فاکتور باشد!"
                              );
                              return;
                            }
                            dispatch(LOADING_START());
                            dispatch(
                              financialCheckRequest({
                                kill_house_info_key:
                                  item.barInfo.killHouseAssignmentKey,
                                pay: formik2.values.paymentType,
                                fee: formik2.values.fee,
                                real_weight:
                                  item.barInfo.killHouseNetWeight /
                                  item.quantity,
                                province_input_wage: formik2.values.wage,
                                province_input_amount: formik2.values.amount
                                  ? formik2.values.amount
                                  : null,
                                province_input_amount_state: activeButtonIndex,
                                state: "accepted",
                                reason: formik2.values.reason,
                                bank: paymentType,
                              })
                            ).then((r) => {
                              if (r.payload.error) {
                                openNotif({
                                  vertical: "top",
                                  horizontal: "center",
                                  msg: r.payload.error,
                                  severity: "error",
                                });
                              } else {
                                dispatch(
                                  provinceFinancialGetPendingRequestsService({
                                    selectedDate1,
                                    selectedDate2,
                                  })
                                );
                                dispatch(
                                  DRAWER({
                                    right: false,
                                    bottom: false,
                                    top: false,
                                    content: null,
                                  })
                                );
                                // getFileFromApi(roles, id, dispatch);
                                openNotif({
                                  vertical: "top",
                                  horizontal: "center",
                                  msg: "عملیات با موفقیت انجام شد.",
                                  severity: "success",
                                });
                              }
                              dispatch(LOADING_END());
                            });
                          }}
                        >
                          صدور فاکتور
                        </Button>
                      </Grid>
                    )}
                  </AnimatePresence>
                </Grid>
              </Grid>
            </Grid>
          </Grid>
        </>
      </Grid>
    </TimelineItem>
  );
};

FinancialCheckRequestOperation.propTypes = {
  item: PropTypes.object,
  file: PropTypes.object,
};
