import React, { useEffect, useState } from "react";
import DataTable from 'react-data-table-component';
import { useSelector } from "react-redux";
import { RootState } from "redux/reducers";
import { useAppDispatch } from "redux/store";
import { reset{modelName}ToInit, set{modelName}Message } from "redux/actions";
import { Box, Button, Card, CardHeader, CardContent, TextField, InputAdornment, IconButton, Grid, Typography } from "@mui/material";
import { Constant } from "template/Constant";
import ConfirmationModal from "template/ConfirmationModal";
import { delete{modelName} } from "services/{tableName}Service";
import { set{modelName}List } from "redux/actions";
import { get{modelName} } from "services/{tableName}Service";
import AddIcon from '@mui/icons-material/Add';
import RefreshIcon from '@mui/icons-material/Refresh';
{importFKRedux}
{importFKService}

type Props = {
  hideShowForm: (action: string) => void;
  handleRowEdit: (row: any) => void;
  getData: (page: number, pageSize: number, searchKey: string) => void;
  config: any;
  columnDefinitions: any[];
};

export const {modelName}Table: React.FC<Props> = ({
  hideShowForm,
  handleRowEdit,
  getData,
  columnDefinitions,
  config,
}) => {
  const dispatch = useAppDispatch();
  const [search, setSearch] = useState("");
  const [showDelete, setShowDelete] = useState(false);
  const [rowData, setRowData] = useState<any>(undefined);
  const rData = useSelector((state: RootState) => state.{tableName});
  const {tableName}Data = useSelector((state: RootState) => state.{tableName});
  {fkReduxInit}
  {useEffectForFK}

  useEffect(() => {
    if ({tableName}Data && {tableName}Data.list && {tableName}Data.list.length === 0) {
      dispatch(reset{modelName}ToInit());
      get{modelName}(Constant.defaultPageNumber, Constant.defaultDropdownPageSize, "").then((response) => {
        if (response && response.records) {
          dispatch(
            set{modelName}List({
              pageNo: Constant.defaultPageNumber,
              pageSize: Constant.defaultDropdownPageSize,
              list: response.records,
              totalCount: response.total_count,
              searchKey: "",
            })
          );
        } else {
          dispatch(set{modelName}Message(`No Record Found For {modelName}`));
        }
      });
    }
  }, [{tableName}Data.list.length]);

  const handleSearch = () => {
    if (search.length > 0) {
      getData(Constant.defaultPageNumber, Constant.defaultPageSize, search);
    }
  };

  const handlePerRowsChange = async (newPerPage: number, page: number) => {
    await getData(page, newPerPage, "");
  };

  const handlePageChange = (page: number) => {
    getData(page, rData.pageSize, "");
  };

  const handleRowDeleteClick = (row: any) => {
    setRowData(row);
    setShowDelete(true);
  };

  useEffect(() => {
    if (rData && rData.list && rData.list.length === 0) {
      dispatch(reset{modelName}ToInit());
      getData(Constant.defaultPageNumber, Constant.defaultPageSize, "");
    }
  }, [rData.list.length]);

  const handleReset = () => {
    setSearch("");
    dispatch(reset{modelName}ToInit());
    getData(Constant.defaultPageNumber, rData.pageSize, "");
  };

  const handleServerDelete = async () => {
    if (rowData) {
      const response = await delete{modelName}({primaryKeyList});
      if (response) {
        dispatch(reset{modelName}ToInit());
        dispatch(set{modelName}Message("Deleted Successfully"));
        getData(Constant.defaultPageNumber, Constant.defaultPageSize, "");
        setShowDelete(false);
      } else {
        dispatch(set{modelName}Message("Some error occurred!"));
      }
    }
  };

  const handleRowSelection = (row: any) => {
    console.log(row); // Row Selection Functionality can be written here
  };

  const handleAddButtonClick = () => {
    dispatch(set{modelName}Message(''));
    hideShowForm('add');
  };

  const columns = [
    ...columnDefinitions,
    {
      name: "",
      button: true,
      cell: (row: any) => <Button variant="contained" className="btn-sm" onClick={() => handleRowEdit(row)}>Edit</Button>,
      visible: true,
    },
    {
      name: "",
      button: true,
      cell: (row: any) => <Button variant="contained" className="btn-sm" onClick={() => handleRowDeleteClick(row)}>Delete</Button>,
      visible: true,
    },
  ];

  const filteredColumns = columns.filter((column) => column.visible);

  return (
    /*<Card className="shadow mb-4">
      <Card.Header className="py-3">
        <h6 className="m-0 font-weight-bold text-primary">
          {modelName} List ({rData.list.length})
          <Button variant="outlined" className="btn-circle btn-sm ml-2" onClick={handleReset}>
            <i className="fa fa-refresh"></i>
          </Button>
          <Button className="btn-icon-split float-right" onClick={handleAddButtonClick}>
            <span className="icon text-white-50">
              <i className="fas fa-add"></i>
            </span>
            <span className="text">Add New</span>
          </Button>
        </h6>
      </Card.Header>
      <Card.Body>
        <Col className="ml-auto" style={{ padding: "4px" }} md={3} xs={12} xl={3}>
          <TextField
            placeholder="Search"
            variant="outlined"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <Button
                    disabled={search.length <= 2}
                    variant="contained"
                    onClick={handleSearch}
                  >
                    Search
                  </Button>
                </InputAdornment>
              ),
            }}
          />
        </Col>
        <div className="table-responsive">
          <DataTable
            selectableRows
            onSelectedRowsChange={handleRowSelection}
            paginationPerPage={Constant.defaultPageNumber}
            paginationRowsPerPageOptions={Constant.paginationRowsPerPageOptions}
            columns={filteredColumns}
            data={rData.list}
            onChangeRowsPerPage={handlePerRowsChange}
            paginationTotalRows={rData.totalCount}
            className="custom-datatable table table-bordered"
            pagination
            paginationServer
            onChangePage={handlePageChange}
            customStyles={{
              headRow: {
                style: {
                  color: config["HeadRowColor"] !== undefined ? config["HeadRowColor"] : "#223336",
                  backgroundColor: config["HeadRowBackgroundColor"] !== undefined ? config["HeadRowBackgroundColor"] : "#e7eef0",
                  wordWrap: "break-word",
                },
              },
              rows: {
                style: {
                  color: config["RowColor"] !== undefined ? config["RowColor"] : "#223336",
                  backgroundColor: config["RowBackgroundColor"] !== undefined ? config["RowBackgroundColor"] : "#e7eef0",
                },
              },
            }}
          />
        </div>
      </Card.Body>
      <ConfirmationModal
        buttonNegative="Cancel"
        buttonPositive="Delete"
        title="Delete Confirmation"
        show={showDelete}
        body="Are you sure?"
        onNegative={() => setShowDelete(false)}
        onPositive={handleServerDelete}
      />
    </Card>*/
     <Card className="shadow mb-4">
    <CardHeader
      title={`{modelName} List (${rData.list.length})`}
      action={
        <>
          <IconButton onClick={handleReset}>
            <RefreshIcon />
          </IconButton>
          <Button className="btn-icon-split float-right" onClick={handleAddButtonClick} variant="contained" endIcon={<AddIcon />}>
            Add New
          </Button>
        </>
      }
    />
    <CardContent>
      <Grid container spacing={2} justifyContent="flex-end">
        <Grid item xs={12} md={3}>
          <TextField
            placeholder="Search"
            variant="outlined"
            fullWidth
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <Button
                    disabled={search.length <= 2}
                    variant="contained"
                    onClick={handleSearch}
                  >
                    Search
                  </Button>
                </InputAdornment>
              ),
            }}
          />
        </Grid>
      </Grid>
      <Box mt={2}>
        <DataTable
          selectableRows
          onSelectedRowsChange={handleRowSelection}
          paginationPerPage={Constant.defaultPageNumber}
          paginationRowsPerPageOptions={Constant.paginationRowsPerPageOptions}
          columns={filteredColumns}
          data={rData.list}
          onChangeRowsPerPage={handlePerRowsChange}
          paginationTotalRows={rData.totalCount}
          className="custom-datatable table table-bordered"
          pagination
          paginationServer
          onChangePage={handlePageChange}
          customStyles={{
            headRow: {
              style: {
                color: config["HeadRowColor"] !== undefined ? config["HeadRowColor"] : "#223336",
                backgroundColor: config["HeadRowBackgroundColor"] !== undefined ? config["HeadRowBackgroundColor"] : "#e7eef0",
                wordWrap: "break-word",
              },
            },
            rows: {
              style: {
                color: config["RowColor"] !== undefined ? config["RowColor"] : "#223336",
                backgroundColor: config["RowBackgroundColor"] !== undefined ? config["RowBackgroundColor"] : "#e7eef0",
              },
            },
          }}
        />
      </Box>
    </CardContent>
    <ConfirmationModal
      buttonNegative="Cancel"
      buttonPositive="Delete"
      title="Delete Confirmation"
      show={showDelete}
      body="Are you sure?"
      onNegative={() => setShowDelete(false)}
      onPositive={handleServerDelete}
    />
  </Card>
  );
};
