import React, { useEffect, useState } from "react";
import {
  Button,
  IconButton,
  TextField,
  RadioGroup,
  FormControlLabel,
  Radio,
  FormControl,
} from "@mui/material";
import axios from "axios";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { Grid } from "../../../../components/grid/Grid";
import { useDispatch, useSelector } from "react-redux";
import { SlaughterSellCarcassOutProvinceAddBuyer } from "../slaughter-sell-carcass-out-province-add-buyer/SlaughterSellCarcassOutProvinceAddBuyer";
import EditIcon from "@mui/icons-material/Edit";
import { RiSearchLine } from "react-icons/ri";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const SlaughterSellCarcassOutProvinceBuyers = () => {
  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  const dispatch = useDispatch();

  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [textValue, setTextValue] = useState("");
  const [page, setPage] = useState(1);
  const [tableData, setTableData] = useState([]);
  const [personType, setPersonType] = useState("real"); // real | legal
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    const response = await axios.get(
      `out-province-carcasses-buyer/?search=filter&value=${textValue}&role=${getRoleFromUrl()}${
        checkPathStartsWith("slaughter")
          ? `&role_key=${selectedSubUser?.key}`
          : ""
      }&page=${page}&page_size=${perPage}&state=buyer-list&type=${personType}`
    );
    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);
  };

  const handlePageChange = (page) => {
    fetchApiData(page);
    setPage(page);
  };

  const handlePerRowsChange = (perRows) => {
    setPerPage(perRows);
    setPage(1);
  };

  const updateTable = () => {
    fetchApiData(page !== 0 ? page : 1);
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      const baseCells = [page === 1 ? i + 1 : i + perPage * (page - 1) + 1];
      const buyerInfoCell = `${item?.fullname} (${item?.mobile})`;
      const editCell = (
        <IconButton
          color="primary"
          key={i}
          onClick={() => {
            dispatch(
              DRAWER({
                right: !(window.innerWidth <= 600),
                bottom: window.innerWidth <= 600,
                content: (
                  <SlaughterSellCarcassOutProvinceAddBuyer
                    updateTable={updateTable}
                    isEdit
                    data={item}
                    defaultPersonType={
                      item?.buyer?.parentLegalPersonNationalCode
                        ? "legal"
                        : "real"
                    }
                    defaultNationalCode={item?.buyer?.nationalCode}
                  />
                ),
                title: "ویرایش خریدار",
              })
            );
          }}
        >
          <EditIcon />
        </IconButton>
      );

      if (personType === "real") {
        return [
          ...baseCells,
          buyerInfoCell,
          item?.unitName,
          item?.province,
          item?.city,
          item?.requestsInfo?.numberOfRequests?.toLocaleString(),
          item?.requestsInfo?.totalQuantity?.toLocaleString(),
          item?.requestsInfo?.totalWeight?.toLocaleString(),
          editCell,
        ];
      } else {
        return [
          ...baseCells,
          item?.unitName,
          item?.buyer?.parentLegalPersonNationalCode,
          item?.province,
          item?.city,
          item?.requestsInfo?.numberOfRequests?.toLocaleString(),
          item?.requestsInfo?.totalQuantity?.toLocaleString(),
          item?.requestsInfo?.totalWeight?.toLocaleString(),
          editCell,
        ];
      }
    });

    setTableData(d);
  }, [data, personType, page, perPage, dispatch]);

  useEffect(() => {
    fetchApiData(1);
  }, [dispatch, perPage, personType, selectedSubUser?.key]);

  const handleSubmit = async (event) => {
    event.preventDefault();
    dispatch(LOADING_START());

    try {
      const response = await axios.get(
        `out-province-carcasses-buyer/?role=${getRoleFromUrl()}${
          checkPathStartsWith("slaughter")
            ? `&role_key=${selectedSubUser?.key}`
            : ""
        }&search=filter&value=${textValue}&page=${1}&page_size=${perPage}&state=buyer-list&type=${personType}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid
        container
        justifyContent="center"
        alignItems="center"
        gap={2}
        xs={12}
      >
        <FormControl>
          <RadioGroup
            style={{
              display: "flex",
              justifyContent: "center",
            }}
            row
            aria-labelledby="person-type-radio-group"
            name="personType"
            value={personType}
            onChange={(e) => {
              const val = e.target.value;
              setPersonType(val);
              setPage(1);
            }}
          >
            <FormControlLabel value="real" control={<Radio />} label="حقیقی" />
            <FormControlLabel value="legal" control={<Radio />} label="حقوقی" />
          </RadioGroup>
        </FormControl>
      </Grid>
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        <Button
          variant="contained"
          onClick={() => {
            dispatch(
              DRAWER({
                right: !(window.innerWidth <= 600),
                bottom: window.innerWidth <= 600,
                content: (
                  <SlaughterSellCarcassOutProvinceAddBuyer
                    updateTable={updateTable}
                  />
                ),
                title: "افزودن خریدار",
              })
            );
          }}
        >
          افزودن خریدار
        </Button>
        <Grid>
          <form onSubmit={handleSubmit}>
            <TextField
              id="outlined-basic"
              size="small"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button
              // disabled={!textValue}
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </form>
        </Grid>
      </Grid>

      <ResponsiveTable
        data={tableData}
        columns={
          personType === "real"
            ? [
                "ردیف",
                "مشخصات خریدار",
                "نام واحد",
                "استان",
                "شهر",
                "تعداد درخواست ها",
                "حجم تقریبی (قطعه)",
                "وزن (کیلوگرم)",
                "ویرایش",
              ]
            : [
                "ردیف",
                "نام واحد",
                "شناسه حقوقی",
                "استان",
                "شهر",
                "تعداد درخواست ها",
                "حجم تقریبی (قطعه)",
                "وزن (کیلوگرم)",
                "ویرایش",
              ]
        }
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title="خریداران لاشه خارج استان"
      />
    </Grid>
  );
};
