import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { Grid } from "../components/grid/Grid";
import {
  Accordion,
  AccordionDetails,
  AccordionSummary,
  Button,
  Divider,
  InputAdornment,
  TextField,
  Typography,
} from "@mui/material";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";

import logo from "../assets/images/logo.png";
import { useFormik } from "formik";
import { Yup } from "../lib/yup/yup";
import Num2persian from "num2persian";
import { useDispatch } from "react-redux";
import { wagePaymentGetUserInfo } from "../features/authentication/services/wage-payment-get-user-info";
import { OPEN_MODAL } from "../lib/redux/slices/appSlice";
import { SlaughterPayFeesGateway } from "../features/slaughter-house/components/slaughter-pay-fees-gateway/SlaughterPayFeesGateway";
import { SimpleTable } from "../components/simple-table/SimpleTable";

const WagePayment = () => {
  const { key, province } = useParams();

  const [userInfo, setUserInfo] = useState();

  const dispatch = useDispatch();

  const formik = useFormik({
    initialValues: {
      offer: 0,
    },
    validationSchema: Yup.object({
      offer: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!")
        .min(200000, "حداقل بیست هزار تومان وارد کنید"),
      // .max(
      //   2000000000,
      //   "در هر بار پرداخت، حداکثر مبلغ 200 میلیون تومان میتوانید پرداخت کنید!"
      // ),
    }),
  });

  useEffect(() => {
    if (key) {
      dispatch(
        wagePaymentGetUserInfo({ province, key: `user_gate_way_id=${key}` })
      ).then((r) => {
        setUserInfo(r.payload.data);
        if (r.payload?.data?.totalAmount > 2000000000) {
          formik.setFieldValue("offer", 2000000000);
        } else {
          formik.setFieldValue(
            "offer",
            parseInt(Math.ceil(r.payload.data.totalAmount / 10000) * 10000)
          );
        }
      });
    }
  }, []);

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

  const [tableData, setTableData] = useState([]);

  useEffect(() => {
    if (userInfo?.role === "Poultry" || userInfo?.role === "buyer") {
      const d = userInfo?.orderCode?.map((item, i) => {
        return [i + 1, item];
      });

      setTableData(d);
    }
  }, [userInfo]);

  return (
    <Grid container justifyContent="center" alignItems="center" mt={2}>
      <Grid
        xs={12}
        sm={8}
        md={4}
        style={{
          borderStyle: "solid",
          borderWidth: "1px",
          borderRadius: "30px",
          borderColor: "gray",
          boxShadow: "0px 5px 10px rgba(0, 0, 0, 0.1)",
          padding: "20px",
        }}
      >
        <Grid xs={12}>
          <img
            alt="logo"
            src={logo}
            style={{ width: "100px", height: "100px", userSelect: "none" }}
          />
        </Grid>
        <Typography variant="body1" color="primary" mb={1}>
          سامانه رصدیار
        </Typography>
        <Typography variant="body1" color="secondary" mb={2}>
          پنل پرداخت تعرفه
        </Typography>

        <Divider />

        <Grid container justifyContent="space-between" mt={2} mb={2}>
          <Typography variant="body1" color="primary">
            نام و نام خانوادگی:
          </Typography>

          <Grid>
            <Typography variant="body1" color="gray">
              {userInfo?.fullname}
              {/* {userInfo?.role === "Poultry"
                ? `${userInfo?.fullname}`
                : userInfo?.role === "Buyer"
                ? `${userInfo?.fullname}`
                : `${userInfo?.fullname} (${userInfo?.name})`} */}
            </Typography>
            <Divider />
            <Typography variant="body1" color="gray">
              {userInfo?.mobile}
            </Typography>
          </Grid>
        </Grid>

        <Divider />
        {userInfo?.role === "Poultry" && (
          <>
            {userInfo?.orderCode && (
              <Grid container justifyContent="space-between" mt={2} mb={2}>
                <Typography variant="body1" color="secondary">
                  کد سفارش:
                </Typography>

                <Typography variant="body1" color="gray">
                  {userInfo?.orderCode?.toLocaleString()}
                </Typography>
              </Grid>
            )}
            <Grid container justifyContent="space-between" mt={2} mb={2}>
              <Typography variant="body1" color="secondary">
                تعداد سفارشات:
              </Typography>

              <Typography variant="body1" color="gray">
                {userInfo?.numberOfRequests?.toLocaleString()}
              </Typography>
            </Grid>
            <Grid container justifyContent="space-between" mt={2} mb={2}>
              <Typography variant="body1" color="secondary">
                حجم سفارشات:
              </Typography>

              <Typography variant="body1" color="gray">
                {userInfo?.totalQuantity?.toLocaleString()} قطعه
              </Typography>
            </Grid>

            <Grid container justifyContent="space-between" mt={2} mb={2}>
              <Typography variant="body1" color="secondary">
                وزن سفارشات:
              </Typography>

              <Typography variant="body1" color="gray">
                {userInfo?.totalWeight?.toLocaleString()} کیلوگرم
              </Typography>
            </Grid>
          </>
        )}

        {(userInfo?.role === "Poultry" || userInfo?.role === "buyer") && (
          <Accordion
            my={2}
            sx={{
              borderRadius: "8px",
              boxShadow: "0px 4px 20px rgba(0, 0, 0, 0.1)",
              backgroundColor: "#f5f5f5",
              "&:before": { display: "none" },
            }}
          >
            <AccordionSummary
              expandIcon={<ExpandMoreIcon sx={{ color: "#1976d2" }} />}
              aria-controls="panel1a-content"
              sx={{
                backgroundColor: "#fff",
              }}
            >
              <Typography sx={{ color: "#1976d2", fontWeight: "bold" }}>
                مشاهده سفارشات
              </Typography>
            </AccordionSummary>
            <AccordionDetails
              sx={{
                backgroundColor: "#f9f9f9",
                borderTop: "1px solid #e0e0e0",
                padding: "8px",
                transition: "all 0.3s ease-in-out",
              }}
            >
              <Grid>
                <SimpleTable columns={["ردیف", "کد سفارش"]} data={tableData} />
              </Grid>
            </AccordionDetails>
          </Accordion>
        )}

        <Grid
          container
          justifyContent="space-between"
          mt={2}
          mb={2}
          style={{ fontWeight: "bolder" }}
        >
          <Typography variant="body1" color="primary">
            جمع بدهی:
          </Typography>

          <Typography
            variant="body1"
            style={{ color: "red", fontWeight: "bolder" }}
          >
            {parseInt(
              Math.ceil(userInfo?.totalAmount / 10000) * 10000
            ).toLocaleString()}{" "}
            ریال
          </Typography>
        </Grid>

        <Divider />

        <Grid container justifyContent="space-between" mt={2} mb={2}>
          <Typography variant="body1" color="primary">
            مبلغ تراکنش:
          </Typography>

          <Typography variant="body1" color="gray">
            {parseInt(
              Math.ceil(formik.values.offer / 10000) * 10000
            ).toLocaleString()}{" "}
            ریال
          </Typography>
        </Grid>

        <Divider />

        <Grid container justifyContent="center" mt={2} mb={2} gap={2}>
          <TextField
            id="offer"
            label={
              userInfo?.role === "Poultry" || userInfo?.role === "Buyer"
                ? "مبلغ"
                : "ویرایش مبلغ"
            }
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">ریال</InputAdornment>
              ),
              readOnly:
                userInfo?.role === "Poultry" || userInfo?.role === "Buyer",
            }}
            variant="outlined"
            sx={{ width: "100%" }}
            value={formik.values.offer}
            error={formik.touched.offer ? Boolean(formik.errors.offer) : null}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            helperText={
              formik.touched.offer && Boolean(formik.errors.offer)
                ? formik.errors.offer
                : null
            }
          />

          <Typography variant="body1" mb={2} sx={{ color: "darkcyan" }}>
            معادل {Num2persian(formik.values.offer / 10)} تومان
          </Typography>
          {/* <Grid xs={12}>
            <Typography style={{ fontSize: "12px" }} color="error" mb={1}>
              توجه: در هر تراکنش حداکثر مبلغ 200 میلیون تومان میتوانید پرداخت
              کنید!
            </Typography>
          </Grid> */}
          <Button
            variant="contained"
            fullWidth
            disabled={!formik.isValid}
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: "پرداخت تعرفه از طریق درگاه پرداخت",
                  content: (
                    <SlaughterPayFeesGateway
                      backend={province}
                      isPayment
                      isPaymentData={{
                        order_codes: userInfo?.orderCode
                          ? userInfo?.orderCode
                          : null,
                        role: userInfo?.role,
                        user_key: userInfo?.userKey ? userInfo?.userKey : null,
                        total_amount: formik.values.offer,
                      }}
                    />
                  ),
                })
              );
            }}
          >
            پرداخت تعرفه - درگاه پرداخت
          </Button>
        </Grid>
      </Grid>
    </Grid>
  );
};

export default WagePayment;
