import React, { useEffect, useState } from "react";
import { Button, Tab, Tabs, TextField, Tooltip } from "@mui/material";
import axios from "axios";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { useDispatch, useSelector } from "react-redux";
import { provinceJahadGetHerdInfoDashboardService } from "../../services/province-jahad-get-herd-dashbored";
import { ProvinceJahadHerdsOperations } from "../province-jahad-herds-operations/ProvinceJahadHerdsOperations";
import { ProvicneJahadSubmitHerd } from "../province-jahad-submit-herd/ProvicneJahadSubmitHerd";
import { convertDaysToYMD } from "../../../../utils/formatTime";

export const ProvinceJahadHerds = () => {
  const dispatch = useDispatch();
  const userKey = useSelector((state) => state.userSlice.userProfile.key);

  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 [dashboardData, setDashboardData] = useState([]);
  const [value, setValue] = useState("0");

  const fetchApiData = async (page) => {
    let response;
    dispatch(LOADING_START());
    response = await axios.get(
      `/LiveStock/live-stock/live-stock-view/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}&type=${
        value === "0" ? "pending" : "archive"
      }`
    );

    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);
  };
  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };
  const handleChange = (event, newValue) => {
    setValue(newValue);
  };
  const handlePageChange = (page) => {
    fetchApiData(page);
    setPage(page);
  };

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

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

  const getDashboardData = () => {
    dispatch(
      provinceJahadGetHerdInfoDashboardService({
        search: textValue,
        type: value === "0" ? "pending" : "archive",
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.rancher?.fullname || "-",
        item?.rancher?.nationalId,
        item?.rancher?.mobile || "-",
        item?.rancher?.city || "-",
        item?.nationalIdLivestockCode || "-",
        item?.herdCode || "-",
        item?.type || "-",
        item?.birthDay || "-",
        item?.gender || "-",
        convertDaysToYMD(item?.age) || "-",
        item?.contractorCode || "-",
        item?.uniqueIdentifier || "-",
        item?.agent || "-",
        item?.registeringUser || "-",
        item?.registeringDate || "-",
        <ProvinceJahadHerdsOperations
          dataType={value === "0" ? "pending" : "archive"}
          key={i}
          item={item}
          getDashboardData={getDashboardData}
          updateTable={updateTable}
        />,
      ];
    });

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

  useEffect(() => {
    fetchApiData(1);
  }, [dispatch, perPage, value]);

  useEffect(() => {
    getDashboardData();
  }, []);

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

    try {
      const response = await axios.get(
        `/LiveStock/live-stock/live-stock-view/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=1&page_size=${perPage}&type=${
          value === "0" ? "pending" : "archive"
        }`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      getDashboardData();
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        <Grid
          container
          xs={12}
          justifyContent="center"
          alignItems="center"
          gap={2}
        >
          <Tabs value={value} onChange={handleChange}>
            <Tab value="0" label="فعال" />
            <Tab value="1" label="بایگانی شده" />
          </Tabs>
        </Grid>
        <Button
          variant="contained"
          // disabled
          aria-label="delete"
          color="primary"
          onClick={() => {
            dispatch(
              DRAWER({
                title: "ایجاد گله",
                right: !(window.innerWidth <= 600),
                bottom: window.innerWidth <= 600,
                content: (
                  <ProvicneJahadSubmitHerd
                    updateTable={updateTable}
                    getDashboardData={getDashboardData}
                  />
                ),
              })
            );
          }}
        >
          ایجاد گله
        </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>
        <Tooltip title="خروجی اکسل">
          <a
            href={`${
              axios.defaults.baseURL
            }live-stock-herds-excel/?role=${getRoleFromUrl()}&key=${userKey}`}
            rel="noreferrer"
          >
            <Button color="success">
              <RiFileExcel2Fill size={32} />
            </Button>
          </a>
        </Tooltip>
      </Grid>

      <Grid container mt={2} mb={4} isDashboard xs={12}>
        <ResponsiveTable
          noPagination
          isDashboard
          columns={[
            "تعداد گله",
            "تعداد گوسفندان",
            "تعداد بزها ",
            "تعداد گاوها",
            "تعداد اسب ها ",
            "تعداد شترها",
            "تعداد دام سبک",
            "تعداد دام سنگین",
            "مجموع دام ها",
          ]}
          data={[
            [
              dashboardData?.liveStocksCount?.toLocaleString(),
              dashboardData?.sheep?.toLocaleString(),
              dashboardData?.goat?.toLocaleString(),
              dashboardData?.cow?.toLocaleString(),
              dashboardData?.horse?.toLocaleString(),
              dashboardData?.camel?.toLocaleString(),
              dashboardData?.lightLivestock?.toLocaleString(),
              dashboardData?.heavyLivestock?.toLocaleString(),
              Math.round(
                dashboardData?.lightLivestock + dashboardData?.heavyLivestock
              )?.toLocaleString(),
            ],
          ]}
          title={"خلاصه اطلاعات"}
        />
      </Grid>
      <ResponsiveTable
        data={tableData}
        columns={[
          "ردیف",
          "دامدار",
          "کد ملی دامدار",
          "موبایل",
          "شهرستان",
          "کد ملی دام",
          "کد گله",
          "گونه",
          "تاریخ تولد",
          "جنسیت",
          "سن",
          "کد پیمانکار",
          "شناسه یکتای واحد کشاورزی",
          "مامور",
          "کاربر ثبت کننده",
          "تاریخ تکمیل فرم",
          "عملیات",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title="گله ها "
      />
    </Grid>
  );
};
