import React, { useContext, useEffect, useState } from "react";
import {
  Box,
  Button,
  Typography,
  TextField,
  InputAdornment,
  Pagination,
  Tooltip,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
} from "@mui/material";
import { AiOutlineArrowUp } from "react-icons/ai";
import { Grid } from "../components/grid/Grid";
import { motion } from "framer-motion";
import { useFormik } from "formik";
import { Yup } from "../lib/yup/yup";
import { useDispatch, useSelector } from "react-redux";
import { slaughterGetWalletBalance } from "../features/slaughter-house/services/get-wallet-balance";
import { BackButton } from "../components/back-button/BackButton";
import { OPEN_MODAL } from "../lib/redux/slices/appSlice";
import { SlaughterPayFeesGateway } from "../features/slaughter-house/components/slaughter-pay-fees-gateway/SlaughterPayFeesGateway";
import { slaughterGetProfile } from "../features/slaughter-house/services/slaughter-get-profile";
import Num2persian from "num2persian";
import { AppContext } from "../contexts/AppContext";
import moment from "moment";
import axios from "axios";
import { SimpleTable } from "../components/simple-table/SimpleTable";
import { getRoleFromUrl } from "../utils/getRoleFromUrl";
import { DatePicker } from "@mui/x-date-pickers";
import { SPACING } from "../data/spacing";
import { format } from "date-fns-jalali";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";

const Wallet = () => {
  const [showInput, setShowInput] = useState(false);
  const [balance, setBalance] = useState(0);
  const [dataTableM, setDataTableM] = useState([]);
  const dispatch = useDispatch();
  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [textValue, setTextValue] = useState("");
  const [type, setType] = useState("completed");

  const handleChange = (event) => {
    setType(event.target.value);
  };

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };
  const userInfo = useSelector((state) => state.userSlice);

  const handleDepositClick = () => {
    setShowInput(true);
  };

  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);

  const fetchApiData = async (page, textValue) => {
    const response = await axios.get(
      `transactions/?search=filter&value=${textValue}&page=${page}&type=wallet&page_size=${10}&date1=${selectedDate1}&date2=${selectedDate2}&state=${type}&role=${getRoleFromUrl()}`
    );
    setData(response.data.results);
    setTotalRows(response.data.count);
  };

  useEffect(() => {
    fetchApiData(1);
  }, [selectedDate1, selectedDate2, type]);

  const handleSubmit = async (event) => {
    event.preventDefault();
    try {
      const response = await axios.get(
        `transactions/?search=filter&value=${textValue}&type=wallet&date1=${selectedDate1}&date2=${selectedDate2}&state=${type}&role=${getRoleFromUrl()}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  const [page, setPage] = useState(0);
  const handleChangePageM = (event, newPage) => {
    setPage(newPage);
    fetchApiData(newPage + 1, textValue);
  };

  useEffect(() => {
    dispatch(slaughterGetWalletBalance()).then((r) => {
      setBalance(r.payload.data?.balance);
    });
    dispatch(slaughterGetProfile());
  }, []);

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        i + 1,
        format(new Date(item.createDate), "yyyy/MM/dd hh:mm:ss"),
        item.payer,
        item.orderId,
        item.saleReferenceId,
        item.orderId,
        item.cardHolderPan,
        item?.amount?.toLocaleString() + " ﷼",
        item.message?.split("_")?.join(" "),
      ];
    });

    setDataTableM(d);
  }, [data]);

  const { inventorySelectedKillHouse } = useSelector(
    (state) => state.slaughterSlice
  );

  const formik = useFormik({
    initialValues: {
      amount: "",
    },
    validationSchema: Yup.object({
      amount: Yup.number()
        .required("این فیلد اجباری است!")
        .min(1000000, "حداقل مبلغ صد هزار تومان است!")
        .max(
          1818180000,
          "جمع مبلغ کل و مالیات نباید از دویست میلیون تومان بیشتر شود!"
        )
        .typeError("لطفا مبلغ را به درستی وارد کنید!"),
    }),
  });

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

  const getValueWIthTax = (value) => {
    return Number(value / 10) + Number(value);
  };

  return (
    <Grid xs={12} container justifyContent="center">
      <Grid xs={12} sm={12} md={10} lg={10} justifyContent="center">
        <Grid>
          <BackButton />
        </Grid>
        <Grid justifyContent="center" xs={12}>
          <motion.div
            initial={{ opacity: 0, y: -20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5, delay: 0.2 }}
          >
            <Box
              p={3}
              borderRadius={12}
              boxShadow={3}
              bgcolor="background.paper"
              textAlign="center"
              style={{ backgroundColor: "aliceblue" }}
            >
              <Typography variant="h4" mb={2} color="primary">
                کیف پول
              </Typography>
              <Typography variant="body1" mb={4} sx={{ color: "darkcyan" }}>
                موجودی کیف پول: {balance?.toLocaleString()} ریال
              </Typography>
              {!showInput ? (
                <Button
                  variant="contained"
                  color="primary"
                  startIcon={<AiOutlineArrowUp />}
                  sx={{
                    borderRadius: 20,
                    textTransform: "none",
                    fontSize: 16,
                  }}
                  onClick={handleDepositClick}
                >
                  افزایش موجودی
                </Button>
              ) : (
                <motion.div
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.5 }}
                >
                  <TextField
                    sx={{ mb: 2 }}
                    fullWidth
                    id="amount"
                    label="مبلغ را وارد کنید"
                    value={formik.values.amount}
                    error={
                      formik.touched.amount
                        ? Boolean(formik.errors.amount)
                        : null
                    }
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    InputProps={{
                      endAdornment: (
                        <InputAdornment position="end">ریال</InputAdornment>
                      ),
                    }}
                    helperText={
                      formik.touched.amount && Boolean(formik.errors.amount)
                        ? formik.errors.amount
                        : null
                    }
                    autoComplete="current-password"
                    variant="outlined"
                  />
                  <Grid container xs={12}>
                    <Grid item xs={12}>
                      {formik.values.amount > 0 && (
                        <Typography
                          variant="body1"
                          mb={2}
                          sx={{ color: "darkcyan" }}
                        >
                          {Num2persian(formik.values.amount)} ریال
                        </Typography>
                      )}
                    </Grid>
                    <Grid item xs={12}>
                      {formik.values.amount > 0 && (
                        <Typography
                          variant="body1"
                          mb={2}
                          sx={{ color: "red" }}
                        >
                          با احتساب ده درصد ارزش افزوده:{" "}
                          {getValueWIthTax(
                            formik.values.amount
                          ).toLocaleString()}{" "}
                          ریال
                        </Typography>
                      )}
                    </Grid>
                  </Grid>
                  <Button
                    type="submit"
                    variant="contained"
                    color="secondary"
                    sx={{
                      borderRadius: 20,
                      textTransform: "none",
                      fontSize: 16,
                      color: "white",
                      marginRight: 2,
                    }}
                    onClick={() => {
                      setShowInput(!showInput);
                    }}
                  >
                    انصراف
                  </Button>
                  <Button
                    disabled={!formik.isValid || !inventorySelectedKillHouse}
                    onClick={() => {
                      dispatch(
                        OPEN_MODAL({
                          title: "واریز به کیف پول از طریق درگاه پرداخت",
                          content: (
                            <SlaughterPayFeesGateway
                              amount={formik.values.amount}
                              amountWithTax={getValueWIthTax(
                                formik.values.amount
                              )}
                              user_key={inventorySelectedKillHouse}
                            />
                          ),
                        })
                      );
                    }}
                    type="submit"
                    variant="contained"
                    color="primary"
                    sx={{
                      borderRadius: 20,
                      textTransform: "none",
                      fontSize: 16,
                    }}
                  >
                    پرداخت
                  </Button>
                </motion.div>
              )}
            </Box>
          </motion.div>
        </Grid>
        <Grid container justifyContent="center" xs={12} mt={2}>
          <Grid
            container
            alignItems="center"
            justifyContent="space-between"
            gap={2}
            paddingTop={2}
            mb={1}
            width="100%"
          >
            <Grid container alignItems="center" gap={SPACING.SMALL}>
              <Typography>تراکنش ها</Typography>
              <Grid container gap={SPACING.SMALL}>
                <Grid>
                  <FormControl>
                    <InputLabel id="demo-simple-select-label">
                      نوع تراکنش
                    </InputLabel>
                    <Select
                      labelId="demo-simple-select-label"
                      id="demo-simple-select"
                      value={type}
                      label="Age"
                      onChange={handleChange}
                    >
                      <MenuItem value={"completed"}>موفق</MenuItem>
                      <MenuItem value={"failed"}>ناموفق</MenuItem>
                    </Select>
                  </FormControl>
                </Grid>
                <Grid>
                  <DatePicker
                    label="از تاریخ"
                    id="date"
                    renderInput={(params) => (
                      <TextField style={{ width: "160px" }} {...params} />
                    )}
                    value={selectedDate1}
                    onChange={(e) => {
                      setSelectedDate1(moment(e).format("YYYY-MM-DD"));
                    }}
                  />
                </Grid>
                <Grid>
                  <DatePicker
                    label="تا تاریخ"
                    id="date"
                    renderInput={(params) => (
                      <TextField style={{ width: "160px" }} {...params} />
                    )}
                    value={selectedDate2}
                    onChange={(e) => {
                      setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                    }}
                  />
                </Grid>
              </Grid>
              <form onSubmit={handleSubmit}>
                <TextField
                  id="outlined-basic"
                  size="small"
                  autoComplete="off"
                  label="جستجو"
                  variant="outlined"
                  style={{ width: 250 }}
                  onChange={handleTextChange}
                />
                <Button
                  // disabled={!textValue}
                  type="submit"
                  onClick={handleSubmit}
                  endIcon={<RiSearchLine />}
                >
                  جستجو
                </Button>
              </form>
              <Tooltip title="خروجی اکسل">
                <a
                  href={`${axios.defaults.baseURL}wallete_excel/?date1=${selectedDate1}&date2=${selectedDate2}&key=${userInfo?.userProfile?.key}`}
                  rel="noreferrer"
                >
                  <Button color="success">
                    <RiFileExcel2Fill size={32} />
                  </Button>
                </a>
              </Tooltip>
            </Grid>
          </Grid>
          <Grid xs={12} container justifyContent="center">
            <SimpleTable
              columns={[
                "ردیف",
                "تاریخ و زمان",
                "پرداخت کننده",
                "شماره درخواست",
                "شماره پیگیری",
                "کدسفارش",
                "شماره کارت",
                "مبلغ",
                "متن خطا",
              ]}
              data={dataTableM}
            />
            <Grid container justifyContent="center" mt={2}>
              <Pagination
                count={Math.ceil(totalRows / 10)}
                page={page + 1}
                variant="outlined"
                onChange={(event, newPage) => {
                  handleChangePageM(event, newPage - 1);
                }}
              />
            </Grid>
          </Grid>
        </Grid>
      </Grid>
    </Grid>
  );
};

export default Wallet;
