import {
  Accordion,
  AccordionDetails,
  AccordionSummary,
  Autocomplete,
  Button,
  Grid,
  TextField,
  Typography,
} from "@mui/material";
import { useNavigate } from "react-router-dom";
import { AdvancedTable } from "../../../../components/advanced-table/AdvancedTable";
import { SPACING } from "../../../../data/spacing";
import { ROUTE_PROVINCE__FINANCIAL_USER_FINACIAL_FILE } from "../../../../routes/routes";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import SearchIcon from "@mui/icons-material/Search";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { cityGetProvinces } from "../../../city/services/CityGetProvinces";
import { cityGetCity } from "../../../city/services/city-get-city";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { provinceFinancialGetUsersWaletinfo } from "../../services/province-financial-get-users-walet-info";
import FilterAltIcon from "@mui/icons-material/FilterAlt";
import { provinceFinancialSearchUserDocument } from "../../services/province-financial-search-user-document";
import { getFaUserRole } from "../../../../utils/getFaUserRole";

export const ProvinceFinancialDocumentRegistration = () => {
  const [expanded, setExpanded] = useState(true);
  const [isFitered, setIsFitered] = useState(false);
  const handleChange = () => {
    setExpanded(!expanded);
  };

  const dispatch = useDispatch();

  const [provinceData, setProvinceData] = useState();
  const [cityData, setCityData] = useState();
  const [provinceKey, setProvinceKey] = useState();
  const [citylabel, setcitylabel] = useState();
  const [isExistProvince, setIsExistProvince] = useState(true);

  const [dataTable, setDataTable] = useState([]);
  const users = useSelector(
    (state) => state.provinceFinancialSlice.userWaletInfo
  );

  const formik = useFormik({
    initialValues: {
      username: "",
      fullname: "",
      mobile: "",
      nationalcode: "",
    },
    validationSchema: Yup.object({
      fullname: Yup.string().typeError("لطفا فیلد را پر کنید!"),
      username: Yup.number().typeError("لطفا عدد وارد کنید!"),
      mobile: Yup.number()
        .test("len", "شماره تلفن باید با 0 شروع شود", (val, context) => {
          if (context.originalValue?.length > 0) {
            return (
              context.originalValue && context.originalValue.startsWith("0")
            );
          }
        })
        .test("len", "شماره تماس 11 رقم باید باشد", (val, context) => {
          if (context.originalValue?.length > 0) {
            if (context.originalValue) {
              return context.originalValue.length === 11;
            }
          }
        })
        .typeError("لطفا عدد وارد کنید!"),
      nationalcode: Yup.number(),
    }),
  });

  useEffect(() => {
    formik.validateForm();
    dispatch(LOADING_START());
    dispatch(provinceFinancialGetUsersWaletinfo()).then(() => {
      dispatch(cityGetProvinces())?.then((r) => {
        setProvinceData(r.payload.data);
        dispatch(LOADING_END());
      });
    });
  }, []);

  const handleSearch = () => {
    const values = Object.values(formik.values).filter(
      (item) => item.length > 0
    );
    let finalValue = "";

    for (let index = 0; index < values.length; index++) {
      finalValue = finalValue + values[index] + ",";
    }
    finalValue = finalValue.substring(0, finalValue.length - 1);

    if (citylabel) {
      if (finalValue) {
        finalValue = finalValue + "," + citylabel;
      } else {
        finalValue = citylabel;
      }
    }

    dispatch(LOADING_START());

    dispatch(provinceFinancialSearchUserDocument(finalValue)).then((r) => {
      dispatch(LOADING_END());
      const data = r.payload.data;
      const d = data?.map((item, i) => {
        const name = getFaUserRole(item.role);

        return [
          i + 1,
          item.fullname,
          name,
          item.mobile,
          item.nationalId,
          item.province,
          item.city,
          item.creditor.toLocaleString() + " ریال",
          item.debtor.toLocaleString() + " ریال",
          item.penalty.toLocaleString() + " ریال",
          Math.abs(item.depositable).toLocaleString(),
          <Button
            onClick={() => {
              navigate(
                ROUTE_PROVINCE__FINANCIAL_USER_FINACIAL_FILE +
                  item.walletKey +
                  "/" +
                  item.id
              );
            }}
            key={i}
          >
            مشاهده
          </Button>,
        ];
      });

      setDataTable(d);
    });
  };

  useEffect(() => {
    const d = users?.map((item, i) => {
      const name = getFaUserRole(item.role);

      return [
        i + 1,
        item.fullname,
        name,
        item.mobile,
        item.nationalId,
        item.province,
        item.city,
        item.creditor.toLocaleString() + " ریال",
        item.debtor.toLocaleString() + " ریال",
        item.penalty.toLocaleString() + " ریال",
        Math.abs(item.depositable).toLocaleString(),
        <Button
          onClick={() => {
            navigate(
              ROUTE_PROVINCE__FINANCIAL_USER_FINACIAL_FILE +
                item.walletKey +
                "/" +
                item.id
            );
          }}
          key={i}
        >
          مشاهده
        </Button>,
      ];
    });

    setDataTable(d);
  }, [users]);

  const handleShowTransactions = () => {
    setIsFitered(!isFitered);
  };

  useEffect(() => {
    if (isFitered) {
      const filteredData = users.filter(
        (item) => item.creditor > 1 || item.debtor > 1 || item.penalty > 1
      );

      const d = filteredData?.map((item, i) => {
        const name = getFaUserRole(item.role);
        return [
          i + 1,
          item.fullname,
          name,
          item.mobile,
          item.nationalId,
          item.province,
          item.city,
          item.creditor.toLocaleString() + " ریال",
          item.debtor.toLocaleString() + " ریال",
          item.penalty.toLocaleString() + " ریال",
          Math.abs(item.depositable).toLocaleString() + " ریال",
          <Button
            onClick={() => {
              navigate(
                ROUTE_PROVINCE__FINANCIAL_USER_FINACIAL_FILE +
                  item.walletKey +
                  "/" +
                  item.id
              );
            }}
            key={i}
          >
            مشاهده
          </Button>,
        ];
      });
      setDataTable(d);
    } else {
      const d = users?.map((item, i) => {
        const name = getFaUserRole(item.role);

        return [
          i + 1,
          item.fullname,
          name,
          item.mobile,
          item.nationalId,
          item.province,
          item.city,
          item.creditor.toLocaleString() + " ریال",
          item.debtor.toLocaleString() + " ریال",
          item.penalty.toLocaleString() + " ریال",
          Math.abs(item.depositable).toLocaleString() + " ریال",

          <Button
            onClick={() => {
              navigate(
                ROUTE_PROVINCE__FINANCIAL_USER_FINACIAL_FILE +
                  item.walletKey +
                  "/" +
                  item.id
              );
            }}
            key={i}
          >
            مشاهده
          </Button>,
        ];
      });

      setDataTable(d);
    }
  }, [isFitered]);

  const handleValidForm = () => {
    if (formik.isValid) {
      if (
        Object.values(formik.values).filter((item) => item.length > 0)
          .length === 0 &&
        !citylabel
      ) {
        return true;
      } else {
        return false;
      }
    } else {
      return true;
    }
  };

  useEffect(() => {
    if (provinceKey) {
      dispatch(LOADING_START());
      dispatch(cityGetCity(provinceKey)).then((r) => {
        setCityData(r.payload.data);
        setIsExistProvince(false);
        dispatch(LOADING_END());
      });
    }
  }, [provinceKey]);

  const navigate = useNavigate();
  return (
    <>
      <Grid container justifyContent="space-between" gap={SPACING.SMALL}>
        <Grid justifyContent="start" xs={12} mt={SPACING.MEDIUM}>
          <Accordion expanded={expanded} onChange={handleChange}>
            <AccordionSummary
              expandIcon={<ExpandMoreIcon />}
              aria-controls="panel1a-content"
              id="panel1a-header"
            >
              <Typography>جستجو</Typography>
            </AccordionSummary>
            <AccordionDetails>
              <Grid container xs={12} gap={SPACING.SMALL}>
                <Grid>
                  <TextField
                    size="small"
                    id="username"
                    label="کد کاربری"
                    value={formik.values.username}
                    error={
                      formik.touched.username
                        ? Boolean(formik.errors.username)
                        : null
                    }
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    helperText={
                      formik.touched.username && Boolean(formik.errors.username)
                        ? formik.errors.username
                        : null
                    }
                    autoComplete="current-password"
                    variant="outlined"
                  />
                </Grid>

                <Grid>
                  <TextField
                    size="small"
                    id="fullname"
                    label="نام و نام خانوادگی"
                    value={formik.values.fullname}
                    error={
                      formik.touched.fullname
                        ? Boolean(formik.errors.fullname)
                        : null
                    }
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    helperText={
                      formik.touched.fullname && Boolean(formik.errors.fullname)
                        ? formik.errors.fullname
                        : null
                    }
                    autoComplete="current-password"
                    variant="outlined"
                  />
                </Grid>
                <Grid>
                  <TextField
                    size="small"
                    id="mobile"
                    label="تلفن"
                    value={formik.values.mobile}
                    error={
                      formik.touched.mobile
                        ? Boolean(formik.errors.mobile)
                        : null
                    }
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    helperText={
                      formik.touched.mobile && Boolean(formik.errors.mobile)
                        ? formik.errors.mobile
                        : null
                    }
                    autoComplete="current-password"
                    variant="outlined"
                  />
                </Grid>
                <Grid>
                  <TextField
                    size="small"
                    id="nationalcode"
                    label="کد ملی"
                    value={formik.values.nationalcode}
                    error={
                      formik.touched.nationalcode
                        ? Boolean(formik.errors.nationalcode)
                        : null
                    }
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    helperText={
                      formik.touched.nationalcode &&
                      Boolean(formik.errors.nationalcode)
                        ? formik.errors.nationalcode
                        : null
                    }
                    autoComplete="current-password"
                    variant="outlined"
                  />
                </Grid>
                <Grid>
                  <Autocomplete
                    sx={{ minWidth: "150px" }}
                    size="small"
                    disablePortal
                    id="province"
                    options={
                      provinceData
                        ? provinceData?.map((i) => ({
                            id: i.key,
                            label: i.name,
                          }))
                        : []
                    }
                    onChange={(e, value) => {
                      setProvinceKey(value.id);
                    }}
                    renderInput={(params) => (
                      <TextField {...params} label="استان" />
                    )}
                  />
                </Grid>
                <Grid>
                  <Autocomplete
                    sx={{ minWidth: "180px" }}
                    size="small"
                    disabled={isExistProvince}
                    disablePortal
                    id="city"
                    options={
                      cityData
                        ? cityData.map((i) => ({ id: i.key, label: i.name }))
                        : []
                    }
                    onChange={(e, value) => {
                      setcitylabel(value.label);
                    }}
                    renderInput={(params) => (
                      <TextField {...params} label="شهر" />
                    )}
                  />
                </Grid>

                <Button
                  disabled={handleValidForm(formik)}
                  onClick={handleSearch}
                  variant="contained"
                  endIcon={<SearchIcon />}
                >
                  جستجو
                </Button>

                <Button
                  onClick={handleShowTransactions}
                  variant="contained"
                  endIcon={<FilterAltIcon />}
                  sx={{
                    backgroundColor: "#e3e3e3",
                    color: "#000",
                    "&:hover": {
                      backgroundColor: "#d0d0d0",
                    },
                  }}
                >
                  {isFitered ? <>حذف فیلتر</> : <> فقط کاربران دارای تراکنش</>}
                </Button>
              </Grid>
            </AccordionDetails>
          </Accordion>
          <Grid mt={SPACING.SMAll}>
            <AdvancedTable
              columns={[
                "ردیف",
                "نام و نام خانوادگی",
                "نقش",
                "تلفن",
                "کد ملی",
                "استان",
                "شهر",
                "بستانکار",
                "بدهکار",
                "جریمه",
                "قابل واریز",
                "مشاهده",
              ]}
              data={dataTable}
            />
          </Grid>
        </Grid>
      </Grid>
    </>
  );
};
