import { useEffect, useState, useCallback } from 'react';
import { useDispatch } from 'react-redux';
import FormHeader from '../PageComponents/FormHeader.jsx';
import { Search } from '../../Components/Forms/Search.jsx';
import { Tables } from '../../Components/Tables/Table.jsx';
import { Messages } from '../../Components/Notifications/Messages.jsx';
import moment from 'moment';
import { DeleteFilled } from '@ant-design/icons';
import { changeBreadCrumb } from '../../Features/AppPage/CenterPage.js';
import {
  getCancelPartialPayment,
  putCancelPartialPayment,
} from '../../Features/PendingPaymentCancel/PendingPaymentCancel.js';
import { ExtractDateFormate, extractLastNumberOrderId, getSession } from '../../Services/Others.js';
import { Space, Table } from 'antd';
import { DefaultModal } from '../../Components/Modal/DefaultModal.jsx';
import { IoEye } from 'react-icons/io5';
import '../../Styles/CancelReschedule/CancelPendingPayment.scss';
const subDirectory = import.meta.env.BASE_URL;
const CancellationPendingPaymentList = () => {
  const dispatch = useDispatch();
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');
  const UserId = getSession('UserId');
  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [searchedText, setSearchedText] = useState('');
  const [sortedInfo, setSortedInfo] = useState({});
  const [tabledata, settabledata] = useState([]);
  const [page, setpage] = useState(1);
  const [Open, setOpen] = useState({ productDtl: false, ordpaymtDtl: false });
  const [Details, setDetails] = useState({
    productDetails: [],
    OrderPaymentDtl: [],
  });
  const items = [
    {
      name: 'Home',
      link: `${subDirectory}app-page/home`,
    },
    {
      name: 'Cancel Unpaid Orders',
      link: `${subDirectory}setting/cancel-pendingpayment`,
    },
  ];

  const ViewProductsandPaymentDtls = async (row, val) => {
    console.log(row, 'rowrow');

    if (val == 'prod') {
      setOpen({ productDtl: true, ordpaymtDtl: false });
    } else {
      setOpen({ productDtl: false, ordpaymtDtl: true });
    }
    setDetails({
      productDetails: row?.productDetails,
      OrderPaymentDtl: row?.OrderPaymentDtl,
    });
  };
  const handleCancelNew = () => {
    setOpen({ productDtl: false, ordpaymtDtl: false });
  };
  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: 'ORDER ID',
      dataIndex: 'OrderId',
      key: 'OrderId',
      align: 'right',
      render: (text, record) => (
        <a style={{ color: 'black' }}>
          {record?.OrderId &&
            extractLastNumberOrderId(record?.OrderId, record?.FYStatus)}
        </a>
      ),
      filteredValue: [searchedText],
      onFilter: (value, record) => {
        return String(record.OrderId)
          ?.toLowerCase()
          ?.includes(value?.toLowerCase());
      },
      ellipsis: true,
    },
    {
      title: 'Customer Mobile ',
      dataIndex: 'CustSuppName',
      key: 'CustSuppName',
      //   width: "100px",
      align: 'center',
    },
    {
      title: 'Products',
      dataIndex: 'Products',
      key: 'Products',
      //   width: "100px",
      align: 'center',
      render: (text, record) => (
        <div>
          <IoEye
            style={{ color: '#1292EE', fontSize: '25px', cursor: 'pointer' }}
            onClick={() => ViewProductsandPaymentDtls(record, 'prod')}
          />
        </div>
      ),
    },

    {
      title: 'Payment Dtl',
      dataIndex: 'Payment Dtl',
      key: 'Payment Dtl',
      align: 'center',
      render: (text, record) => (
        <div>
          <IoEye
            style={{ color: '#1292EE', fontSize: '25px', cursor: 'pointer' }}
            onClick={() => ViewProductsandPaymentDtls(record, 'Payment')}
          />
        </div>
      ),
    },
    {
      title: 'DATE',
      dataIndex: 'EffectiveFrom',
      key: 'EffectiveFrom',

      render: (text) => (
        <a style={{ color: 'black' }}>{ExtractDateFormate(text)}</a>
      ),
    },

    {
      title: 'Action',
      key: 'Action',
      dataIndex: 'Action',
      align: 'center',
      render: (_, record, index) =>
        tabledata?.length >= 1 ? (
          <button
            style={{
              color: '#ffff',
              background: '#1292ee',
              padding: '3px 10px',
              border: '1px solid #1292ee',
              borderRadius: '4px',
              cursor: 'pointer',
            }}
            onClick={() => actionsFormatter(record)}
          >
            Cancel Transaction
          </button>
        ) : null,
    },
  ];
  const columns1 = [
    {
      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',
      align: 'left',
    },
    {
      title: 'QTY',
      dataIndex: 'SalesQty',
      key: 'SalesQty',
      align: 'center',
    },
    {
      title: 'MRP',
      dataIndex: 'MRP',
      key: 'ChargesFixed',
      width: 'MRP',
      align: 'right',
    },
  ];
  const columns2 = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',
      width: '100px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
      ),
    },

    {
      title: 'Payment Type',
      dataIndex: 'PaymentTypeName',
      key: 'PaymentTypeName',
      width: '100px',
      align: 'left',
    },
    {
      title: 'Amount',
      dataIndex: 'Amount',
      key: 'Amount',
      width: '100px',
      align: 'center',
    },
  ];
  useEffect(() => {
    dispatch(changeBreadCrumb({ items: items }));
    fetchCancellationPartialData();
  }, []);

  const fetchCancellationPartialData = async () => {
    if (!AppId || !CompId || !BranchId) {
      console.error(
        'Missing required identifiers: AppId, CompId, or BranchId.'
      );
      return;
    }

    const data = {
      AppId,
      CompId,
      BranchId,
    };

    try {
      const res = await dispatch(getCancelPartialPayment(data)).unwrap();
      if (res?.data?.statusCode === 1) {
        const fetchedData = res?.data?.data;

        settabledata(fetchedData);
      } else {
        settabledata([]);
      }
    } catch (error) {
      console.error(
        'Failed to fetch cancellation or rescheduling data:',
        error
      );
      settabledata([]);
    }
  };

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

  const actionsFormatter = async (record) => {
    const data = {
      OrderId: record?.OrderId,
      UpdatedBy: UserId,
    };
    let response = await dispatch(putCancelPartialPayment(data)).unwrap();
    if (response?.data?.statusCode == 1) {
      setMessageType('success');
      setMessageData(response?.data?.response);
      fetchCancellationPartialData();
    }
  };

  const onSearch = (value) => {
    setSearchedText(value);
  };
  const onSearchChange = (e) => {
    setSearchedText(e?.target?.value);
  };
  const handleChange = (pagination, filters, sorter) => {
    setSortedInfo(sorter);
  };
  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);

  return (
    <div className="userPageTable">
      <div className="userPageContent">
        <Messages
          messageType={messageType}
          messageData={messageData}
          onComplete={onComplete}
        />
        <div className="formAddNew">
          <div>
            <FormHeader title={'Cancel Unpaid Order'} />
          </div>
          <div className="searchAddDiv">
            <div className="formSearch">
              <Search
                placeholder="Search"
                onSearch={onSearch}
                onSearchChange={onSearchChange}
              />
            </div>
          </div>
        </div>
        <div className="reportTable">
          <Tables
            columns={columns}
            data={tabledata}
            dataSource={tabledata}
            pagination={handlePageChange}
            onChange={handleChange}
          />
        </div>
      </div>
      <DefaultModal
        open={Open?.productDtl}
        title="Product  Details"
        footer={false}
        width={900}
        children={
          <>
            <div>
              <div></div>

              {/* <div>
               
                               

                                    <Table
                                    //   rowSelection={{ ...rowSelection, selectedRowKeys }}
                                      columns={columns1}
                                      dataSource={Details?.productDetails}
                                      pagination={{
                                        onChange: handlePageChange,
                                        defaultPageSize: 10,
                                        showSizeChanger: false,
                                        hideOnSinglePage: true,
                                      }}
                                      onChange={handleChange}
                            />

                      </div>  */}

              <div className="reportTableCancelPendingPayment">
                <Tables
                  columns={columns1}
                  data={Details?.productDetails}
                  dataSource={Details?.productDetails}
                  pagination={handlePageChange}
                  onChange={handleChange}
                />{' '}
              </div>

              {/* <div>
                        Payment Details
                                

<Table
//   rowSelection={{ ...rowSelection, selectedRowKeys }}
  columns={columns2}
  dataSource={Details?.OrderPaymentDtl}
  pagination={{
    onChange: handlePageChange,
    defaultPageSize: 10,
    showSizeChanger: false,
    hideOnSinglePage: true,
  }}
  onChange={handleChange}
/>

</div>  */}
            </div>
          </>
        }
        // handleSubmit={handleSubmit}
        handleCancel={handleCancelNew}
      />

      <DefaultModal
        open={Open?.ordpaymtDtl}
        title="Payment Details"
        footer={false}
        width={900}
        children={
          <>
            <div>
              <div></div>

              {/* <div>
                                    <Table
                                      columns={columns2}
                                      dataSource={Details?.OrderPaymentDtl}
                                      pagination={{
                                        onChange: handlePageChange,
                                        defaultPageSize: 10,
                                        showSizeChanger: false,
                                        hideOnSinglePage: true,
                                      }}
                                      onChange={handleChange}
                            />

                      </div>  */}
              <div className="reportTableCancelPendingPayment">
                <Tables
                  columns={columns2}
                  data={Details?.OrderPaymentDtl}
                  dataSource={Details?.OrderPaymentDtl}
                  pagination={handlePageChange}
                  onChange={handleChange}
                />{' '}
              </div>
            </div>
          </>
        }
        handleCancel={handleCancelNew}
      />
    </div>
  );
};
export default CancellationPendingPaymentList;
