import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import axios from "axios";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { formatJustDate } from "../../../../utils/formatTime";
import { Grid } from "../../../../components/grid/Grid";
import { Button } from "@mui/material";
import { SPACING } from "../../../../data/spacing";
import { ProvinceSubmitPricing } from "../province-submit-pricing/ProvinceSubmitPricing";
import CustomCard from "../../../../components/custom-card/CustomCard";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { ProvincePriceEdit } from "../province-edit-price/ProvincePriceEdit";

export const ProvincePricing = () => {
  const dispatch = useDispatch();

  const [data, setData] = useState([]);
  const [dataTable, setDataTable] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [page, setPage] = useState(1);

  const fetchApiData = async (page) => {
    try {
      dispatch(LOADING_START());
      const response = await axios.get(
        `chicken-commission-prices/?role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}`
      );
      dispatch(LOADING_END());
      setData(response.data.results);
      setTotalRows(response.data.count);
    } catch (error) {
      console.error("Error fetching pricing data:", error);
      dispatch(LOADING_END());
    }
  };

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

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

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

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

  useEffect(() => {
    const d = data?.map((item, i) => [
      i + 1,
      formatJustDate(item?.date),
      item?.chickenAveragePrice?.toLocaleString() + " ﷼",
      item?.killHousePrice?.toLocaleString() + " ﷼",
      item?.wholesalerPrice?.toLocaleString() + " ﷼",
      item?.retailerPrice?.toLocaleString() + " ﷼",
      item?.priceInfo?.killHousePrice?.toLocaleString() + " ﷼",
      item?.priceInfo?.wholesalePrice?.toLocaleString() + " ﷼",
      item?.priceInfo?.retailPrice?.toLocaleString() + " ﷼",
      <ProvincePriceEdit key={i} updateTable={updateTable} item={item} />,
    ]);

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

  const role = getRoleFromUrl();

  const renderPriceCards = () => {
    if (!data || data.length === 0) return null;

    const latestData = data[0];

    const priceCards = [
      {
        title: "قیمت مرغ زنده",
        value: latestData?.chickenAveragePrice?.toLocaleString() + " ریال",
        date: formatJustDate(latestData?.createDate),
      },
      {
        title: "قیمت درب کشتارگاه",
        value:
          latestData?.priceInfo?.killHousePrice?.toLocaleString() + " ریال",
        date: formatJustDate(latestData?.createDate),
      },
      {
        title: "قیمت عمده فروشی",
        value:
          latestData?.priceInfo?.wholesalePrice?.toLocaleString() + " ریال",
        date: formatJustDate(latestData?.createDate),
      },
      {
        title: "قیمت خرده فروشی",
        value: latestData?.priceInfo?.retailPrice?.toLocaleString() + " ریال",
        date: formatJustDate(latestData?.createDate),
      },
    ];

    return (
      <Grid container mt={SPACING.SMALL} px={2}>
        {priceCards.map((card, index) => (
          <Grid item xs={12} sm={6} md={3} key={index} p={1}>
            <CustomCard
              title={card.title}
              value={`${card.value} - ${card.date}`}
            />
          </Grid>
        ))}
      </Grid>
    );
  };

  return (
    <>
      <Grid
        container
        direction="column"
        alignItems="start"
        justifyContent="center"
        gap={SPACING.SMALL}
        px={2}
      >
        {(role === "ProvinceFinancial" || role === "ProvinceOperator") && (
          <Grid container gap={SPACING.MEDIUM} alignItems="start">
            <Grid>
              <Button
                variant="contained"
                onClick={() => {
                  dispatch(
                    DRAWER({
                      right: !(window.innerWidth <= 600),
                      bottom: window.innerWidth <= 600,
                      title: "قیمت گذاری",
                      content: <ProvinceSubmitPricing />,
                    })
                  );
                }}
              >
                قیمت گذاری
              </Button>
            </Grid>
          </Grid>
        )}
      </Grid>

      {/* نمایش کارت‌های قیمت */}
      {renderPriceCards()}

      <Grid
        container
        alignItems="center"
        justifyContent="space-between"
        gap={SPACING.SMALL}
        mt={SPACING.MEDIUM}
        px={2}
      >
        <ResponsiveTable
          title="قیمت مرغ"
          name="بایگانی قیمت‌ها"
          columns={[
            "ردیف",
            "تاریخ",
            "قیمت مرغ زنده",
            " کارمزد کشتارگاه",
            "کارمزد عمده‌فروش",
            "کارمزد خرده‌فروش",
            "قیمت درب کشتارگاه",
            "قیمت عمده فروش",
            "قیمت خرده فروش",
            "عملیات",
          ]}
          customWidth="100%"
          data={dataTable}
          page={page}
          perPage={perPage}
          totalRows={totalRows}
          handlePageChange={handlePageChange}
          handlePerRowsChange={handlePerRowsChange}
        />
      </Grid>
    </>
  );
};
