import React, { useEffect, useState, useMemo } from 'react'
import { createPortal } from 'react-dom';
import { ToastContainer, toast } from 'react-toastify';
import BaseButton from '../BaseButton'
import CardBoxModal from '../CardBoxModal'
import CardBox from "../CardBox";
import { fetch, update, deleteItem, setRefetch, deleteItemsByIds } from '../../stores/approval_steps/approval_stepsSlice'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
import { useRouter } from 'next/router'
import { Field, Form, Formik } from "formik";
import {
    DataGrid,
    GridColDef,
} from '@mui/x-data-grid';
import {loadColumns} from "./configureApproval_stepsCols";
import _ from 'lodash';
import dataFormatter from '../../helpers/dataFormatter'
import {dataGridStyles} from "../../styles";



const perPage =  10 

const TableSampleApproval_steps = ({ filterItems, setFilterItems, filters, showGrid }) => {
  const notify = (type, msg) => toast( msg, {type, position: "bottom-center"});

    const dispatch = useAppDispatch();
    const router = useRouter();

    const pagesList = [];
    const [id, setId] = useState(null);
    const [currentPage, setCurrentPage] = useState(0);
    const [filterRequest, setFilterRequest] = React.useState('');
    const [columns, setColumns] = useState<GridColDef[]>([]);
    const [selectedRows, setSelectedRows] = useState([]);
    const [sortModel, setSortModel] = useState([
        {
            field: '',
            sort: 'desc',
        },
    ]);
  
  const { approval_steps, loading, count, notify: approval_stepsNotify, refetch } = useAppSelector((state) => state.approval_steps)
  const { currentUser } = useAppSelector((state) => state.auth);
    const numPages = Math.floor(count / perPage) === 0 ? 1 : Math.ceil(count / perPage);
    for (let i = 0; i < numPages; i++) {
        pagesList.push(i);
    }

    const loadData = async (page = currentPage, request = filterRequest) => {
        if (page !== currentPage) setCurrentPage(page);
        if (request !== filterRequest) setFilterRequest(request);
        const { sort, field } = sortModel[0];

      const query = `?page=${page}&limit=${perPage}${request}&sort=${sort}&field=${field}`;
      dispatch(fetch({ limit: perPage, page, query }));
  };

  useEffect(() => {
      if (approval_stepsNotify.showNotification) {
          notify(approval_stepsNotify.typeNotification, approval_stepsNotify.textNotification);
      }
  }, [approval_stepsNotify.showNotification]);

  useEffect(() => {
      if (!currentUser) return;
      loadData();
  }, [sortModel, currentUser]);

  useEffect(() => {
    if (refetch) {
      loadData(0);
      dispatch(setRefetch(false));
    }
  }, [refetch, dispatch]);

  const [isModalInfoActive, setIsModalInfoActive] = useState(false)
  const [isModalTrashActive, setIsModalTrashActive] = useState(false)

  const handleModalAction = () => {
    setIsModalInfoActive(false)
    setIsModalTrashActive(false)
  }

  

  

  const handleDeleteModalAction = (id: string) => {
    setId(id)
    setIsModalTrashActive(true)
  }
  const handleDeleteAction = async () => {
      if (id) {
          await dispatch(deleteItem(id));
          await loadData(0);
          setIsModalTrashActive(false);
      }
  };

  const generateFilterRequests = useMemo(() => {
    let request = '&';
    filterItems.forEach((item) => {
      const isRangeFilter = filters.find(
        (filter) =>
          filter.title === item.fields.selectedField &&
          (filter.number || filter.date),
      );

      if (isRangeFilter) {
        const from = item.fields.filterValueFrom;
        const to = item.fields.filterValueTo;
        if (from) {
          request += `${item.fields.selectedField}Range=${from}&`;
        }
        if (to) {
          request += `${item.fields.selectedField}Range=${to}&`;
        }
      } else {
        const value = item.fields.filterValue;
        if (value) {
          request += `${item.fields.selectedField}=${value}&`;
        }
      }
    });
    return request;
  }, [filterItems, filters]);

  const deleteFilter = (value) => {
    const newItems = filterItems.filter((item) => item.id !== value);

    if (newItems.length) {
        setFilterItems(newItems);
    } else {
        loadData(0, '');
        
        setFilterItems(newItems);
    }
  };

  const handleSubmit = () => {
    loadData(0, generateFilterRequests);
    
  };

  const handleChange = (id) => (e) => {
    const value = e.target.value;
    const name = e.target.name;

    setFilterItems(
      filterItems.map((item) => {
        if (item.id !== id) return item;
        if (name === 'selectedField') return { id, fields: { [name]: value } };

        return { id, fields: { ...item.fields, [name]: value } }
      }),
    );
  };

  const handleReset = () => {
      setFilterItems([]);
      loadData(0, '');
      
  };

  const onPageChange = (page: number) => {
    loadData(page);
    setCurrentPage(page);
  };

  
    useEffect(() => {
        if (!currentUser) return;

        loadColumns(
            handleDeleteModalAction,
            `approval_steps`,
            currentUser,
        ).then((newCols) => setColumns(newCols));
    }, [currentUser]);
  


  const handleTableSubmit = async (id: string, data) => {
    
    if (!_.isEmpty(data)) {
      await dispatch(update({ id, data }))
        .unwrap()
        .then((res) => res)
        .catch((err) => {
          throw new Error(err);
        });
    }
  };

  const onDeleteRows = async (selectedRows) => {
    await dispatch(deleteItemsByIds(selectedRows));
    await loadData(0);
  };

  const controlClasses =
      'w-full my-1.5 rounded-lg border border-[#D8D0C2] bg-white px-3 py-2 text-sm text-[#0E1A2B] shadow-sm outline-none placeholder:text-[#9A8F7F] focus:border-[#D8B75E] focus:ring-2 focus:ring-[#D8B75E]/25 dark:border-dark-700 dark:bg-slate-800 dark:placeholder-gray-400';


  const dataGrid = (
        <div  className='relative overflow-x-auto'>
          <DataGrid
              autoHeight
              rowHeight={64}
              sx={dataGridStyles}
              className={'datagrid--table'}
              getRowClassName={() => `datagrid--row`}
              rows={approval_steps ?? []}
              columns={columns}
              initialState={{
                  pagination: {
                      paginationModel: {
                          pageSize: 10,
                      },
                  },
              }}
              disableRowSelectionOnClick
              onProcessRowUpdateError={(params) => {
                  console.log('Error', params);
              }}
              processRowUpdate={async (newRow, oldRow) => {
                const data = dataFormatter.dataGridEditFormatter(newRow);

                try {
                  await handleTableSubmit(newRow.id, data);
                  return newRow;
                } catch {
                  return oldRow;
                }
              }}
              sortingMode={'server'}
              checkboxSelection
              onRowSelectionModelChange={(ids) => {
                setSelectedRows(ids)
              }}
              onSortModelChange={(params) => {
                  params.length
                      ? setSortModel(params)
                      : setSortModel([{ field: '', sort: 'desc' }]);
              }}
              rowCount={count}
              pageSizeOptions={[10]}
              paginationMode={'server'}
              loading={loading}
              onPaginationModelChange={(params) => {
                  onPageChange(params.page);
              }}
          />
        </div>
  )

  return (
    <>
    {filterItems && Array.isArray( filterItems ) && filterItems.length ?
        <CardBox className='mb-6 border border-[#DDD5C7] bg-[#FBF8F1] shadow-sm'>
            <Formik
                initialValues={{
                    checkboxes: ['lorem'],
                    switches: ['lorem'],
                    radio: 'lorem',
                }}
                onSubmit={() => null}
            >
                <Form>
                    <>
                        <div className='mb-4 flex flex-wrap items-center justify-between gap-3'>
                            <div>
                                <p className='text-xs font-semibold uppercase tracking-[0.14em] text-[#7A5B13]'>Active filters</p>
                                <p className='mt-1 text-sm text-[#5B6472]'>Narrow the register without leaving the governance workspace.</p>
                            </div>
                            <span className='rounded-full border border-[#D8B75E] bg-[#FFF8DF] px-3 py-1 text-xs font-semibold text-[#7A5B13]'>Review scope</span>
                        </div>
                        {filterItems && filterItems.map((filterItem) => {
                            return (
                                <div key={filterItem.id} className="grid gap-3 rounded-lg border border-[#E5E0D6] bg-white p-4 shadow-sm md:grid-cols-[minmax(180px,0.9fr)_minmax(240px,1.4fr)_auto] md:items-end">
                                    <div className="flex flex-col w-full">
                                        <div className="text-xs font-semibold uppercase tracking-[0.12em] text-[#7A5B13]">Filter</div>
                                        <Field
                                            className={controlClasses}
                                            name='selectedField'
                                            id='selectedField'
                                            component='select'
                                            value={filterItem?.fields?.selectedField || ''}
                                            onChange={handleChange(filterItem.id)}
                                        >
                                            {filters.map((selectOption) => (
                                                <option
                                                    key={selectOption.title}
                                                    value={`${selectOption.title}`}
                                                >
                                                    {selectOption.label}
                                                </option>
                                            ))}
                                        </Field>
                                    </div>
                                    {filters.find((filter) => 
                                        filter.title === filterItem?.fields?.selectedField
                                    )?.type === 'enum' ? (
                                        <div className="flex flex-col w-full">
                                            <div className="text-xs font-semibold uppercase tracking-[0.12em] text-[#7A5B13]">
                                                Value
                                            </div>
                                            <Field
                                                className={controlClasses}
                                                name="filterValue"
                                                id='filterValue'
                                                component="select"
                                                value={filterItem?.fields?.filterValue || ''}
                                                onChange={handleChange(filterItem.id)}
                                            >
                                                <option value="">Select Value</option>
                                                {filters.find((filter) => 
                                                    filter.title === filterItem?.fields?.selectedField
                                                )?.options?.map((option) => (
                                                    <option key={option} value={option}>
                                                        {option}
                                                    </option>
                                                ))}
                                            </Field>
                                        </div>
                                    ) : filters.find((filter) => 
                                        filter.title === filterItem?.fields?.selectedField
                                    )?.number ? (
                                        <div className="grid w-full gap-3 sm:grid-cols-2">
                                            <div className="flex flex-col w-full">
                                                <div className="text-xs font-semibold uppercase tracking-[0.12em] text-[#7A5B13]">From</div>
                                                <Field
                                                    className={controlClasses}
                                                    name='filterValueFrom'
                                                    placeholder='From'
                                                    id='filterValueFrom'
                                                    value={filterItem?.fields?.filterValueFrom || ''}
                                                    onChange={handleChange(filterItem.id)}
                                                />
                                            </div>
                                            <div className="flex flex-col w-full">
                                                <div className="text-xs font-semibold uppercase tracking-[0.12em] text-[#7A5B13]">To</div>
                                                <Field
                                                    className={controlClasses}
                                                    name='filterValueTo'
                                                    placeholder='to'
                                                    id='filterValueTo'
                                                    value={filterItem?.fields?.filterValueTo || ''}
                                                    onChange={handleChange(filterItem.id)}
                                                />
                                            </div>
                                        </div>
                                    ) : filters.find(
                                        (filter) =>
                                            filter.title ===
                                            filterItem?.fields?.selectedField
                                    )?.date ? (
                                        <div className='grid w-full gap-3 sm:grid-cols-2'>
                                            <div className='flex flex-col w-full'>
                                                <div className='text-xs font-semibold uppercase tracking-[0.12em] text-[#7A5B13]'>
                                                    From
                                                </div>
                                                <Field
                                                    className={controlClasses}
                                                    name='filterValueFrom'
                                                    placeholder='From'
                                                    id='filterValueFrom'
                                                    type='datetime-local'
                                                    value={filterItem?.fields?.filterValueFrom || ''}
                                                    onChange={handleChange(filterItem.id)}
                                                />
                                            </div>
                                            <div className='flex flex-col w-full'>
                                                <div className='text-xs font-semibold uppercase tracking-[0.12em] text-[#7A5B13]'>To</div>
                                                <Field
                                                    className={controlClasses}
                                                    name='filterValueTo'
                                                    placeholder='to'
                                                    id='filterValueTo'
                                                    type='datetime-local'
                                                    value={filterItem?.fields?.filterValueTo || ''}
                                                    onChange={handleChange(filterItem.id)}
                                                />
                                            </div>
                                        </div>
                                    ) : (
                                        <div className="flex flex-col w-full">
                                            <div className="text-xs font-semibold uppercase tracking-[0.12em] text-[#7A5B13]">Contains</div>
                                            <Field
                                                className={controlClasses}
                                                name='filterValue'
                                                placeholder='Contained'
                                                id='filterValue'
                                                value={filterItem?.fields?.filterValue || ''}
                                                onChange={handleChange(filterItem.id)}
                                            />
                                        </div>
                                    )}
                                    <div className="flex flex-col">
                                        <div className="text-xs font-semibold uppercase tracking-[0.12em] text-[#7A5B13]">Action</div>
                                        <BaseButton
                                            className="my-2"
                                            type='reset'
                                            color='danger'
                                            label='Delete'
                                            onClick={() => {
                                                deleteFilter(filterItem.id)
                                            }}
                                        />
                                    </div>
                                </div>
                            )
                        })}
                        <div className="flex flex-wrap gap-2">
                            <BaseButton
                                className="my-2 mr-3"
                               color="info"
                                label='Apply'
                                onClick={handleSubmit}
                            />
                            <BaseButton
                                className="my-2"
                                 color='whiteDark'
                                label='Reset'
                                onClick={handleReset}
                            />
                        </div>
                    </>
                </Form>
            </Formik>
        </CardBox> : null
    }
      <CardBoxModal
        title="Please confirm"
        buttonColor="info"
        buttonLabel={loading ? 'Deleting...' : 'Confirm'}
        isActive={isModalTrashActive}
        onConfirm={handleDeleteAction}
        onCancel={handleModalAction}
      >
        <p>Are you sure you want to delete this item?</p>
      </CardBoxModal>

      
        {dataGrid}
      

      

      {selectedRows.length > 0 &&
        createPortal(
          <BaseButton
            className='me-4'
            color='danger'
            label={`Delete ${selectedRows.length === 1 ? 'Row' : 'Rows'}`}
            onClick={() => onDeleteRows(selectedRows)}
          />,
          document.getElementById('delete-rows-button'),
      )}
    <ToastContainer />
    </>
  )
}

export default TableSampleApproval_steps
