import React from "react";
import { Link } from "react-router-dom";
import {
  InputNumber,
  Select,
  Menu,
  Card,
  Radio,
  Space,
  Checkbox,
  Drawer,
  Row,
  Col,
} from "antd";
import { ClockCircleOutlined } from "@ant-design/icons";
import { fetchClassifieds } from "@lib/redux/actions/classifieds-actions";
import { fetchDistricts } from "@lib/redux/actions/districts-actions";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import SelectDistrict from "./select-district";
import isEmpty from "lodash/isEmpty";

const queryParams = new URLSearchParams(window.location.search);
// [loadSort, setLoadSort] = React.useState(true);

const sortParams = queryParams
  .get("sort")
  ?.split(",")
  .map((pm) => ({
    label: pm.split("=")[0],
    value: pm.split("=")[1],
  }));
const priceRangeDefault = (): { min: number; max: number } => {
  const aboveprice = sortParams?.find((sp) => sp.label == "aboveprice");
  const belowprice = sortParams?.find((sp) => sp.label == "belowprice");
  if (aboveprice && belowprice) {
    return { min: parseInt(aboveprice.value), max: parseInt(belowprice.value) };
  } else if (aboveprice) {
    return { min: parseInt(aboveprice.value), max: null };
  } else if (belowprice) {
    return { min: null, max: parseInt(belowprice.value) };
  }
  return { min: null, max: null };
};
const ageRangeDefault = (): { min: number; max: number } => {
  const aboveage = sortParams?.find((sp) => sp.label == "aboveage");
  const belowage = sortParams?.find((sp) => sp.label == "belowage");
  if (aboveage && belowage) {
    return { min: parseInt(aboveage.value), max: parseInt(belowage.value) };
  } else if (aboveage) {
    return { min: parseInt(aboveage.value), max: null };
  } else if (belowage) {
    return { min: null, max: parseInt(belowage.value) };
  }
  return { min: null, max: null };
};
const defaultCondition = () =>
  sortParams?.find((sp) => sp.label == "condition");
const defaultGender = () => sortParams?.find((sp) => sp.label == "gender");
const defaultCustom = (key) => sortParams?.find((sp) => sp.label == key);

interface SMI {
  status?;
  classifieds?;
  fetchClassifieds?;
  single_classified?;
  districts?;
  fetchDistricts?;
  match?;
  currentDistrict?;
}

const getSortParam = () =>
  new URLSearchParams(window.location.search)
    .get("sort")
    ?.split(",")
    .map((pm) => ({
      label: pm.split("=")[0],
      value: pm.split("=")[1],
    }));
const neol = () => {
    if (
      new URLSearchParams(window.location.search)
        .get("sort")
        ?.split(",")
        .map((pm) => ({
          label: pm.split("=")[0],
          value: pm.split("=")[1],
        }))
        ?.find((sp) => sp.label == "oldest")
    ) {
      return { label: "Oldest", key: "oldest" };
    }
    return {
      label: "Newest",
      key: "newest",
    };
  },
  SortBarComponent = ({
    status,
    classifieds,
    fetchClassifieds,
    single_classified = {},
    districts,
    fetchDistricts,
    match,
    currentDistrict,
  }: SMI) => {
    const [showAllSubclassifieds, setShowAllSubclassifieds] = React.useState(
        false
      ),
      [sortValue, setSortValue] = React.useState(queryParams.get("sort")),
      getSort = (param) => {
        let paramsArr = [];
        if (sortValue) {
          paramsArr = queryParams.get("sort")?.split(",");
          const result = paramsArr.find((p) => p.includes(param));
          return result?.includes("=")
            ? result?.substring(param.length + 1)?.replaceAll(" ", "+")
            : result?.substring(param.length + 3)?.replaceAll(" ", "+");
          // return paramsArr.find(p => p.includes(param))?.substring(param.length+3);
        } else {
          return undefined;
        }
      },
      doSort = (param, value?, nullable = true) => {
        // NOTE: ?sort=newest,oldest,belowprice%3D30,aboveprice%3D20,quantity%3D30,currency%3DUS$
        // NOTE: %3D = '='
        // NOTE: eg: 'belowprice%3D30' translates to 'belowprice=30'

        let paramsArr = [];
        if (queryParams.get("sort")) {
          paramsArr = queryParams.get("sort")?.split(",");
          if (param == "newest" || param == "oldest") {
            paramsArr = paramsArr.filter((pm) => pm !== "oldest");
            paramsArr = paramsArr.filter((pm) => pm !== "newest");
          }

          const alreadyContains = (): boolean => {
            let huh = false;
            paramsArr.map((pm) => {
              if (pm.includes(param + "%3D")) huh = true;
            });
            return huh;
          };
          const newParamValue = value ? param + "%3D" + value : param;
          const paramToChange = paramsArr?.find((pr) => pr.includes(param));

          paramsArr?.filter((pr: string) => {
            pr == paramToChange ? newParamValue : pr;
            return pr;
          });
          if (!alreadyContains()) {
            paramsArr = paramsArr.filter((pm) => !pm.includes(param + "%3D"));
            paramsArr = paramsArr.filter((pm) => !pm.includes(param + "="));
            paramsArr = paramsArr.filter((pm) => !pm.includes(param));
            paramsArr.push(newParamValue);
          } else {
            paramsArr = paramsArr.filter((pm) => !pm.includes(param + "%3D"));
            paramsArr = paramsArr.filter((pm) => !pm.includes(param + "="));
            paramsArr = paramsArr.filter((pm) => !pm.includes(param));
            if ((!value && nullable) || value) {
              paramsArr.push(newParamValue);
            }
          }
        } else {
          if ((!value && nullable) || value) {
            paramsArr.push(value ? param + "%3D" + value : param);
          }
        }

        setSortValue(paramsArr.join(","));

        queryParams.set("sort", paramsArr.join(","));

        return paramsArr[paramsArr.length - 1];

        // history.replaceState(null, null, '?' + queryParams.toString());

        // setLoadSort(!loadSort);
      },
      TimeSortMenu = () => {
        const handleChange = (value) => doSort(value);

        return (
          <Select
            defaultValue={neol().key}
            style={{ width: "100%" }}
            onChange={handleChange}
          >
            <Select.Option value="newest">
              <ClockCircleOutlined className="pr-2" />
              Newest
            </Select.Option>
            // eslint-disable-next-line indent
            <Select.Option value="oldest">
              <ClockCircleOutlined className="pr-2" rotate={180} />
              Oldest
            </Select.Option>
          </Select>
        );
      },
      ConditionSortMenu = () => {
        const [defaultValue, setDefaultValue] = React.useState(
          getSort("condition") ?? defaultCondition()?.value
        );

        const handleChange = (e) => {
          doSort("condition", e.target.value, false);
        };

        return (
          <Card
            size="small"
            title="Condition"
            style={{ width: "100%", marginBottom: "10px" }}
          >
            <Radio.Group onChange={handleChange} defaultValue={defaultValue}>
              <Space direction="vertical">
                <Radio value={undefined}>Show all</Radio>
                <Radio value="used">Used</Radio>
                <Radio value="unused">Unused</Radio>
              </Space>
            </Radio.Group>
          </Card>
        );
      },
      FurnishingSortMenu = () => {
        const handleChange = (value) => doSort("furnishing", value, false);

        return (
          <Card
            size="small"
            title="Condition"
            style={{ width: "100%", marginBottom: "10px" }}
          >
            <Select style={{ width: "100%" }} onChange={handleChange}>
              <Select.Option value="fully-furnished">
                Fully Furnished
              </Select.Option>
              <Select.Option value="semi-furnished">
                Semi Furnished
              </Select.Option>
              <Select.Option value="unfurnished">Unfurnished</Select.Option>
            </Select>
          </Card>
        );
      },
      RoomsSortMenu = () => {
        const handleChange = (value) => doSort("rooms", value, false);
        return (
          <Card
            size="small"
            title="Rooms"
            style={{ width: "100%", marginBottom: "10px" }}
          >
            <Select style={{ width: "100%" }} onChange={handleChange}>
              <Select.Option value="1">1</Select.Option>
              <Select.Option value="2">2</Select.Option>
              <Select.Option value="3">3</Select.Option>
              <Select.Option value="4">4</Select.Option>
              <Select.Option value="5">5</Select.Option>
              <Select.Option value="6">6</Select.Option>
              <Select.Option value="7">7</Select.Option>
              <Select.Option value="8">8</Select.Option>
              <Select.Option value="9">9</Select.Option>
              <Select.Option value="10+">10+</Select.Option>
            </Select>
          </Card>
        );
      },
      JobClassSortMenu = () => {
        const handleChange = (value) => doSort("job_class", value, false);

        return (
          <Card
            size="small"
            title="Job Class"
            style={{ width: "100%", marginBottom: "10px" }}
          >
            <Select
              defaultValue={
                getSortParam()?.find((pr) => pr.label == "job_class")?.value
              }
              style={{ width: "100%" }}
              onChange={handleChange}
            >
              <Select.Option value="hiring">
                <ClockCircleOutlined className="pr-2" />
                Hiring
              </Select.Option>
              <Select.Option value="searching">
                <ClockCircleOutlined className="pr-2" rotate={180} />
                Searching
              </Select.Option>
            </Select>
          </Card>
        );
      },
      AgeSortMenu = () => {
        return (
          <Card
            size="small"
            title="Age"
            style={{ width: "100%", marginBottom: "10px" }}
          >
            <div>
              <label className="d-block">Min</label>
              <InputNumber
                defaultValue={ageRangeDefault().min}
                formatter={(value) =>
                  `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
                }
                parser={(value) => value.replace(/\s?|(,*)/g, "")}
                onChange={(value) => doSort("aboveage", value, false)}
                style={{ width: "100%" }}
              />
            </div>
            <div className="mt-10">
              <label className="d-block">Max</label>
              <InputNumber
                defaultValue={ageRangeDefault().max}
                formatter={(value) =>
                  `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
                }
                parser={(value) => value.replace(/\s?|(,*)/g, "")}
                onChange={(value) => doSort("belowage", value)}
                style={{ width: "100%" }}
              />
            </div>
          </Card>
        );
      },
      GenderSortMenu = () => {
        const [defaultValue, setDefaultValue] = React.useState(
          getSort("gender") ?? defaultGender()?.value
        );

        const handleChange = (e) => {
          doSort("gender", e.target.value, false);
        };

        return (
          <Card
            size="small"
            title="Gender"
            style={{ width: "100%", marginBottom: "10px" }}
          >
            <Radio.Group onChange={handleChange} defaultValue={defaultValue}>
              <Space direction="vertical">
                <Radio value={undefined}>Show all</Radio>
                <Radio value="male">Male</Radio>
                <Radio value="female">Female</Radio>
                <Radio value="unisex">Unisex</Radio>
              </Space>
            </Radio.Group>
          </Card>
        );

        // const handleChange = value => doSort('gender', value, false);
        //
        // return (
        // 	<Card size="small" title="Gender" style={{ width: '100%', marginBottom: '10px' }}>
        // 		<Select defaultValue={getSortParam()?.find(pr => pr.label == 'gender')?.value} style={{ width: '100%' }} onChange={handleChange}>
        // 			<Select.Option value="male">
        // 				<ClockCircleOutlined className='pr-2' />
        // 	Male
        // 			</Select.Option>
        // 			<Select.Option value="female">
        // 				<ClockCircleOutlined className='pr-2' rotate={180} />
        // 	Female
        // 			</Select.Option>
        // 		</Select>
        // 	</Card>
        // );
      },
      JobTypeSortMenu = () => {
        const handleChange = (value) => doSort("job_type", value, false);

        return (
          <Card
            size="small"
            title="Condition"
            style={{ width: "100%", marginBottom: "10px" }}
          >
            <Select
              defaultValue={
                getSortParam()?.find((pr) => pr.label == "job_type")?.value
              }
              style={{ width: "100%" }}
              onChange={handleChange}
            >
              <Select.Option value="contract">
                <ClockCircleOutlined className="pr-2" />
                Contract
              </Select.Option>
              <Select.Option value="part_time">
                <ClockCircleOutlined className="pr-2" rotate={180} />
                Part Time
              </Select.Option>
              <Select.Option value="full_time">
                <ClockCircleOutlined className="pr-2" rotate={180} />
                Full Time
              </Select.Option>
              <Select.Option value="freelance">
                <ClockCircleOutlined className="pr-2" rotate={180} />
                Freelance
              </Select.Option>
              <Select.Option value="temporary">
                <ClockCircleOutlined className="pr-2" rotate={180} />
                Temporary
              </Select.Option>
            </Select>
          </Card>
        );
      };

    React.useEffect(() => {
      if (!classifieds?.length)
        fetchClassifieds(null, {
          queryParams: {
            include: "subclassifieds.".repeat(8).slice(0, -1),
          },
        });

      if (!districts?.length) fetchDistricts();
    }, []);

    // const [currentDistrict, setCurrentDistrict] = React.useState(districts?.find(ds => ds?.slug == match.params.slug));
    // React.useEffect(() => {
    // 	setCurrentDistrict(districts?.find(ds => ds?.slug == subdomain || ds?.slug == match?.params?.district_slug));
    // }, [districts, match.params.slug, match.params.district_slug]);

    return (
      <>
        <div className="ads-sidebar">
          <SelectDistrict
            style={{ width: "100%" }}
            currentPath={match.params.slug}
          >
            <button
              style={{ margin: 0, marginBottom: "10px" }}
              className="btn btn-sm btn-success w-100"
            >
              <i className="pr-1 far fa-map-marker"></i>
              <span>{currentDistrict?.name ?? "All of Ashanti"}</span>
            </button>
          </SelectDistrict>

          <div className="row">
            {!isEmpty(single_classified?.subclassifieds) ||
            !isEmpty(single_classified?.classified) ? (
              <div className="col-12">
                <Card
                  size="small"
                  title={
                    <>
                      <img
                        style={{
                          width: "15px",
                          height: "15px",
                          marginRight: "10px",
                        }}
                        src={single_classified.picture}
                        alt={single_classified.name}
                      />
                      {single_classified?.name}
                    </>
                  }
                  style={{ width: "100%", marginBottom: "10px" }}
                >
                  <ul className="list sort-menu-item-body">
                    {/* single_classified?.subclassifieds?.filter(cl => showAllSubclassifieds || single_classified?.subclassifieds?.length <= 3 ? true : single_classified?.subclassifieds?.indexOf(cl) < 3)?.map(cl => */}
                    {single_classified?.subclassifieds?.map((cl) => (
                      <li key={cl.id}>
                        <Link to={"/" + cl?.slug}>
                          <div className="single-list-category d-flex justify-content-between align-items-center">
                            <div className="category-icon">
                              <img
                                style={{
                                  width: "15px",
                                  height: "15px",
                                  marginRight: "10px",
                                }}
                                src={cl.picture}
                                alt={cl.name}
                              />
                            </div>
                            <div className="category-text">
                              <h6
                                style={{ fontSize: "14px" }}
                                className="title"
                              >
                                {cl.name}
                              </h6>
                            </div>
                          </div>
                        </Link>
                      </li>
                    ))}

                    {/* single_classified?.subclassifieds?.length > 3
									? (
										<li className='mt-10'>
										<Checkbox checked={showAllSubclassifieds} onChange={b => setShowAllSubclassifieds(b.target.checked)}>
										{showAllSubclassifieds ? 'Showing all items' : `Show all ${single_classified?.subclassifieds?.length} subcategories`}
										</Checkbox>
										</li>
									) : null */}
                  </ul>
                  {single_classified?.classified ? (
                    <li className="mt-10">
                      <Link
                        to={"/" + single_classified?.classified?.slug}
                        className="clr-1-important"
                      >
                        <i
                          className="fas fa-angle-double-left"
                          style={{ marginRight: "10px" }}
                        ></i>
                        Back to {single_classified?.classified?.name}
                      </Link>
                    </li>
                  ) : null}
                </Card>
              </div>
            ) : null}

            {!single_classified.classified_id ? (
              <div className="col-12" style={{ marginBottom: "30px" }}>
                <div>
                  <Menu
                    style={{
                      width: "100%",
                      border: "1px solid #f0f0f0",
                      paddingBottom: "10px",
                    }}
                    mode="vertical"
                  >
                    {classifieds
                      ?.filter((cl) => !cl.classified_id)
                      ?.map((cl) => (
                        <Menu.SubMenu
                          style={{ marginBottom: "0px", height: "30px" }}
                          key={cl.id}
                          icon={
                            <img
                              style={{
                                width: "15px",
                                height: "15px",
                                marginRight: "10px",
                              }}
                              src={cl.picture}
                            />
                          }
                          title={
                            <Link
                              className="text-sm clr-2-important"
                              to={"/" + cl?.slug}
                            >
                              {cl.name}
                            </Link>
                          }
                        >
                          {cl.subclassifieds?.map((subcl) => (
                            <Menu.Item
                              style={{ marginBottom: "0px", height: "30px" }}
                              key={subcl.id}
                              icon={
                                <img
                                  style={{
                                    width: "15px",
                                    height: "15px",
                                    marginRight: "10px",
                                  }}
                                  src={subcl.picture}
                                />
                              }
                            >
                              <Link className="text-sm" to={"/" + subcl?.slug}>
                                {subcl.name}
                              </Link>
                            </Menu.Item>
                          ))}
                        </Menu.SubMenu>
                      ))}
                  </Menu>
                </div>
              </div>
            ) : null}

            {JSON.parse(single_classified?.sort_options ?? "[]")
              ?.find((s) => typeof s == "object" && s.custom_sort)
              ?.custom_sort?.map((customSortOption) => (
                <div className="col-12">
                  <Card
                    className={
                      customSortOption?.options?.length > 7 ||
                      (customSortOption?.visual_type == "range" &&
                        customSortOption?.options?.length > 2)
                        ? "indicates-scroll"
                        : null
                    }
                    key={customSortOption?.key}
                    size="small"
                    title={customSortOption?.label}
                    style={{ width: "100%", marginBottom: "10px" }}
                  >
                    <div className="sort-menu-item-body">
                      {customSortOption?.visual_type == "range" ? (
                        <>
                          <div>
                            <label className="d-block">Min</label>
                            <InputNumber
                              value={getSort("min_" + customSortOption.key)}
                              // formatter={value => `GH₵ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                              parser={(value) =>
                                value.replace(/GH₵\s?|(,*)/g, "")
                              }
                              onChange={(value) =>
                                doSort(
                                  "min_" + customSortOption.key,
                                  value,
                                  false
                                )
                              }
                              style={{ width: "100%" }}
                            />
                          </div>
                          <div className="mt-10">
                            <label className="d-block">Max</label>
                            <InputNumber
                              value={getSort("max_" + customSortOption.key)}
                              // formatter={value => `GH₵ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                              parser={(value) =>
                                value.replace(/GH₵\s?|(,*)/g, "")
                              }
                              onChange={(value) =>
                                doSort(
                                  "max_" + customSortOption.key,
                                  value,
                                  false
                                )
                              }
                              style={{ width: "100%" }}
                            />
                          </div>
                          {customSortOption?.options ? (
                            <div className="mt-10">
                              <Radio.Group
                                onChange={(e) => {
                                  const split = e.target.value.split("-");
                                  const min = split[0];
                                  const max = split[1];
                                  doSort(
                                    "min_" + customSortOption?.key,
                                    min,
                                    false
                                  );
                                  doSort(
                                    "max_" + customSortOption?.key,
                                    max,
                                    false
                                  );
                                }}
                                value={`${getSort(
                                  "min_" + customSortOption.key
                                )}-${getSort("max_" + customSortOption.key)}`}
                              >
                                <Space direction="vertical">
                                  {customSortOption?.options?.map((op) => (
                                    <Radio
                                      key={op?.value}
                                      value={op?.value}
                                      style={{
                                        fontWeight: 600,
                                        fontSize: "13px",
                                        color: "rgba(0, 0, 0, 0.85)",
                                      }}
                                    >
                                      {op?.label}
                                    </Radio>
                                  ))}
                                </Space>
                              </Radio.Group>
                            </div>
                          ) : null}
                        </>
                      ) : null}

                      {customSortOption?.visual_type == "checkbox" ? (
                        <Checkbox.Group
                          onChange={(e) =>
                            doSort(customSortOption?.key, e.join("+"), false)
                          }
                          value={getSort(customSortOption?.key)
                            ?.split("+")
                            ?.filter((nu) => nu)}
                        >
                          <Space direction="vertical">
                            {customSortOption?.options?.map((op) => (
                              <Checkbox
                                key={op?.value}
                                value={op?.value}
                                style={{
                                  fontWeight: 600,
                                  fontSize: "13px",
                                  color: "rgba(0, 0, 0, 0.85)",
                                }}
                              >
                                {op?.label}
                              </Checkbox>
                            ))}
                          </Space>
                        </Checkbox.Group>
                      ) : null}

                      {!customSortOption?.visual_type ||
                      customSortOption?.visual_type == "radio" ? (
                        <Radio.Group
                          onChange={(e) =>
                            doSort(customSortOption?.key, e.target.value, false)
                          }
                          value={getSort(customSortOption?.key)}
                        >
                          <Space direction="vertical">
                            <Radio
                              value={undefined}
                              style={{
                                fontWeight: 600,
                                fontSize: "13px",
                                color: "rgba(0, 0, 0, 0.85)",
                              }}
                            >
                              Show all
                            </Radio>
                            {customSortOption?.options?.map((op) => (
                              <Radio
                                key={op?.value}
                                value={op?.value}
                                style={{
                                  fontWeight: 600,
                                  fontSize: "13px",
                                  color: "rgba(0, 0, 0, 0.85)",
                                }}
                              >
                                {op?.label}
                              </Radio>
                            ))}
                          </Space>
                        </Radio.Group>
                      ) : null}
                    </div>
                  </Card>
                </div>
              ))}

            <div className="mt-20 col-12">
              <Link
                className="btn btn-sm btn-success w-100"
                to={"?sort=" + sortValue}
              >
                Apply Filters
              </Link>
            </div>
          </div>
        </div>
      </>
    );
  },
  mapStateToProps = (state) => state,
  mapDispatchToProps = (dispatch) =>
    bindActionCreators(
      {
        fetchClassifieds,
        fetchDistricts,
      },
      dispatch
    ),
  TheMenu = connect(mapStateToProps, mapDispatchToProps)(SortBarComponent),
  SortBar = ({ match }: { match }) => {
    const [showDrawer, setShowDrawer] = React.useState(false);

    return document.body.getBoundingClientRect().width < 992 ? (
      <>
        <Drawer
          width="100vw"
          className="text-center"
          onClose={(e) => setShowDrawer(false)}
          title={<span>Sort</span>}
          placement="right"
          visible={showDrawer}
        >
          <TheMenu match={match} />
        </Drawer>
        <button
          className="btn btn-sm btn-success w-100"
          onClick={() => setShowDrawer(true)}
        >
          Filter Results
        </button>
      </>
    ) : (
      <TheMenu match={match} />
    );
  };

export default SortBar;
