import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Paper from "@mui/material/Paper";
import Pagination from "@mui/material/Pagination";
import Box from "@mui/material/Box";
import axios from "axios";
import { useEffect, useState } from "react";
import { NativeSelect } from "@mui/material";

const tableStyles = {
  tableContainer: {
    marginBottom: "16px",
    maxHeight: "70vh",
    overflow: "auto",
  },
  selectButton: {
    marginRight: "8px",
  },
};

function AdvancedTablePage({ columns, list, api }) {
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(5);
  const [tableData, setTableData] = useState([]);
  const [tableRows, setTableRows] = useState([]);
  const [totalRows, setTotalRows] = useState(0);

  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  const codeList = eval(list);

  function replacePlaceholders(inputHTML, item) {
    const replacedHTML = inputHTML.replace(
      /{(.*?)}/g,
      (match, propertyName) => {
        return item[propertyName] !== undefined ? item[propertyName] : "-";
      }
    );
    return <div dangerouslySetInnerHTML={{ __html: replacedHTML }} />;
  }

  useEffect(() => {
    const apiUrl = `${api}&page=${page + 1}&page_size=${rowsPerPage}`;
    axios.get(apiUrl).then((response) => {
      setTableData(response?.data?.results);
      setTotalRows(response?.data?.count);
    });
  }, [api, page, rowsPerPage]);

  useEffect(() => {
    const d = tableData?.map((item) => {
      const result = codeList.map((option) => {
        const properties = option.split(".");
        let value = item;
        for (const property of properties) {
          if (property.includes("<")) {
            value = replacePlaceholders(option, item);
          } else {
            value = value[property];
          }
        }
        return value;
      });
      return result;
    });

    setTableRows(d);
  }, [tableData, codeList]);

  return (
    <Box sx={{ width: "100%", marginBottom: "10px" }}>
      <TableContainer component={Paper} style={tableStyles.tableContainer}>
        <Table stickyHeader>
          <TableHead>
            <TableRow>
              {columns.map((column, index) => (
                <TableCell key={index}>{column}</TableCell>
              ))}
            </TableRow>
          </TableHead>
          <TableBody>
            {tableRows.map((row, rowIndex) => (
              <TableRow key={rowIndex}>
                {row.map((cell, cellIndex) => (
                  <TableCell key={cellIndex}>{cell}</TableCell>
                ))}
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>

      <Box display="flex" justifyContent="space-between" alignItems="center">
        <NativeSelect
          size="small"
          value={rowsPerPage}
          onChange={handleChangeRowsPerPage}
        >
          <option value={5}>5</option>
          <option value={10}>10</option>
          <option value={25}>25</option>
        </NativeSelect>

        <Pagination
          count={Math.ceil(totalRows / rowsPerPage)}
          page={page + 1}
          variant="outlined"
          onChange={(event, newPage) => {
            handleChangePage(event, newPage - 1);
          }}
        />
      </Box>
    </Box>
  );
}

export default AdvancedTablePage;

// sample usage
// <AdvancedTablePage
//             name="دوره های فعال جوجه ریزی"
//             api={`kill_house_request_bar_management/?check&role=${getRoleFromUrl()}&search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}`}
//             columns={[
//               "ردیف",
//               "نام فارم",
//               "سالن",
//               "دوره جوجه ریزی",
//               "تاریخ ثبت جوجه ریزی",
//               "تاریخ جوجه ریزی",
//               "نژاد",
//               "سن",
//               "تعداد جوجه ریزی",
//               "تلفات دوره",
//               "کشتار شده",
//               "مانده برای کشتار",
//               "اقدام",
//             ]}
//             list={[
//               "poultryRequest.poultry.address.city.name",
//               "poultryRequest.poultry.address.city.name",
//               "poultryRequest.poultry.address.city.name",
//               "poultryRequest.poultry.address.city.name",
//               "poultryRequest.poultry.address.city.name",
//               "poultryRequest.poultry.address.city.name",
//               "poultryRequest.poultry.address.city.name",
//               "poultryRequest.poultry.address.city.name",
//               "poultryRequest.poultry.address.city.name",
//               "poultryRequest.poultry.address.city.name",
//               "poultryRequest.poultry.address.city.name",
//               "poultryRequest.poultry.address.city.name",
//               "poultryRequest.poultry.address.city.name",
//             ]}
//           />
