import { useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { ArrowRightOutlined, UpOutlined } from '@ant-design/icons';
import {
  GlobalOrderCardDetails,
  GlobalEstimateBooking,
  getCurrentOrderid,
  GlobalCurrentOrderId,
  getMissedOrderids,
  changeCurrentOrderId,
} from '../../../../Features/BookingScreen/BookingData/BookingData';
import TooltipWrapper from '../../../../Components/Tooltip/Tooltip';
import dayjs from 'dayjs';

import { RiListSettingsLine } from 'react-icons/ri';
import { DefaultModal } from '../../../../Components/Modal/DefaultModal.jsx';
import Buttons from '../../../../Components/Forms/Buttons.jsx';
import FormHeader from '../../../PageComponents/FormHeader.jsx';
import { DatePicker, Form } from 'antd';
import { InputField } from '../../../../Components/Forms/InputField.jsx';
import { StoredSessionData } from '../../../../Features/ThemeChange/ThemeChange.js';
import moment from 'moment';
import { getSession } from '../../../../Services/Others.js';
import { useDateStore } from '../../../../Features/BookingScreen/BookingData/DateStore.js';
import '../../../../Styles/BookingScreen/Components/UtillComponents/CustomisedInvoiceChange.scss';
const CustomisedInvoiceChange = () => {
  const dispatch = useDispatch();
  const formRef = useRef(null);
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');

  const globalOrderId = useSelector(GlobalCurrentOrderId);
  const [OpenInvoiceModal, setOpenInvoiceModal] = useState(false);
  const [CurrentOrderid, setCurrentOrderid] = useState(null);
  const [BranchStartno,setBranchStartno] = useState(null)
  const { invoiceDate, setInvoiceDate } = useDateStore();
  const [MissedOrderIds, setMissedOrderIds] = useState([]);
  console.log(MissedOrderIds, 'MissedOrderIdsMissedOrderIds');

  const fetchdatas = async () => {
     let data = { compId: CompId, branchId: BranchId };
      let response = await dispatch(getCurrentOrderid(data)).unwrap();
     
          if (response?.data?.statusCode == 1) {
              console.log(response?.data?.data, 'response?.data?.data');
              if (CompId && BranchId && globalOrderId == null) {
                  // setMissedOrderIds(response?.data?.data)
                  setCurrentOrderid(response?.data?.data?.[0]?.StartNo);
                  setBranchStartno(response?.data?.data?.[0]?.BranchStartNo)
                  formRef.current?.setFieldsValue({
                    CurrentOrderid: response?.data?.data?.[0]?.StartNo,
                  });
                }else {
                setCurrentOrderid(globalOrderId);
                setBranchStartno(response?.data?.data?.[0]?.BranchStartNo)
                formRef.current?.setFieldsValue({ CurrentOrderid: globalOrderId });
              }
           }
           else{
              setCurrentOrderid(null);
                setBranchStartno(null)
                formRef.current?.setFieldsValue({ CurrentOrderid: null });
           } 

    if (CompId && BranchId && AppId) {
      let data = { compId: CompId, branchId: BranchId, appId: AppId };
      let response = await dispatch(getMissedOrderids(data)).unwrap();
      if (response?.data?.statusCode == 1) {
        setMissedOrderIds(response?.data?.data);
      }
    }
  };

  const ChangeInvoiceModal = () => {
    setOpenInvoiceModal(true);
    fetchdatas();
  };
  const InvoiceModalCancel = () => {
    setOpenInvoiceModal(false);
  };

  const onFinish = () => {
    console.log(CurrentOrderid, 'CurrentOrderidCurrentOrderid');
    dispatch(changeCurrentOrderId(CurrentOrderid));
    InvoiceModalCancel();
    //   const formattedDate = date ? date.format('DD-MMM-YYYY') : '';
    //     dispatch(changeCustomOrderDate(formattedDate));
  };
  const disablefutureDates = (current) => {
    return current && current > moment().startOf('day');
  };
  const handleDateChange = (date) => {
    const formattedDate = date ? date.format('DD-MMM-YYYY') : '';
    setInvoiceDate(formattedDate);
    // Handle the selected date here
    console.log('Selected Date:', formattedDate, date);
  };
  const getDatePickerValue = () => {
    return dayjs(invoiceDate);
  };
  const newinvoicenoset =(invoiceno) =>{
      setCurrentOrderid(invoiceno);
      formRef.current?.setFieldsValue({
                    CurrentOrderid: invoiceno,
                  });
  }
  return (
    <div className="BSBilling7-icon-flex">
      {/* <BiSolidOffer className='BSBillingNav-icon'/> */}
      <TooltipWrapper title={'Customised Bill No'}>
        <div className="missingNumCheckIcon">
          <div>
            <RiListSettingsLine onClick={() => ChangeInvoiceModal()} />
          </div>
        </div>
      </TooltipWrapper>
      {OpenInvoiceModal && (
        <div>
          <DefaultModal
            open={OpenInvoiceModal}
            width={800}
            footer={false}
            title={'Customised Invoice Number'}
            children={
              <div>
                {/* <div className="formName">
                  <FormHeader title={'Customised Invoice Number'} />
                </div> */}
                <Form
                  ref={formRef}
                  initialValues={{ CurrentOrderid: CurrentOrderid }}
                  className="formDivAnt"
                  onFinish={onFinish}
                >
                  <div>
                    <div className="missingInoutDiv">
                      <Form.Item
                        name="CurrentOrderid"
                        rules={[
                          {
                            required: true,
                            message: 'Please Enter Invoice Number',
                          },
                         
                          {
                            validator: async (_, value) => {
                              // Your existing text safety validation

                              // Convert to number and compare
                              const numericValue = Number(value);

                              if (numericValue < BranchStartno) {
                                return Promise.reject(
                                  `Invoice Number must be greater than ${BranchStartno}`
                                );
                              }

                              return Promise.resolve();
                            },
                          },
                        ]}
                      >
                        <InputField
                          type="number"
                          autoComplete="off"
                          maxLength={15}
                          value={CurrentOrderid}
                          label={<label class="required">Invoice Number</label>}
                          isOnChange={CurrentOrderid}
                          onChange={(e) => setCurrentOrderid(e?.target?.value)}
                        />
                      </Form.Item>
                      <div className='fromlabelDate'> 
                        <label>Bill Date</label>
                        <DatePicker
                          disabledDate={disablefutureDates}
                          format="DD-MMM-YYYY"
                          onChange={handleDateChange}
                          value={getDatePickerValue()}
                        />
                      </div>
                    </div>
                {MissedOrderIds?.length > 0 &&
                    <div>
                      <p className="missedinvocenum">Missed Invoice Numbers:</p>
                      <div className="Missedorderlist" >
                        {MissedOrderIds?.map((item) => (
                          <p onClick={()=>newinvoicenoset(item?.OrderNo)}>{item.OrderNo}</p>
                        ))}
                      </div>
                      <p></p>
                    </div>
                }
                    <div
                      className='CustomisedBTN'
                    >
                      <Buttons
                        buttonText="SUBMIT"
                        color="901D77"
                        icon={<ArrowRightOutlined />}
                        htmlType={true}
                      />
                    </div>
                  </div>
                </Form>
                <div></div>
              </div>
            }
            handleCancel={InvoiceModalCancel}
          />
        </div>
      )}
    </div>
  );
};
export default CustomisedInvoiceChange;
