import { useCallback, useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import FormHeader from '../PageComponents/FormHeader';
import { Checkbox, Form, Space } from 'antd';
import Buttons from '../../Components/Forms/Buttons';
import { Messages } from '../../Components/Notifications/Messages';
import { RadioGrpButton } from '../../Components/Forms/RadioGroup.jsx';
import { ArrowRightOutlined } from '@ant-design/icons';
import { DropDowns } from '../../Components/Forms/DropDown';
import { getLayoutCategories } from '../../Features/BookingScreen/BookingData/BookingData';
import { getSession } from '../../Services/Others';
import {
  changeBreadCrumb,
  getEmpAccess,
} from '../../Features/AppPage/CenterPage.js';
import {
  getProdListBasedOnCat,
  putCancelAppProd,
} from '../../Features/CancelReschedule/CancelApplicableProd';
import '../../Styles/CancelReschedule/CancelApplicableProd.scss';
import { Tables } from '../../Components/Tables/Table.jsx';
import { useAuth } from '../../AuthContext.jsx';

const subDirectory = import.meta.env.BASE_URL;

const CancelApplicableProd = () => {
  const { SadminuserAccess } = useAuth();
  let SAAccessCommonMaster = SadminuserAccess?.find(
    (e) => e?.MenuName === 'Cancel Applicable Products'
  );

  const dispatch = useDispatch();
  const formRef = useRef();
  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 [selCancelProdType, setselCancelProdType] = useState('APY');
  const [AllCategory, setAllCategory] = useState([]);
  const [selProdCat, setselProdCat] = useState(null);
  const [SelCatProds, setSelCatProds] = useState([]);
  const [AllSelCatProds, setAllSelCatProds] = useState([]);
  const [SelectData, setSelectData] = useState([]);
  const [UnCheckedProd, setUnCheckedProd] = useState([]);
  const [AllCalAppProd, setAllCalAppProd] = useState([]);
  const [page, setpage] = useState(1);
  const [empData, setEmpData] = useState();
  const [addnewAccess, setaddnewAccess] = useState(true);

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

  useEffect(() => {
    getLayoutCategoriesdata();
    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 === 'Cancel Applicable Products'
    );
    setEmpData(datas?.[0]);
  };

  const selectCancelProdType = (e) => {
    setselCancelProdType(e);
  };
  const getLayoutCategoriesdata = async () => {
    let res = await dispatch(
      getLayoutCategories({ CompId: CompId, AppId: AppId, BranchId: BranchId })
    ).unwrap();
    if (res?.data?.statusCode === 1) {
      setAllCategory(res?.data?.data);
    }
  };
  const SelectProductCategory = async (e) => {
    formRef.current?.setFieldsValue({ ProdCat: e });
    setselProdCat(e);
    let data = {
      CompId: CompId,
      AppId: AppId,
      BranchId: BranchId,
      ProdCat: e,
      type: 'C',
    };
    let res = await dispatch(getProdListBasedOnCat(data)).unwrap();
    if (res?.data?.statusCode === 1) {
      setSelCatProds(res?.data?.data);
      setAllSelCatProds(res?.data?.data?.map((i) => i.ProdId));

      let allapiY = res?.data?.data
        ?.filter((item) => item.CancelAvailable === 'Y')
        ?.map((i) => i.ProdId);

      let notinUncheck = allapiY?.filter(
        (item) => !UnCheckedProd?.includes(item)
      );
      if (SelectData?.some((item) => notinUncheck?.includes(item))) {
        let notinSeldata = notinUncheck?.filter(
          (item) => !SelectData?.includes(item)
        );
        setSelectData([...SelectData, ...notinSeldata]);
      } else {
        setSelectData([...SelectData, ...notinUncheck]);
      }

      let TempAvalProd = res?.data?.data
        ?.filter((item) => item.CancelAvailable === 'Y')
        ?.map((i) => i.ProdId);
      if (AllCalAppProd?.some((item) => TempAvalProd?.includes(item))) {
        setAllCalAppProd([...AllCalAppProd]);
      } else {
        setAllCalAppProd([
          ...AllCalAppProd,
          ...res?.data?.data
            ?.filter((item) => item.CancelAvailable === 'Y')
            ?.map((i) => i.ProdId),
        ]);
      }
    } else {
      setSelCatProds([]);
    }
  };
  const addeddata = (record) => {
    if (SelectData?.includes(record.ProdId)) {
      setSelectData(SelectData?.filter((a) => a != record.ProdId));
      if (AllCalAppProd?.includes(record.ProdId)) {
        setUnCheckedProd([...UnCheckedProd, record.ProdId]);
      }
    } else {
      setSelectData([...SelectData, record.ProdId]);
      if (AllCalAppProd?.includes(record.ProdId)) {
        setUnCheckedProd(UnCheckedProd?.filter((b) => b != record.ProdId));
      }
    }
  };
  const selectAllProd = () => {
    if (AllSelCatProds.every((item) => SelectData.includes(item))) {
      let fillprod = SelectData?.filter(
        (item) => !AllSelCatProds.includes(item)
      );
      setSelectData([...fillprod]);
      let uncheckdata = AllCalAppProd?.filter(
        (item) => !fillprod?.includes(item)
      );
      setUnCheckedProd(uncheckdata);
    } else if (AllSelCatProds.some((item) => SelectData.includes(item))) {
      let fillprod = SelectData?.filter(
        (item) => !AllSelCatProds.includes(item)
      );
      setSelectData([...fillprod, ...AllSelCatProds]);
      let temseldata = [...fillprod, ...AllSelCatProds];
      let uncheckdata = AllCalAppProd?.filter(
        (item) => !temseldata?.includes(item)
      );
      setUnCheckedProd(uncheckdata);
    } else {
      setSelectData([...SelectData, ...AllSelCatProds]);
      let temseldata = [...SelectData, ...AllSelCatProds];
      let uncheckdata = AllCalAppProd?.filter(
        (item) => !temseldata?.includes(item)
      );
      setUnCheckedProd(uncheckdata);
    }
  };
  const columns = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',
      width: '100px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
      ),
    },
    {
      title: 'Product Name',
      dataIndex: 'ProdName',
      key: 'ProdName',
      width: '100px',
      render: (text, record) => (
        <a style={{ color: 'black' }}>
          {record.ProdName + '(' + record.Size + record.UOMName + ')'}
        </a>
      ),
    },
    {
      title: () => (
        <Checkbox
          checked={AllSelCatProds.every((item) => SelectData.includes(item))}
          onChange={selectAllProd}
        />
      ),
      key: 'Action',
      dataIndex: 'Action',
      width: '80px',
      render: (text, record) => (
        <Space size="middle">
          <Checkbox
            checked={SelectData?.includes(record.ProdId) ? true : false}
            onClick={() => addeddata(record)}
          />
        </Space>
      ),
    },
  ];

  const onFinish = async () => {
    const ProdAppDtl = SelectData?.map((item) => ({ ProdId: item }));
    const ProdNotAppDtl = UnCheckedProd?.map((item) => ({ ProdId: item }));
    let dataAPY = {
      CompId: CompId,
      AppId: AppId,
      BranchId: BranchId,
      ProductApplicableDetails: [],
      ProductNotApplicableDetails: [],
      AllProducts: 'Y',
      UpdatedBy: UserId,
    };
    let dataAPN = {
      CompId: CompId,
      AppId: AppId,
      BranchId: BranchId,
      ProductApplicableDetails: [],
      ProductNotApplicableDetails: [],
      AllProducts: 'N',
      UpdatedBy: UserId,
    };
    let dataPB = {
      CompId: CompId,
      AppId: AppId,
      BranchId: BranchId,
      ProductApplicableDetails: ProdAppDtl,
      ProductNotApplicableDetails: ProdNotAppDtl,
      AllProducts: 'P',
      UpdatedBy: UserId,
    };

    let res = await dispatch(
      putCancelAppProd(
        selCancelProdType === 'APY'
          ? dataAPY
          : selCancelProdType === 'APN'
            ? dataAPN
            : selCancelProdType === 'PB'
              ? dataPB
              : ''
      )
    ).unwrap();
    if (res?.data?.statusCode === 1) {
      setMessageType('success');
      setMessageData(res?.data?.response);
      setselCancelProdType('APY');
      setselProdCat(null);
      setSelCatProds([]);
      setAllSelCatProds([]);
      setSelectData([]);
      setUnCheckedProd([]);
      setAllCalAppProd([]);
      formRef.current?.resetFields();
    } else {
      setMessageType('error');
      setMessageData(res?.data?.response);
    }
  };
  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);

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

  return (
    <>
      <div className="pageOverAll">
        <div className="userPage">
          <div className="userPageContent">
            <Messages
              messageType={messageType}
              messageData={messageData}
              onComplete={onComplete}
            />

            <div className="formName">
              <FormHeader title={'Cancel Applicable Products'} />
            </div>
            <div className="formDivCan">
              <div className="CancellationProd-div">
                <Form ref={formRef} onFinish={onFinish}>
                  <div>
                    <Form.Item name="CancelProdType">
                      <li className="drp_btn_Emp">
                        <div className="Cancel-Form-radio">
                          <RadioGrpButton
                            content={[
                              { value: 'APY', label: 'Select All Products' },
                              { value: 'APN', label: 'Remove All Products' },
                              { value: 'PB', label: 'Product Based' },
                            ]}
                            fieldState={true}
                            defaultSelect={selCancelProdType}
                            onSelectFuntion={(e) => selectCancelProdType(e)}
                            onClickFunction={(e) => selectCancelProdType(e)}
                          />
                        </div>
                      </li>
                    </Form.Item>
                  </div>
                  {selCancelProdType === 'PB' && (
                    <>
                      <div>
                        <Form.Item
                          name="ProdCat"
                          rules={[
                            {
                              required: true,
                              pattern: /^(?!\s*$).+/,
                              message: 'Please Enter Category',
                            },
                          ]}
                        >
                          <DropDowns
                            options={AllCategory?.map((option) => ({
                              value: option.ProdCat,
                              label: option.ProdCatName,
                            }))}
                            label={
                              <label class="required">Product Category</label>
                            }
                            className="field-DropDown"
                            onChangeFunction={(e) => SelectProductCategory(e)}
                            valueData={selProdCat}
                            isOnChange={selProdCat !== null ? true : false}
                          />
                        </Form.Item>
                      </div>

                      {SelCatProds?.length > 0 && (
                        <div className="CancelProdTable">
                          <Tables
                            columns={columns}
                            data={SelCatProds}
                            dataSource={SelCatProds}
                            pagination={handlePageChange}
                          />
                        </div>
                      )}
                    </>
                  )}
                  <div className="CancelProd-submitButton">
                    <Buttons
                      buttonText="SUBMIT"
                      color="901D77"
                      icon={<ArrowRightOutlined />}
                      onClick={() => onFinish()}
                      disabled={addnewAccess}
                    />
                  </div>
                </Form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default CancelApplicableProd;
