import { useState, useEffect, useCallback } from 'react';
import { useDispatch } from 'react-redux';
import { Space } from 'antd';
import {
  EditFilled,
  DeleteFilled,
  PlusOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import {
  changeBreadCrumb,
  getEmpAccess,
} from '../../Features/AppPage/CenterPage.js';
import { Tables } from '../../Components/Tables/Table';
import FormHeader from '../PageComponents/FormHeader.jsx';
import { useNavigate, useLocation } from 'react-router-dom';
import Search from '../../Components/Forms/Search.jsx';
import Buttons from '../../Components/Forms/Buttons';
import {
  getEmpBasedOnCmpId,
  getEmpBasedOnCmpIdBrId,
  delEmp,
  EmpDesgDropDown,
} from '../../Features/EmpMaster/EmpMaster.js';
import { getSession } from '../../Services/Others';
import { Messages } from '../../Components/Notifications/Messages';
import '../../Styles/Employee/EmpMaster.scss';
import { useAuth } from '../../AuthContext.jsx';
import { getshift } from '../../Features/ShiftMaster/ShiftMaster.js';
const subDirectory = import.meta.env.BASE_URL;

const items = [
  {
    name: 'Home',
    link: `${subDirectory}app-page/home`,
  },

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

const EmployeeMaster = () => {
  const { SadminuserAccess } = useAuth();
  let SAAccessCommonMaster = SadminuserAccess?.find(
    (e) => e?.MenuName === 'Add Employee'
  );

  const navigate = useNavigate();
  const location = useLocation();
  const dispatch = useDispatch();

  const AppId = getSession('AppId');
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const UserId = getSession('UserId');
  const UserType = getSession('UserType');

  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [TableData, setTableData] = useState([]);
  const [filteredInfo, setFilteredInfo] = useState({});
  const [sortedInfo, setSortedInfo] = useState({});
  const [searchedText, setSearchedText] = useState('');
  const [page, setpage] = useState(1);
  const [empData, setEmpData] = useState();
  const [addnewAccess, setaddnewAccess] = useState(true);
  const [ShiftData, setShiftData] = useState([]);
  const [DesingnData, setDesingnData] = useState([]);

  async function fetchData() {
    if (location?.state?.Notiffy) {
      setMessageType(location?.state?.Notiffy.messageType);
      setMessageData(location?.state?.Notiffy.messageData);
    }

    if (BranchId) {
      const gettingTableData = await dispatch(
        getEmpBasedOnCmpIdBrId({ cmpId: CompId, BranchId: BranchId })
      ).unwrap();
      if (gettingTableData?.data?.statusCode === 1) {
        setTableData(gettingTableData?.data?.data);
      }
    } else {
      const gettingTableData = await dispatch(
        getEmpBasedOnCmpId(CompId)
      ).unwrap();
      if (gettingTableData?.data?.statusCode === 1) {
        setTableData(gettingTableData?.data?.data);
      }
    }
    const gettingTableData = await dispatch(getshift(CompId)).unwrap();
    if (gettingTableData?.data?.statusCode === 1) {
      const activeEmployees = gettingTableData?.data?.data?.filter(
        (emp) => emp.ActiveStatus === 'A'
      );

      setShiftData(activeEmployees);
    }
    const gettingEmpDesgDropDown = await dispatch(
      EmpDesgDropDown({ AppId: AppId })
    ).unwrap();
    if (gettingEmpDesgDropDown?.data?.statusCode === 1) {
      setDesingnData(gettingEmpDesgDropDown?.data?.data);
    }
  }

  useEffect(() => {
    try {
      fetchData();
    } catch (err) {
      console.log(err, 'err');
    }

    // 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 response = await dispatch(
      getEmpAccess({
        CompId: CompId,
        BranchId: BranchId,
        AppId: AppId,
        EmpId: UserId,
      })
    ).unwrap();
    let datas = response?.data?.data?.[0]?.EmpAccessDetails?.filter(
      (item) => item.ConfigName === 'Add Employee'
    );
    setEmpData(datas?.[0]);
  };

  useEffect(() => {
    dispatch(changeBreadCrumb({ items: items }));
  }, []);

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

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

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

  //Delete
  const statusFormatter = async (row) => {
    let deleteData = {
      UniqueId: row.UniqueId,
      ActiveStatus: row.ActiveStatus == 'A' ? 'D' : 'A',
      UpdatedBy: UserId,
    };
    let response = await dispatch(delEmp(deleteData)).unwrap();
    if (response?.data?.statusCode == 1) {
      fetchData();
      setMessageType('success');
      setMessageData(
        row.ActiveStatus == 'A'
          ? 'In-Activated Successfully'
          : 'Activated Successfully'
      );
    } else if (response?.data?.statusCode === 2) {
      if (row.ActiveStatus === 'D') {
        setMessageType('error');
        setMessageData(response?.data?.response);
      }
    }
  };

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

  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: 'Employee Name',
      dataIndex: 'EmpFirstName',
      key: 'EmpFirstName',
      width: '180px',
      render: (text, row) => (
        <a style={{ color: 'black', width: '200px' }}>
          {row.EmpFirstName} {row.EmpLastName}
        </a>
      ),
      filteredValue: [searchedText],
      onFilter: (value, record) => {
        return (
          String(record.EmpFirstName)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase()) ||
          String(record.CompName)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase()) ||
          String(record.BrName)?.toLowerCase()?.includes(value?.toLowerCase())
        );
      },
      sorter: (a, b) => a?.EmpFirstName?.length - b?.EmpFirstName?.length,
      sortOrder:
        sortedInfo.columnKey === 'EmpFirstName' ? sortedInfo.order : null,
      ellipsis: true,
    },
    {
      title: 'Company Name',
      dataIndex: 'CompName',
      key: 'CompName',
      width: '200px',
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
      filteredValue: filteredInfo.CompName || null,
      onFilter: (value, record) => record.CompName?.includes(value),
      sorter: (a, b) => a?.CompName?.length - b?.CompName?.length,
      sortOrder: sortedInfo.columnKey === 'CompName' ? sortedInfo.order : null,
      ellipsis: true,
    },
    {
      title: 'Branch Name',
      dataIndex: 'BrName',
      key: 'BrName',
      width: '180px',
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
      filteredValue: filteredInfo.BrName || null,
      onFilter: (value, record) => record.BrName?.includes(value),
      sorter: (a, b) => a?.BrName?.length - b?.BrName?.length,
      sortOrder: sortedInfo.columnKey === 'BrName' ? sortedInfo.order : null,
      ellipsis: true,
    },

    {
      title: 'Designation',
      dataIndex: 'EmpDesignationName',
      key: 'EmpDesignationName',
      width: '150px',
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
      filteredValue: filteredInfo.EmpDesignationName || null,
      onFilter: (value, record) => record.EmpDesignationName?.includes(value),
      sorter: (a, b) =>
        a?.EmpDesignationName?.length - b?.EmpDesignationName?.length,
      sortOrder:
        sortedInfo.columnKey === 'EmpDesignationName' ? sortedInfo.order : null,
      ellipsis: true,
    },

    {
      title: 'Action',
      key: 'Action',
      dataIndex: 'Action',
      width: '180px',
      render: (_, record, index) =>
        TableData.length >= 1 ? (
          <Space size="middle">
            {/* edit cmd */}
            {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,
    },
  ];
  const data = TableData;

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

  const handelAddButton = () => {
    if (DesingnData.length > 0) {
      if (ShiftData.length > 0) {
        navigate(`${subDirectory}setting/employee-master/new`);
      } else {
        setMessageData('Please Add Shift Details');
        setMessageType('warning');
        setTimeout(() => {
          navigate(`${subDirectory}setting/shift-master`);
        }, 1000);
      }
    } else {
      setMessageData('Please Add Designation Details');
      setMessageType('warning');
      // navigate(`${subDirectory}setting/shift-master`);
    }
  };

  return (
    <div className="userPageTable">
      <div className="userPageContent">
        <Messages
          messageType={messageType}
          messageData={messageData}
          onComplete={onComplete}
        />
        <div className="formAddNew">
          <div>
            <FormHeader title={'Employee'} />
          </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 EmployeeMaster;
