import React, { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { Space } from 'antd';
import {
  EditFilled,
  DeleteFilled,
  PlusOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import { Messages } from '../../Components/Notifications/Messages';
import { Tables } from '../../Components/Tables/Table';
import { Search } from '../../Components/Forms/Search';
import {
  changeBreadCrumb,
  getEmpAccess,
} from '../../Features/AppPage/CenterPage.js';
import Buttons from '../../Components/Forms/Buttons';
import { getSession } from '../../Services/Others';
import {
  getDineinTableData,
  DeleteDineinTableData,
} from '../../Features/Dinein/Dinein';
import FormHeader from '../PageComponents/FormHeader.jsx';
import { useAuth } from '../../AuthContext.jsx';
import '../../Styles/OverAllStyle/OverAllStyle.scss';

const subDirectory = import.meta.env.ENV_BASE_URL;
const items = [
  {
    name: 'Home',
    link: `${subDirectory}app-page/home`,
  },

  {
    name: 'DineIn',
    link: `${subDirectory}setting/dinein-master`,
  },
];

const DiningList = () => {
  const { SadminuserAccess } = useAuth();
  let SAAccessCommonMaster = SadminuserAccess?.find(
    (e) => e?.MenuName === 'Dine In'
  );
  console.log(SadminuserAccess, 'SadminuserAccess', SAAccessCommonMaster);

  const [page, setpage] = useState(1);
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');
  const UserId = getSession('UserId');
  const UserType = getSession('UserType');

  const navigateTo = useNavigate();
  const dispatch = useDispatch();
  const [tabledata, setTabledata] = useState();
  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [filteredInfo, setFilteredInfo] = useState({});
  const [searchedText, setSearchedText] = useState('');
  const [sortedInfo, setSortedInfo] = useState({});
  const [empData, setEmpData] = useState();
  const [addnewAccess, setaddnewAccess] = useState(true);

  const handelAddButton = () => {
    navigateTo(`${subDirectory}setting/dinein-master/new`);
  };

  const handleChange = (pagination, filters, sorter) => {
    setFilteredInfo(filters);
    setSortedInfo(sorter);
  };

  const handlePageChange = (current) => {
    setpage(current);
  };

  useEffect(() => {
    TableData();
    dispatch(changeBreadCrumb({ items: items }));
    // if (UserType === "Employee") {
    //   fetchApi()
    // }
  }, []);

  useEffect(() => {
    if (UserType === 'Employee') {
      fetchApi();
    }
  }, [UserType]);

  useEffect(() => {
    let hasAccess = false;

    if (UserType === 'Admin' || UserType === 'Super Admin') {
      hasAccess = true;
    } else if (UserType === 'Employee') {
      hasAccess = empData?.AddAccess === 'Y';
    } else if (UserType === 'Super Admin User') {
      hasAccess = SAAccessCommonMaster?.AddAccess === 'Y';
    }

    setaddnewAccess(!hasAccess);
  }, [empData, SAAccessCommonMaster, UserType]);

  const fetchApi = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      EmpId: UserId,
    };
    let response = await dispatch(getEmpAccess(data)).unwrap();
    let datas = response?.data?.data?.[0]?.EmpAccessDetails?.filter(
      (item) => item.ConfigName === 'Dine In'
    );
    setEmpData(datas?.[0]);
  };

  const TableData = async () => {
    let response = await dispatch(
      getDineinTableData({ CompId: CompId, BranchId: BranchId, AppId: AppId })
    ).unwrap();
    if (response?.data?.statusCode == 1) {
      setTabledata(response?.data?.data);
    }
  };

  const actionsFormatter = async (row, rowIndex) => {
    if (row.ActiveStatus !== 'D') {
      navigateTo(
        `${subDirectory}setting/dinein-master/edit`,
        { state: { editstate: row } },
        { key: rowIndex }
      );
    }
  };

  const onSearch = (value) => {
    setSearchedText(value);
  };

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

  //Delete Funsction
  const statusFormatter = async (row) => {
    let deleteData = {
      TableId: row.TableId,
      ActiveStatus: row.ActiveStatus == 'A' ? 'D' : 'A',
      UpdatedBy: getSession('UserId'),
    };
    let response = await dispatch(DeleteDineinTableData(deleteData)).unwrap();
    if (response?.data?.statusCode == 1) {
      TableData();
      setMessageType('success');
      setMessageData(
        row.ActiveStatus == 'A'
          ? 'In-Activated Successfully'
          : 'Activated Successfully'
      );
    }
  };

  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);

  const columns = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',
      width: '80px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
      ),
    },
    {
      title: 'Table Name',
      dataIndex: 'TableName',
      key: 'TableName',
      width: '150px',
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
      filteredValue: [searchedText],
      onFilter: (value, record) => {
        return (
          String(record.TableName)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase()) ||
          String(record.TableName)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase()) ||
          String(record.ChairCount)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase()) ||
          String(record.ChairLevelSer)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase()) ||
          String(record.DineInTypeName)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase())
        );
      },
      sorter: (a, b) => a?.TableName?.length - b?.TableName?.length,
      sortOrder: sortedInfo.columnKey === 'TableName' ? sortedInfo.order : null,
      ellipsis: true,
    },
    {
      title: 'Chair Count',
      dataIndex: 'ChairCount',
      key: 'ChairCount',
      width: '100px',
      align: 'right',
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
      filteredValue: filteredInfo.ChairCount || null,
      onFilter: (value, record) => record.ChairCount?.includes(value),
      sorter: (a, b) => a?.ChairCount?.length - b?.ChairCount?.length,
      sortOrder:
        sortedInfo.columnKey === 'ChairCount' ? sortedInfo.order : null,
      ellipsis: true,
    },
    {
      title: 'DineIn Type',
      dataIndex: 'DineInTypeName',
      key: 'DineInTypeName',
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
      filteredValue: filteredInfo.CompName || null,
      onFilter: (value, record) => record.DineInTypeName?.includes(value),
      sorter: (a, b) => a?.DineInTypeName?.length - b?.DineInTypeName?.length,
      sortOrder:
        sortedInfo.columnKey === 'DineInTypeName' ? sortedInfo.order : null,
      ellipsis: true,
      align: "center"
    },
    {
      title: 'Chair Level Serve',
      dataIndex: 'ChairLevelSer',
      key: 'ChairLevelSer',
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
      filteredValue: filteredInfo.ChairLevelSer || null,
      onFilter: (value, record) => record.ChairLevelSer?.includes(value),
      sorter: (a, b) => a?.ChairLevelSer?.length - b?.ChairLevelSer?.length,
      sortOrder:
        sortedInfo.columnKey === 'ChairLevelSer' ? sortedInfo.order : null,
      ellipsis: true,
      align: "center", 
    },
    {
      title: 'Chair Name',
      dataIndex: 'ChairLevelSerDetails',
      key: 'ChairLevelSerDetails',
      width: '280px',
      render: (ChairLevelSerDetails) => (
        <a style={{ color: 'black' }}>
          {ChairLevelSerDetails?.length > 0
            ? ChairLevelSerDetails?.map((item) => item.ChairName).join(',')
            : ' - '}
        </a>
      ),
    },
    {
      title: 'Action',
      key: 'Action',
      width: '100px',
      dataIndex: 'Action',
      render: (_, record, index) =>
        tabledata.length >= 1 ? (
          <Space size="middle">
            {record.ActiveStatus === 'A' ? (
              <a>
                <EditFilled
                  style={{ color: '#1292EE' }}
                  onClick={() =>
                    UserType === 'Super Admin' ||
                    (UserType === 'Super Admin User' &&
                      SAAccessCommonMaster?.UpdateAccess === 'Y') ||
                    (UserType === 'Employee' &&
                      empData?.UpdateAccess === 'Y') ||
                    UserType === 'Admin'
                      ? actionsFormatter(record, index)
                      : null
                  }
                />
              </a>
            ) : (
              ''
            )}
            <a>
              {record.ActiveStatus === 'A' ? (
                <DeleteFilled
                  style={{
                    color: '#FF4D4F',
                  }}
                  onClick={() =>
                    UserType === 'Super Admin' ||
                    (UserType === 'Super Admin User' &&
                      SAAccessCommonMaster?.DeleteAccess === 'Y') ||
                    (UserType === 'Employee' &&
                      empData?.DeleteAccess === 'Y') ||
                    UserType === 'Admin'
                      ? statusFormatter(record)
                      : null
                  }
                />
              ) : (
                <ReloadOutlined
                  style={{
                    color: '#52C41A',
                  }}
                  onClick={() =>
                    UserType === 'Super Admin' ||
                    (UserType === 'Super Admin User' &&
                      SAAccessCommonMaster?.DeleteAccess === 'Y') ||
                    (UserType === 'Employee' &&
                      empData?.DeleteAccess === 'Y') ||
                    UserType === 'Admin'
                      ? statusFormatter(record)
                      : null
                  }
                />
              )}
            </a>
          </Space>
        ) : null,
    },
  ];

  return (
    <div className="userPageTable">
      <div className="userPageContent">
        <div className="formAddNew">
          <Messages
            messageType={messageType}
            messageData={messageData}
            onComplete={onComplete}
          />
          <div>
            <FormHeader title={'Dinein'} />
          </div>
          <div className="searchAddDiv">
            <div className="formSearch">
              <Search
                placeholder="Search"
                onSearch={onSearch}
                onSearchChange={onSearchChange}
              />
            </div>

            <Buttons
              buttonText={'Add New'}
              handleSubmit={() => handelAddButton()}
              disabled={addnewAccess}
              color="901D77"
              icon={<PlusOutlined />}
            >
              OPEN
            </Buttons>
          </div>
        </div>
        <div className="reportTable">
          <Tables
            columns={columns}
            data={tabledata}
            dataSource={tabledata}
            pagination={handlePageChange}
            onChange={handleChange}
          />
        </div>
      </div>
    </div>
  );
};
export default DiningList;
