import { useEffect, useState } from 'react';
import {  Form,Popover, Input, Button, AutoComplete, Tooltip } from 'antd';
import { useDispatch, useSelector } from "react-redux";
import { FaParking } from "react-icons/fa";
import { GlobalOrderCardDetails,  GlobalOtherServiceTicketClaim,  GlobalSummeryTotalAmount,  changeOtherServiceTicketClaim, getOtherServiceTicket } from "../../../../Features/BookingScreen/BookingData/BookingData";
import TooltipWrapper from '../../../../Components/Tooltip/Tooltip';
import { isMobile } from 'react-device-detect';
import FloatLabel from '../../../../Components/Forms/FloatLabel';
import { BsUpcScan } from 'react-icons/bs';
import { StoredSessionData } from '../../../../Features/ThemeChange/ThemeChange';
import { consolidateDuplicates } from './BSNavBarOffer/BSNavBarOffer_ReausableFunctions';
import { Messages } from '../../../../Components/Notifications/Messages';

const BSOtherServiceClaim = () => {

    const dispatch = useDispatch();
  const SessionData = useSelector(StoredSessionData);
  const OrderCardDetail = useSelector(GlobalOrderCardDetails);
  const OtherServiceTicketClaim = useSelector(GlobalOtherServiceTicketClaim);
  const BillAmount =useSelector(GlobalSummeryTotalAmount)
  console.log("OtherServiceTicketClaim", BillAmount,OtherServiceTicketClaim);
  const CompId = SessionData?.CompId;
  const BranchId = SessionData?.BranchId;
  const AppId = SessionData?.AppId;
  const UserId = SessionData?.UserId;
  const UserType = SessionData?.UserType;
    const [visible, setVisible] = useState(false);
    console.log("visible", visible);
    const [searchText, setSearchText] = useState(null);
    const [selectedOthersService, setSelectedOthersService] = useState('');
    const [selectedTicketId,setselectedTicketId]=useState(null)
    const [scanner, setScanner] = useState(false);
    const [messageType, setMessageType] = useState(null);
    const [messageData, setMessageData] = useState(null);
  const [error,seterror] = useState(null);
  const [Parkingdata, setParkingdata] = useState([]);
  const [totalParkingAmount, setTotalParkingAmount] = useState(0);
  console.log(totalParkingAmount,Parkingdata, 'Parkingdata')
  useEffect(() => {
    seterror(null);
  }, []);
    useEffect(() => {
      if (OtherServiceTicketClaim?.ParkingClaimed === false) {
              setParkingdata([]);
              setTotalParkingAmount(0);
              setSelectedOthersService('');
      }
    }
    , [OtherServiceTicketClaim]);
    const handleOk = (type) => {
            if (type === "Add") {
                if(totalParkingAmount > 0) {
                      if(BillAmount > totalParkingAmount){

                        dispatch(changeOtherServiceTicketClaim({
                              TicketId: selectedTicketId ,
                              TotalAmt: totalParkingAmount,
                              ParkingClaimed: true,
                              ServiceCategory: Parkingdata ? Parkingdata?.[0]?.ServiceCategory : '',
                            }));
                          }
                          else{
                            setMessageType("error");
                            setMessageData("Other Service Ticket Claim amount cannot be greater than total amount");
                             dispatch(changeOtherServiceTicketClaim({
                                      TotalAmt: 0,
                                      ParkingClaimed: false,
                                      TicketId: null,
                                      ServiceCategory: null,
                                    }));
                          }
                  }
                else{
                  dispatch(changeOtherServiceTicketClaim({
                    TotalAmt: 0,
                    ParkingClaimed: false,
                    TicketId: null,
                    ServiceCategory: null,
                  }));
                }
            }else{
              dispatch(changeOtherServiceTicketClaim({
                TotalAmt: 0,
                ParkingClaimed: false,
                OthersType: 'Remove',
                TicketId: null,
                ServiceCategory: null,
              }));
              setParkingdata([]);
              setTotalParkingAmount(0);
              setSelectedOthersService('');
            }
        setVisible(false);
        seterror(null)
    };

    const handleCancel = () => {
        setVisible(false);
        seterror(null)
    };
 
const handleScanSearch = () => {
    if (scanner === false) {
      setMessageType("success");
      setMessageData("Search by QrCode/BarCode Enabled")
    } else {
      setMessageType("success");
      setMessageData("Search by QrCode/BarCode Disabled")
    }
    setScanner(prev => !prev)
   
  }
const handleOtherServiceSearch = async (value) => {
    setSelectedOthersService(value);
    let data 
 if(value?.length >= 3){
 
    if (scanner) {
      data = {
          TicketId: `${value}`,
          AppId: AppId,
          CompId: CompId,
          BranchId: BranchId
    };
    
    } else {
       data = {
          TicketId: `${value}`,
          AppId: AppId,
          CompId: CompId,
          BranchId: BranchId
    };
  }
    if( value && value.length > 0) {
    let otherdata = await dispatch(getOtherServiceTicket(data)).unwrap();
    if (otherdata?.data?.statusCode === 1) {
        console.log(otherdata?.data?.data, 'otherdata');
          setselectedTicketId(otherdata?.data?.data?.[0]?.ServiceTicketId)
        let Parkingthere = otherdata?.data?.data?.[0]?.ServiceDetails?.filter((item) => item?.ServiceCategoryName === 'Parking');
    if (Parkingthere?.length > 0) {
      console.log(Parkingthere, 'Parkingthere');
       const totalParkingAmount = Parkingthere?.reduce((sum, item) => sum + (item.TotalAmt || 0), 0);
          setParkingdata(Parkingthere);
          setTotalParkingAmount(totalParkingAmount);
          seterror(null);
    }else{
        seterror("No Data Found");
         setParkingdata([]);
         setTotalParkingAmount(0);
    }
        
    }else{
      seterror("No Data Found");
        setParkingdata([]);
         setTotalParkingAmount(0);
    }
    }else{
      seterror(null);
      setParkingdata([]);
      setTotalParkingAmount(0);
    }
  }
  }
 
    const content = (
        <div style={{ width: 200 }}>
                <Form.Item
                        name="OtherServiceClaim"
                      >
                        <div className="product-scan" style={{ width: 200 }}>
                          <FloatLabel label={"Other Service No"} value={selectedOthersService}>
                            <AutoComplete
                              className="field-DropDown"
                              value={selectedOthersService}
                              onChange={handleOtherServiceSearch}
                              onKeyDown={(e) => {
                                if (scanner && e.key === "Enter") {
                                  e.preventDefault();
                                }
                              }}
                             onKeyPress={(e) => {
    // Allow only numeric input and max 4 digits
    if (!/[0-9]/.test(e.key)) {
      e.preventDefault();
      seterror("Please enter only numeric value");
    } else if (selectedOthersService?.length >= 4) {
      e.preventDefault();
      seterror("Only 4 digits allowed");
    } else {
      seterror(null);
    }
  }}
                              disabled={OtherServiceTicketClaim?.ParkingClaimed === true? true : false}
                            >
                            </AutoComplete>
                          </FloatLabel>
                          <Tooltip title={"BarCode/QrCode"} placement={"top"}>
                            <BsUpcScan strokeWidth={0.5} color="#000" style={{ fontSize: "16px", color: scanner ? "#52c41a" : "#888", fontWeight: "600" }} className="product-scan-Icon" onClick={handleScanSearch} />
                          </Tooltip>
                        </div>
                     
                      </Form.Item>
                      <div>{Parkingdata && <><span style={{ color: 'rgb(18, 146, 238)' }}>{Parkingdata?.[0]?.ServiceCategoryName}</span>
                    <div>
                      { Parkingdata.length > 0 && (
                        <>
                          {Parkingdata.map((item, idx) => (
                            <div key={item.ServiceId} style={{ color: 'green' }}>
                            <table>
                            <tbody>
                              <tr><td><div><div>{item.ServiceName}</div>{item.VehicleNumber ? (<div>VehicleNumber:{item.VehicleNumber}</div>) :""}</div></td>: ₹{item.TotalAmt}</tr>
                              </tbody>
                              </table>
                            </div>
                          ))}
                          <div style={{ fontWeight: 'bold', marginTop: 4 }}>
                            Total Amount: ₹{totalParkingAmount}
                          </div>
                        </>
                      )}
                    </div></>
                      
                      }
                      </div>
                   
                        <div>{error && <span style={{ color: 'red' }}>{error}</span>}</div>
                  
            <div style={{ marginTop: 10, display: 'flex', justifyContent: 'space-between' }}>
            {OtherServiceTicketClaim?.ParkingClaimed == false ? (
                
                <Button type="primary" onClick={()=>handleOk("Add")}>
                    OK
                </Button>
            ) : (
                <Button type="primary" onClick={() => handleOk("Remove")}>
                    Remove
                </Button>
            )}
                <Button onClick={handleCancel}>Cancel</Button>
            </div>
        </div>
    );

    return (<>
          <Messages messageType={messageType} messageData={messageData} />
    
        <TooltipWrapper title="Other Service Claim" isMobile={isMobile}>
         <Popover
          content={content}
          title="Other Service Claim"
          trigger="click"
          visible={visible}
          onVisibleChange={(visible) => setVisible(visible)}
      >
          <FaParking
              fill={OrderCardDetail?.length > 0 ? "rgb(18, 146, 238)" : "#888 "}
              style={{ fontSize: 24, cursor: 'pointer' }}
              onClick={() => {
                 
                      setVisible(!visible);
                  
              }}
        />
      </Popover>
        </TooltipWrapper>
    </>);
};

export default BSOtherServiceClaim;
