import { useState, useEffect, useCallback, useMemo } 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 {
  getCustBasedOnCmpIdBrIdAppId,
  delCust,
} from '../../Features/CustMaster/CustMaster.js';
import { getSession } from '../../Services/Others.js';
import { Messages } from '../../Components/Notifications/Messages';
import { useAuth } from '../../AuthContext.jsx';
// import { getPreferenceData } from '../../Features/BookingScreen/BookingData/BookingData.js';
import {
  deleteOtherServices,
  GetOtherServices,
} from '../../Features/OtherServices/OtherServices.js';

const subDirectory = import.meta.env.BASE_URL;

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

  {
    name: 'Other Services',
    link: `${subDirectory}setting/other-services`,
  },
];

const OtherServicesList = () => {
  const { SadminuserAccess } = useAuth();

  console.log(SadminuserAccess, 'SadminuserAccess');

  let SAAccessCommonMaster = SadminuserAccess?.find(
    (e) => e?.MenuName === 'Other Services'
  );
  const navigate = useNavigate();
  const location = useLocation();
  const dispatch = useDispatch();

  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');
  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);

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

    // if (BranchId) {
    //   const gettingTableData = await dispatch(
    //     getCustBasedOnCmpIdBrIdAppId({ CompId, BranchId, AppId })
    //   ).unwrap();
    //   if (gettingTableData?.data?.statusCode === 1) {
    //     // setTableData(gettingTableData?.data?.data);
    //   }
    // }
  }

  useEffect(() => {
    try {
      fetchData();
      getOtherservice();
    } catch (err) {
      console.log(err, 'err');
    }
    // if (UserType === "Employee") {
    //   fetchApi()
    // }
  }, []);

  const getOtherservice = async () => {
    let data = {
      AppId: AppId,
      CompId: CompId,
      BranchId: BranchId,
    };
    let response = await dispatch(GetOtherServices(data)).unwrap();
    if (response?.data?.statusCode === 1) {
      setTableData(response?.data?.data);
    } else {
      setTableData([]);
    }
  };

  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 === 'Other Services'
    );
    setEmpData(datas?.[0]);
  };

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

  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/other-services/update`,
        { state: { editstate: row } },
        { key: rowIndex }
      );
    }
  };
  // const getPreference = async () => {
  //   const data = { AppId: AppId, CompId: CompId, BranchId: BranchId };
  //   const { data: res } = await dispatch(getPreferenceData(data)).unwrap()
  //   const decimalSetting = res?.data?.[0]?.SettingDtlDetails?.find((setting) => setting?.SettingIdName?.toLowerCase() === "decimal" && setting?.SettingValue === 'Y');
  //   if (decimalSetting) {
  //     setAllowDecimal(true)
  //   }
  // }

  //Delete
  const statusFormatter = async (row) => {
    // if (row?.creditBal > 0 && row.ActiveStatus == 'A') {
    //   // setMessageType("warning");
    //   // setMessageData("Customer Has a Credit Balance");
    //   // seCostomerDeActivate(true);
    //   // serowData(row);
    // } else {
    let deleteData = {
      serviceId: row.ServiceId,
      activeStatus: row.ActiveStatus == 'A' ? 'D' : 'A',
      updatedBy: UserId,
    };
    let response = await dispatch(deleteOtherServices(deleteData)).unwrap();
    if (response?.data?.statusCode == 1) {
      fetchData();
      getOtherservice();
      setMessageType('success');
      setMessageData(
        row.ActiveStatus == 'A'
          ? 'In-Activated Successfully'
          : 'Activated Successfully'
      );
    }
    // }
  };

  // const statusFormatter = async (row) => {

  //   let deleteData = {
  //     CustId: row.CustId,
  //     ActiveStatus: row.ActiveStatus == "A" ? "D" : "A",
  //     UpdatedBy: UserId,
  //   };
  //   let response = await dispatch(delCust(deleteData)).unwrap();
  //   if (response?.data?.statusCode == 1) {
  //     fetchData();
  //     setMessageType("success");
  //     setMessageData(
  //       row.ActiveStatus == "A"
  //         ? "In-Activated Successfully"
  //         : "Activated Successfully"
  //     );
  //   }
  // };

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

  // {
  //   "UniqueId": 2,
  //   "ConfigTypeId": 78,
  //   "ServiceId": "OS1-77-127-1791-2",
  //   "ServiceCategory": 3264,
  //   "ConfigTypeIdName": "Other Services",
  //   "ServiceCategoryName": null,
  //   "ServiceName": "rt",
  //   "ServiceShortName": "rt",
  //   "CompId": 77,
  //   "BranchId": 127,
  //   "AppId": 1,
  //   "TaxId": "T1-77-49",
  //   "TaxName": "CGST,SGST",
  //   "TaxAmt": null,
  //   "Rate": 33.01,
  //   "TotalAmt": 34,
  //   "ActiveStatus": "A",
  //   "CreatedBy": 1791,
  //   "CreatedDate": "2025-07-03T16:24:14.91"
  // },
  const columns = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',
      width: '60px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
      ),
    },

    {
      title: 'Service Category',
      dataIndex: 'ServiceCategoryName',
      key: 'ServiceCategoryName',
      width: '100px',
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
      filteredValue: [searchedText],
      onFilter: (value, record) => {
        return (
          String(record.ServiceCategoryName)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase()) ||
          String(record.ServiceName)?.toLowerCase()?.includes(value?.toLowerCase())
        );
      },
    },

    {
      title: 'Service Name',
      key: 'ServiceName',
      align: 'left',
      dataIndex: 'ServiceName',
      width: '100px',
      render: (text, row) => {
        return <a style={{ color: 'black' }}>{text}</a>;
      },
    },
    {
      title: 'Tax',
      key: 'TaxName',
      align: 'center',
      dataIndex: 'TaxName',
      width: '100px',
      render: (text, row) => {
        return <a style={{ color: 'black' }}>{text}</a>;
      },
    },
    {
      title: 'Total Amount',
      key: 'TotalAmt',
        align: 'right',
      dataIndex: 'TotalAmt',
      width: '100px',
      render: (text, row) => {
        return <a style={{ color: 'black' }}>{text}</a>;
      },
    },
    {
      title: 'Action',
      key: 'Action',
      dataIndex: 'Action',
      width: '100px',
      align: 'center',
      render: (_, record, index) =>
        TableData.length >= 1 ? (
          <Space size="middle">
            {record.ActiveStatus === 'A' ? (
              <a>
                <EditFilled
                  style={{ color: '#1292EE' }}
                  onClick={() => actionsFormatter(record, index)}
                />
              </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 onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);

  const handelAddButton = () => {
    navigate(`${subDirectory}setting/other-services/new`);
  };

  return (
    <div className="userPageTable">
      <div className="userPageContent">
        <Messages
          messageType={messageType}
          messageData={messageData}
          onComplete={onComplete}
        />
        <div className="formAddNew">
          <div>
            <FormHeader title={'Other Services'} />
          </div>
          <div className="searchAddDiv">
            <div className="formSearch">
              <Search
                placeholder="Search"
                onSearch={onSearch}
                onSearchChange={onSearchChange}
              />
            </div>
            <Buttons
              buttonText={'Add New'}
              disabled={addnewAccess}
              handleSubmit={() => handelAddButton()}
              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 OtherServicesList;
