import { useState, useEffect, useRef } from 'react';
import { useDispatch } from 'react-redux';
import { useNavigate, useLocation } from 'react-router-dom';
import { Checkbox, Form } from 'antd';
import { ArrowRightOutlined } from '@ant-design/icons';
import { DropDowns } from '../../Components/Forms/DropDown.jsx';
import Buttons from '../../Components/Forms/Buttons.jsx';
import { Messages } from '../../Components/Notifications/Messages';
import FormHeader from '../PageComponents/FormHeader.jsx';
import { changeBreadCrumb } from '../../Features/AppPage/CenterPage.js';
import Search from '../../Components/Forms/Search.jsx';
import { getSession } from '../../Services/Others';
import { Tables } from '../../Components/Tables/Table';
import {
  getEmpListBasedOnCmpIdBrIDEdit,
  getEmpListBasedOnCmpIdBrID,
  getMasterOptionList,
  postEmpAccess,
  putEmpAccess,
} from '../../Features/EmpAccess/EmpAccess.js';
import '../../Styles/EmpAccess/EmpAccess.scss';
import { FeatureAddon } from '../../Features/BookingScreen/BookingData/BookingData.js';
import {
  ApplicationPreferences,
  PricingAppPricingName,
} from '../../Features/BrachLogin/BranchLogin.js';
import { gettableData } from '../../Features/PreferenceMaster/PreferenceMaster.js';
import { useSelector } from 'react-redux';

const subDirectory = import.meta.env.BASE_URL;

const EmpAccessForm = ({ formType }) => {
  const formRef = useRef(null);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const location = useLocation();
  const state = location?.state;
  const editstate = state?.editstate;
  const PricingName = state?.PricingName;

  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [SelectedUserData, setSelectedUserData] = useState();
  const [userDropDown, setuserDropDown] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [cmpId, setcmpId] = useState(getSession('CompId'));
  const [brId, setBrId] = useState(getSession('BranchId'));
  const [AppId, setAppId] = useState(getSession('AppId'));
  const UserId = getSession('UserId');
  const UserType = getSession('UserType');
  const [TableData, setTableData] = useState([]);
  const [FeatureAddonData, setFeatureAddonData] = useState([]);
  const [searchedText, setSearchedText] = useState('');
  const [DineinData, setDineinData] = useState(false);
  const [EstimateData, setEstimateData] = useState(false);
  const appPreferences = useSelector(ApplicationPreferences);
  const bookingTypePreference = appPreferences?.find(
    (preference) => preference?.PreferredCatName === 'Booking Type'
  )?.PreferenceCatDetails;
  const dinePreference = bookingTypePreference?.find(
    (type) =>
      type?.PreferredSubCatName?.toLowerCase() === 'dine in' &&
      type?.PreferredStatus === 'Y'
  );

  const AppType = getSession('AppType');

  const validationMaster = [
    'Kiosk Setup',
    'Kiosk Sales',
    'Product Catalogue',
    'Print Setup',
    'Sales Setup',
  ];
  const items = [
    {
      name: 'Home',
      link: `${subDirectory}app-page/home`,
    },

    {
      name: 'Employee Access',
      link: `${subDirectory}setting/employee-access`,
    },
    {
      name: editstate ? 'Edit' : 'New',
      link: null,
    },
  ];

  useEffect(() => {
    const fetchData = async () => {
      try {
        let Dineindata;
        let Estimatedata;
        if (AppId && cmpId && brId) {
          let DineinData = {
            AppId: AppId,
            CompId: cmpId,
            BranchId: brId,
            UserId: UserId,
          };
          const response = await dispatch(gettableData(DineinData)).unwrap();
          if (response?.data?.statusCode === 1) {
            const SettingValueData = response?.data?.data
              ?.find((e) => e.AppId === AppId)
              ?.SettingDtlDetails?.some(
                (e) => e.SettingIdName === 'DineIn' && e.SettingValue === 'Y'
              );
            if (SettingValueData) {
              setDineinData(true);
              Dineindata = true;
            } else {
              setDineinData(false);
              Dineindata = false;
            }
            const EstimateValueData = response?.data?.data
              ?.find((e) => e.AppId === AppId)
              ?.SettingDtlDetails?.some(
                (e) =>
                  e.SettingIdName === 'Estimation' && e.SettingValue === 'Y'
              );
            if (EstimateValueData) {
              setEstimateData(true);
              Estimatedata = true;
            } else {
              setEstimateData(false);
              Estimatedata = false;
            }
          } else {
            setDineinData(false);
            setEstimateData(false);
          }
        } // Ensure this is awaited if it returns a promise
        if (UserType !== 'Super Admin' && UserType !== 'Super Admin User') {
          let featureAddon = await dispatch(
            FeatureAddon({ AppId: AppId, UserId: UserId })
          ).unwrap();

          if (featureAddon?.data?.statusCode === 1) {
            var DataUpdate =
              featureAddon?.data?.data?.[0]?.FeatAddonHdr?.[0]?.FeatureDtls?.flatMap(
                (e) => {
                  if (
                    e?.FeatureAddonName === 'Customized Template' ||
                    PricingName
                  ) {
                    return ['Sales Setup']; // Change name to "Sales Setup" if it matches
                  }
                  if (e?.FeatureAddonName === 'Kiosk Sales') {
                    return ['Kiosk Sales', 'Kiosk Setup']; // Return both names in an array
                  }
                  return e?.FeatureAddonName ? [e?.FeatureAddonName] : []; // Return the original name in an array
                }
              );

            setFeatureAddonData(DataUpdate);
          } else {
            setFeatureAddonData([]);
          }
        }
        // Ensure this is awaited if it returns a promise
        dispatch(changeBreadCrumb({ items: items }));

        if (formType === 'edit' && editstate) {
          editFetch();
          formRef.current?.setFieldsValue({ EmpId: editstate?.EmpId });
          setSelectedUserData(editstate?.EmpId);
          console.log(editstate?.EmpAccessDetails, 'DineinDataDineinData');
          let FillterData = editstate?.EmpAccessDetails?.filter((e) => {
            if (
              (e?.ConfigName === 'KOT' && !Dineindata) ||
              (e?.ConfigName === 'Dine In' && !Dineindata) ||
              (e?.ConfigName === 'Estimate' && !Estimatedata)
            ) {
              return false;
            } else if (!validationMaster?.includes(e?.ConfigName)) {
              return e;
            } else if (
              (PricingName &&
                e?.ConfigName !== 'Kiosk Setup' &&
                e?.ConfigName !== 'Kiosk Sales') ||
              DataUpdate?.includes(e?.ConfigName)
            ) {
              return e;
            }
            return false;
          });

          let AfterFilterData = [];

          if (AppType?.toLowerCase() === 'wholesale') {
            const validConfigNames = [
              'Whole Sales',
              'Product',
              'Seller',
              'Employee',
              'Shift',
              'Employee Access',
              'Customer',
              'Common Master',
              'Config Type',
              'Product Entry',
              'Employee Screen Rights',
              'Ledger',
              'Preorder',
              'Abstract',
              'Sales',
              'Payment Received',
              'Seller Payment',
              'Android App',
              'Sales Report',
              'Purchase Report',
              'Purchase Payment',
              'Sales Payment',
            ];
            AfterFilterData =
              FillterData?.filter((item) =>
                validConfigNames?.includes(item.ConfigName)
              ) || [];
          } else {
            const validConfigNames = ['Whole Sales', 'Product Entry'];
            !dinePreference && validConfigNames.push('Dine In', 'KOT');
            AfterFilterData =
              FillterData?.filter(
                (item) => !validConfigNames?.includes(item.ConfigName)
              ) || [];
          }

          setTableData(AfterFilterData);

          let FilterSelectitems = AfterFilterData?.filter(
            (item) =>
              'Y' === item.AddAccess ||
              'Y' === item.UpdateAccess ||
              'Y' === item.DeleteAccess ||
              'Y' === item.ReadAccess
          );

          let tempSelectList = FilterSelectitems.map((a) => a.MenuId);
          setSelectedRowKeys(tempSelectList);
          formRef.current?.setFieldsValue(editstate);
        } else {
          GetUserData();
        }
        // else {
        //   navigate(`${subDirectory}setting/employee-access/`);
        // }
      } catch (err) {
        console.log(err, 'err');
      }
    };

    fetchData(); // Call the async function
    // GetUserData();
    // Optional: Cleanup function to avoid memory leaks
    return () => {
      // You can perform any cleanup tasks if needed
    };
  }, []);
  // Ensure dependencies are set if required

  async function editFetch() {
    // getEmpListBasedOnCmpIdBrIDEdit
    let data = {
      CompId: cmpId,
      BranchId: brId,
      // 'AppId':AppId
    };
    const gettingEmpData = await dispatch(
      getEmpListBasedOnCmpIdBrIDEdit(data)
    ).unwrap();
    if (gettingEmpData?.data?.statusCode === 1) {
      setuserDropDown(gettingEmpData?.data?.data);
    }
  }

  async function GetUserData() {
    let data = {
      CompId: cmpId,
      BranchId: brId,
      AppId: AppId,
    };
    const gettingEmpData = await dispatch(
      getEmpListBasedOnCmpIdBrID(data)
    ).unwrap();
    if (gettingEmpData?.data?.statusCode === 1) {
      setuserDropDown(gettingEmpData?.data?.data);
    }
    const MsrtList = await dispatch(getMasterOptionList()).unwrap();
    if (MsrtList?.data?.statusCode === 1) {
      let MsrtListData;
      const validConfigNames =
        AppType?.toLowerCase() === 'wholesale'
          ? [
              'Whole Sales',
              'Product',
              'Seller',
              'Employee',
              'Shift',
              'Employee Access',
              'Customer',
              'Common Master',
              'Config Type',
              'Product Entry',
              'Employee Screen Rights',
              'Ledger',
              'Preorder',
              'Abstract',
              'Sales',
              'Payment Received',
              'Seller Payment',
              'Android App',
              'Sales Report',
              'Purchase Report',
              'Purchase Payment',
              'Sales Payment',
            ]
          : ['Whole Sales', 'Product Entry'];
      AppType?.toLowerCase() !== 'wholesale' &&
        !dinePreference &&
        validConfigNames.push('Dine In', 'KOT');
      MsrtListData = MsrtList?.data?.data?.filter((item) => {
        if (AppType?.toLowerCase() === 'wholesale') {
          return validConfigNames?.includes(item.ConfigName);
        } else {
          return !validConfigNames?.includes(item.ConfigName);
        }
      });

      let tempListData = [];
      let i = 0;
      for (i = 0; i < MsrtListData?.length; i++) {
        let configname = MsrtListData[i]?.ConfigName;
        if (
          (configname === 'KOT' && !DineinData) ||
          (configname === 'Dine In' && !DineinData) ||
          (configname === 'Estimate' && !EstimateData)
        ) {
          continue;
        }
        if (validationMaster?.includes(configname)) {
          if (
            (PricingName &&
              configname !== 'Kiosk Setup' &&
              configname !== 'Kiosk Sales') ||
            FeatureAddonData?.includes(configname)
          ) {
            tempListData.push({
              key: MsrtListData[i]?.ConfigId,
              MenuId: MsrtListData[i]?.ConfigId,
              ConfigName: MsrtListData[i]?.ConfigName,
              AddAccess: 'N',
              UpdateAccess: 'N',
              ReadAccess: 'N',
              DeleteAccess: 'N',
            });
          }
        } else {
          tempListData.push({
            key: MsrtListData[i]?.ConfigId,
            MenuId: MsrtListData[i]?.ConfigId,
            ConfigName: MsrtListData[i]?.ConfigName,
            AddAccess: 'N',
            UpdateAccess: 'N',
            ReadAccess: 'N',
            DeleteAccess: 'N',
          });
        }
      }
      setTableData(tempListData);
      setSelectedRowKeys([]);
    }
  }

  const onFinish = async (values) => {
    let postData = values;
    postData['CompId'] = cmpId;
    postData['BranchId'] = brId;
    postData['AppId'] = AppId;
    postData['EmpId'] = SelectedUserData;

    postData['EmpAccessDetails'] = TableData;
    let response = {};
    if (formType === 'add') {
      postData['CreatedBy'] = getSession('UserId');
      response = await dispatch(postEmpAccess(postData)).unwrap();
    } else if (formType === 'edit') {
      if (editstate) {
        postData['UpdatedBy'] = getSession('UserId');
      }
      response = await dispatch(putEmpAccess(postData)).unwrap();
    }

    if (response?.data?.statusCode == 1) {
      navigate(`${subDirectory}setting/employee-access/`, {
        state: {
          Notiffy: {
            messageType: 'success',
            messageData: response?.data?.response,
          },
        },
      });
    } else {
      setMessageType('error');
      setMessageData(response?.data?.response);
    }
  };

  const UserDropDownChange = async (e) => {
    formRef.current?.setFieldsValue({ EmpId: e });
    setSelectedUserData(e);
    GetUserData();
  };

  const columns = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',
      width: '80px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{index + 1}</a>
      ),
    },
    {
      title: 'Option Name',
      dataIndex: 'ConfigName',
      key: 'ConfigName',
      width: '180px',
      render: (text, row) => (
        <a style={{ color: 'black', width: '200px' }}>{text}</a>
      ),
      filteredValue: [searchedText],
      onFilter: (value, record) => {
        console.log(value, record, '(value, record');

        return (
          String(record.ConfigName)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase()) ||
          String(record.ConfigName)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase()) ||
          String(record.ConfigName)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase())
        );
      },
    },
    {
      title: 'View',
      dataIndex: 'ReadAccess',
      key: 'ReadAccess',
      render: (text, row) => (
        <a style={{ color: 'black' }}>
          <Checkbox
            checked={text === 'Y'}
            onClick={() =>
              onChangeSingleCheck('ReadAccess', row, text === 'Y' ? 'N' : 'Y')
            }
          />
        </a>
      ),
    },
    {
      title: 'Add',
      dataIndex: 'AddAccess',
      key: 'AddAccess',
      render: (text, row) => (
        <a style={{ color: 'black' }}>
          <Checkbox
            checked={text === 'Y'}
            disabled={!row.ReadAccess || row.ReadAccess !== 'Y'} // Always disabled unless 'View' is selected
            onClick={() =>
              onChangeSingleCheck('AddAccess', row, text === 'Y' ? 'N' : 'Y')
            }
          />
        </a>
      ),
    },
    {
      title: 'Edit',
      dataIndex: 'UpdateAccess',
      key: 'UpdateAccess',
      render: (text, row) => (
        <a style={{ color: 'black' }}>
          <Checkbox
            checked={text === 'Y'}
            disabled={!row.ReadAccess || row.ReadAccess !== 'Y'} // Always disabled unless 'View' is selected
            onClick={() =>
              onChangeSingleCheck('UpdateAccess', row, text === 'Y' ? 'N' : 'Y')
            }
          />
        </a>
      ),
    },
    {
      title: 'Delete',
      dataIndex: 'DeleteAccess',
      key: 'DeleteAccess',
      render: (text, row) => (
        <a style={{ color: 'black' }}>
          <Checkbox
            checked={text === 'Y'}
            disabled={!row.ReadAccess || row.ReadAccess !== 'Y'} // Always disabled unless 'View' is selected
            onClick={() =>
              onChangeSingleCheck('DeleteAccess', row, text === 'Y' ? 'N' : 'Y')
            }
          />
        </a>
      ),
    },
  ];

  const onSelectChange = (newSelectedRowKeys) => {
    var oldSelectedRowKeys = selectedRowKeys;
    if (oldSelectedRowKeys?.length === 0 && newSelectedRowKeys?.length === 1) {
      var updatedselectList = TableData?.map((item) => {
        if (parseInt(item.MenuId) === parseInt(newSelectedRowKeys[0])) {
          return {
            ...item,
            key: item?.key,
            MenuId: item?.MenuId,
            ConfigName: item?.ConfigName,
            AddAccess: 'Y',
            UpdateAccess: 'Y',
            ReadAccess: 'Y',
            DeleteAccess: 'Y',
          };
        }
        return item;
      });
    } else if (
      oldSelectedRowKeys?.length === 0 &&
      newSelectedRowKeys?.length > 1
    ) {
      var updatedselectList = TableData?.map((item) => {
        // if (parseInt(item.MenuId) ===  parseInt(newSelectedRowKeys[0])) {
        return {
          ...item,
          key: item?.key,
          MenuId: item?.MenuId,
          ConfigName: item?.ConfigName,
          AddAccess: 'Y',
          UpdateAccess: 'Y',
          ReadAccess: 'Y',
          DeleteAccess: 'Y',
        };
      });
    } else if (newSelectedRowKeys?.length === 0) {
      var updatedselectList = TableData?.map((item) => {
        return {
          ...item,
          key: item?.key,
          MenuId: item?.MenuId,
          ConfigName: item?.ConfigName,
          AddAccess: 'N',
          UpdateAccess: 'N',
          ReadAccess: 'N',
          DeleteAccess: 'N',
        };
      });
    } else if (
      oldSelectedRowKeys?.length > 0 &&
      newSelectedRowKeys?.length >= 1
    ) {
      if (oldSelectedRowKeys?.length < newSelectedRowKeys?.length) {
        let newVal = newSelectedRowKeys?.filter(
          (id) => !oldSelectedRowKeys?.includes(id)
        );
        var updatedselectList = TableData?.map((item) => {
          if (newVal?.includes(item?.MenuId)) {
            return {
              ...item,
              key: item?.key,
              MenuId: item?.MenuId,
              ConfigName: item?.ConfigName,
              AddAccess: 'Y',
              UpdateAccess: 'Y',
              ReadAccess: 'Y',
              DeleteAccess: 'Y',
            };
          }
          return item;
        });
      } else if (oldSelectedRowKeys?.length > newSelectedRowKeys?.length) {
        let newVal = oldSelectedRowKeys?.filter(
          (id) => !newSelectedRowKeys?.includes(id)
        );
        var updatedselectList = TableData?.map((item) => {
          if (newVal?.includes(item?.MenuId)) {
            return {
              ...item,
              key: item?.key,
              MenuId: item?.MenuId,
              ConfigName: item?.ConfigName,
              AddAccess: 'N',
              UpdateAccess: 'N',
              ReadAccess: 'N',
              DeleteAccess: 'N',
            };
          }
          return item;
        });
      }
    }

    setSelectedRowKeys(newSelectedRowKeys);
    setTableData(updatedselectList);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const onChangeSingleCheck = (mode, e, updateData) => {
    let updatedItemList = TableData?.map((item) => {
      if (parseInt(item.MenuId) === parseInt(e?.MenuId)) {
        let updateObj = { ...item, [mode]: updateData };
        let updatedItem = { ...item, [mode]: updateData };

        if (mode === 'ReadAccess' && updateData === 'N') {
          updatedItem = {
            ...updatedItem,
            AddAccess: 'N',
            UpdateAccess: 'N',
            DeleteAccess: 'N',
          };
        }
        const isRowSelected = [
          'AddAccess',
          'UpdateAccess',
          'DeleteAccess',
          'ReadAccess',
        ].some((key) => updatedItem[key] === 'Y');

        if (isRowSelected) {
          if (!selectedRowKeys?.includes(e.MenuId)) {
            setSelectedRowKeys([...selectedRowKeys, e.MenuId]);
          }
        } else {
          setSelectedRowKeys(selectedRowKeys.filter((key) => key !== e.MenuId));
        }

        return updatedItem;
      }
      return item;
    });

    // update the state
    setTableData(updatedItemList);
  };

  const onSearch = (value) => {
    setSearchedText(value);
  };
  const onSearchChange = (e) => {
    setSearchedText(e?.target?.value);
  };

  return (
    <div className="pageOverAll EmpAccessForm-Master">
      <div className="userPage">
        <div className="userPageContent">
          <Messages messageType={messageType} messageData={messageData} />
          <div className="formName">
            <FormHeader title={'Employee Access'} />
          </div>

          <div className="formDiv">
            <Form
              ref={formRef}
              className="formDivAnt"
              onFinish={onFinish}
              initialValues={{ ...editstate }}
            >
              <div className="formDivS">
                <div className="inputForm EmpAccessinputForm">
                  <Form.Item
                    name="EmpId"
                    rules={[
                      {
                        required: true,
                        message: 'Please Select Employee',
                      },
                    ]}
                  >
                    <DropDowns
                      options={userDropDown?.map((option) => ({
                        value: option.UniqueId,
                        label:
                          option.EmpFirstName +
                          ' ' +
                          (option.EmpLastName ? option.EmpLastName : ''),
                      }))}
                      label={<label class="required">Employee Name</label>}
                      id="UserId"
                      field="UserId"
                      fieldState={true}
                      fieldApi={true}
                      className="field-DropDown-Emp"
                      onChangeFunction={(e) => UserDropDownChange(e)}
                      isOnchanges={formType == 'edit' ? true : false}
                      valueData={SelectedUserData}
                      disabled={formType == 'edit' ? true : false}
                    />
                  </Form.Item>
                  <div className="formSearch">
                    <Search
                      placeholder="Search"
                      onSearch={onSearch}
                      onSearchChange={onSearchChange}
                    />
                  </div>
                </div>
              </div>
            </Form>
            <div className="reportTable empAccessreportTable">
              <Tables
                columns={columns}
                data={SelectedUserData ? TableData : []}
                dataSource={TableData}
                rowSelection={rowSelection}
                // pagination={"No Need"}
              />{' '}
            </div>
          </div>
          <Form
            ref={formRef}
            className="formDivAnt"
            onFinish={onFinish}
            initialValues={{ ...editstate }}
            style={{ width: '100%' }}
          >
            <div className="submitButtonDiv">
              <Buttons
                buttonText="SUBMIT"
                color="901D77"
                icon={<ArrowRightOutlined />}
                // handleSubmit={handleSubmit}
              />
            </div>
          </Form>
        </div>
      </div>
    </div>
  );
};
export default EmpAccessForm;
