import { useState, useEffect, useRef, useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
  getSession,
  dateTimeFormatChange,
  validateSafeInput,
} from '../../../Services/Others';
import { Tables } from '../../../Components/Tables/Table';
import { Form } from 'antd';
import { InputField } from '../../../Components/Forms/InputField.jsx';
import Buttons from '../../../Components/Forms/Buttons.jsx';
import { DropDowns } from '../../../Components/Forms/DropDown.jsx';
import { getWholeSalePayments } from '../../../Features/WSTransaction/WSTransaction.js';
import { Messages } from '../../../Components/Notifications/Messages.jsx';
import { DatePicProd } from '../../../Components/Forms/DatePickerProduct.jsx';
import moment from 'moment';
import { GlobalLastEntryDateDtl } from '../../../Features/WholeSale/WholesaleData.js';
import { useAuth } from '../../../AuthContext.jsx';
import {
  changeBreadCrumb,
  getEmpAccess,
} from '../../../Features/AppPage/CenterPage.js';
import '../../../Styles/Payment/PaymentReceivedRetail/PaymentReceivedRetail.scss';
import FormHeader from '../../PageComponents/FormHeader.jsx';
import {
  getEmployeeList,
  getRetailTranList,
  PostPaymentReceivedData,
} from '../../../Features/Payment/PaymentReceivedRetail/PaymentReceivedRetail.js';
import { ArrowRightOutlined } from '@ant-design/icons';
import { getPreferenceData } from '../../../Features/BookingScreen/BookingData/BookingData.js';
const subDirectory = import.meta.env.BASE_URL;
const PaymentReceivedRetail = () => {
  const { SadminuserAccess } = useAuth();
  let SAAccessCommonMaster = SadminuserAccess?.find(
    (e) => e?.MenuName === 'Payment Received'
  );
  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 WSLastEntryDate = useSelector(GlobalLastEntryDateDtl);

  const [page, setpage] = useState(1);
  const [SelectedCustomer, setSelectedCustomer] = useState();
  const [SelectedCustomerRole, setSelectedCustomerRole] = useState();
  const [customer, setCustomer] = useState();
  const [CustPaymentModes, setPaymentModesCust] = useState([]);
  const [AjustDate, setAjustDate] = useState();
  const [EmployeePaymentModes, setPaymentModesEmployee] = useState([]);
  const [CustTableData, setCustTableData] = useState([]);
  const [selectedPaymentMode, setSelectedPaymentMode] = useState('');
  const [PaidListData, SetPaidListData] = useState([]);
  const [ButtonDisabled, setButtonDisabled] = useState(false);
  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [PaymentType, setPaymentType] = useState('M');
  const [FilterData, setFilterData] = useState([]);
  const [empData, setEmpData] = useState();
  const [addnewAccess, setaddnewAccess] = useState(true);
  const [allowDecimal, setAllowDecimal] = useState(false);

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

    {
      name: 'Payment Updates',
      link: `${subDirectory}setting/payment-received-retail`,
    },
  ];

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

  useEffect(() => {
    const PaymentCredit =
      CustPaymentModes?.find((a) => a?.ConfigId === selectedPaymentMode)
        ?.ConfigName === 'Credit';
    if (PaymentCredit) {
      const SelectCustData = customer?.find(
        (a) => a?.CustSuppId === SelectedCustomer
      );
      formRef?.current?.setFieldsValue({
        Payment: SelectCustData?.NetAmount || 0,
      });
    }
  }, [selectedPaymentMode]);
  useEffect(() => {
    // Get the current date in "DD-MM-YYYY" format
    const currentDate = moment().format('DD-MM-YYYY');

    // Call DateChange function with the current date
    DateChange(null, currentDate);
  }, [PaymentType]);
  useEffect(() => {
    if (PaidListData?.length > 0) {
      if (PaymentType === 'M') {
        let filterData = PaidListData?.filter(
          (item) =>
            item.UserRole !== 'Customer' &&
            item?.OBType !== 'Y' &&
            item?.BalanceType !== 'A' &&
            (SelectedCustomer == null ||
              SelectedCustomer == 0 ||
              item?.UserId == SelectedCustomer)
        );
        setFilterData(filterData);
      } else if (PaymentType === 'C') {
        let filterData = PaidListData?.filter(
          (item) =>
            item.UserRole === 'Customer' &&
            item?.OBType !== 'Y' &&
            (SelectedCustomer == null ||
              SelectedCustomer == 0 ||
              item?.UserId == SelectedCustomer)
        );
        setFilterData(filterData);
      } else if (PaymentType === 'O') {
        let filterData = PaidListData?.filter(
          (item) =>
            item?.OBType === 'Y' &&
            item?.BalanceType === 'OB' &&
            (SelectedCustomer == null ||
              SelectedCustomer == 0 ||
              item?.UserId == SelectedCustomer)
        );
        setFilterData(filterData);
      } else if (PaymentType == 'A') {
        let filterData = PaidListData?.filter(
          (item) =>
            item?.BalanceType === 'A' &&
            (SelectedCustomer == null ||
              SelectedCustomer == 0 ||
              item?.UserId == SelectedCustomer)
        );
        setFilterData(filterData);
      }
    }
  }, [PaymentType, PaidListData, SelectedCustomer]);

  const columns = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',
      width: '80px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
      ),
    },
    // {
    //   title: 'No',
    //   key: 'UniqueId',
    //   dataIndex: 'UniqueId',
    //   align: 'center',
    //   width: '80px',
    //   render: (text, object, index) => <a style={{ color: 'black' }}>{text}</a>,
    // },
    {
      title: 'Name',
      key: 'EmpFirstName',
      dataIndex: 'EmpFirstName',
      render: (productDetails, record) => (
        <a style={{ color: 'black' }}>
          {PaymentType === 'M'
            ? record?.UserRole === 'Admin'
              ? `${record?.UserShortName || record?.UserName} (Admin)`
              : record?.EmpFirstName !== ''
                ? record?.EmpFirstName
                : `${record?.UserShortName || record?.UserName} (Employee)`
            : record?.UserShortName
              ? record?.UserShortName
              : record?.UserName}
        </a>
      ),
    },
    {
      title: 'Date',
      key: 'Date',
      dataIndex: 'Date',
      render: (productDetails, record) => (
        <a style={{ color: 'black' }}>{dateTimeFormatChange(record?.Date)}</a>
      ),
    },

    {
      title: 'Payment Type',
      key: 'PaymentTypeName',
      dataIndex: 'PaymentTypeName',
      render: (productDetails, record) => (
        <a style={{ color: 'black' }}>{record?.PaymentTypeName}</a>
      ),
    },

    {
      title: 'Amount',
      key: 'Amount',
      dataIndex: 'Amount',
      align: 'right',
      render: (productDetails, record) => (
        <a
          style={{
            color: record?.Amount < 0 ? 'red' : 'green',
          }}
        >
          {safeRound(record?.Amount)}
        </a>
      ),
    },
  ];

  const onChangeOption = async (e) => {
    setButtonDisabled(false);
    setPaymentType(e);
    formRef?.current?.setFieldsValue({ Customer: null });
    setSelectedCustomer(null);
    setSelectedCustomerRole(null);
  };

  const ChangeCustomer = (e, role) => {
    formRef?.current?.setFieldsValue({ Customer: e });
    setSelectedCustomer(e);
    setSelectedCustomerRole(role);
  };

  const paymentDtlfun = async () => {
    let res = await dispatch(
      getWholeSalePayments({ TypeName: 'Wholesale Payment Mode' })
    ).unwrap();
    if (res?.data?.statusCode === 1) {
      let cashMode = res?.data?.data?.filter(
        (item) => item.ConfigName !== 'Card'
      );
      let cashEmployee = res?.data?.data?.filter(
        (item) => item.ConfigName !== 'Card' && item?.ConfigName !== 'Credit'
      );
      setPaymentModesCust(cashMode);
      setPaymentModesEmployee(cashEmployee);
    }
  };

  useEffect(() => {
    paymentDtlfun();
    TranCompltList();
    getPreference();
    // 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 === 'Payment Received'
    );

    setEmpData(datas?.[0]);
  };
  useEffect(() => {
    fetchWholeSaleEmployee();
  }, [EmployeePaymentModes]);
  const fetchWholeSaleEmployee = async () => {
    const Data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
    };
    const gettingTableData = await dispatch(getEmployeeList(Data)).unwrap();
    if (gettingTableData?.data?.statusCode === 1) {
      setCustomer(gettingTableData?.data?.data);
      let EmpDefaultValue = EmployeePaymentModes?.[0];
      setSelectedPaymentMode(EmpDefaultValue?.ConfigId);
    } else {
      setCustomer([]);
      setSelectedPaymentMode('');
    }
  };
  const getPreference = async () => {
    const data = {
      AppId: AppId,
      CompId: CompId,
      BranchId: BranchId,
      UserId: UserId,
    };
    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);
    }
  };
  const onFinish = async (values) => {
    setButtonDisabled(true);
    const postData = {
      AppId: AppId,
      CompId: CompId,
      BranchId: BranchId,
      UserId: values?.Customer,
      Date: AjustDate,
      ReceivedAmount: values?.Payment,
      PaymentStatus: 'S',
      UserRole: customer?.find((item) => item.UserId === SelectedCustomer)
        ?.RoleName,
      BalanceType: 'A',
      Amount: values?.Payment,
      PaymentType: selectedPaymentMode,
      CreatedBy: UserId,
    };

    console.log(postData, 'postDatapostData');
    const res = await dispatch(PostPaymentReceivedData(postData)).unwrap();
    if (res?.data?.statusCode === 1) {
      setMessageType('success');
      setMessageData('Amount Added Successfully');

      await fetchWholeSaleEmployee();

      await TranCompltList();
      await Clearfun();
    } else {
      setMessageType('error');
      setMessageData(res?.data?.response);
    }
  };

  const Clearfun = async () => {
    setSelectedCustomer(null);
    setSelectedCustomerRole(null);
    // formRef?.current?.setFieldsValue({ Customer: '' });
    // formRef?.current?.setFieldsValue({ Payment: 0 });
    formRef.current?.resetFields(['Customer', 'Payment']);

    const currentDate = moment().format('DD-MM-YYYY');

    // Call DateChange function with the current date
    DateChange(null, currentDate);
    formRef.current?.setFieldsValue({ Date: currentDate });
  };

  const TranCompltList = async () => {
    const Data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      UserId: UserId,
    };
    const gettingTableData = await dispatch(getRetailTranList(Data)).unwrap();
    if (gettingTableData?.data?.statusCode === 1) {
      SetPaidListData(gettingTableData?.data?.data);
      setButtonDisabled(false);
    } else {
      SetPaidListData([]);
    }
  };

  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);

  const handlePageChange = (current) => {
    setpage(current);
  };
  const handleHoldCancel = () => {
    setHold(false);
  };

  const handleAddCustomer = () => {
    setAddCustomer(true);
  };
  const handleAddCustomerCancel = () => {
    // fetchWholeSaleProducts();
    fetchWholeSaleCustomer();
    setAddCustomer(false);
  };
  const DateChange = async (date, dateString) => {
    if (dateString) {
      const Date1 = moment(dateString, ['DD-MM-YYYY']).format(
        'YYYY-MM-DDTHH:mm:ss'
      );
      formRef.current?.setFieldsValue({ Date: Date1 });
      await setAjustDate(Date1);
    }
  };
  function safeRound(amountStr) {
    if (amountStr == null) return allowDecimal ? '0.00' : '0';

    const cleaned = String(amountStr).replace(/[^0-9.-]+/g, '');
    const num = Number(cleaned);

    if (isNaN(num)) return allowDecimal ? '0.00' : '0';

    return allowDecimal ? num.toFixed(2) : Math.round(num).toString();
  }

  return (
    <div className="pageOverAll">
      <div className="userPage">
        <div className="userPageContent">
          <div className="formName" style={{ margin: '0 0rem' }}>
            <FormHeader title={'Payment Updates'} />
          </div>
          <div>
            <div className="PaymentReceivedRetail-Master">
              <Messages
                messageType={messageType}
                messageData={messageData}
                onComplete={onComplete}
              />

              <div className="formDiv">
                <Form
                  style={{ width: '100%' }}
                  ref={formRef}
                  className="formDivAnt"
                  onFinish={onFinish}
                >
                  <div className="OBamountOwner">
                    <Form.Item
                      name="Customer"
                      rules={[
                        {
                          required: true,
                          message: 'Please Select Employee',
                        },
                      ]}
                    >
                      <div>
                        <DropDowns
                          defaultValue={SelectedCustomer}
                          options={[
                            { value: '0', label: 'All' },
                            ...(
                              customer?.map((option) => ({
                                value: option?.UserId,
                                label: option?.EmpFirstName
                                  ? `${option?.EmpFirstName} (${option?.RoleName})`
                                  : option?.MobileNo,
                              })) || []
                            )?.sort((a, b) =>
                              (a.label ?? '')
                                ?.toLowerCase()
                                ?.localeCompare((b.label ?? '')?.toLowerCase())
                            ),
                          ]}
                          label={<label>Owner / Employee </label>}
                          className="field-DropDown"
                          onChangeFunction={(e) =>
                            ChangeCustomer(e, 'Employee')
                          }
                          valueData={SelectedCustomer}
                          alphabetfilter="No"
                        />
                      </div>
                    </Form.Item>

                    <Form.Item
                      name="Payment"
                      rules={[
                        {
                          required: true,
                          pattern: /^[0-9]*\.?[0-9]+$/,
                          message: 'Please enter a valid Amount',
                        },
                        {
                          validator: async (_, value) => {
                            await validateSafeInput(value); // To block HTML tags & SQL keywords
                            return Promise.resolve();
                          },
                        },
                      ]}
                    >
                      <InputField
                        label={<label className="required">Amount</label>}
                        autocomplete="off"
                        inputMode="numeric"
                        onInput={(e) =>
                          (e.target.value = e.target.value.replace(
                            /[^0-9]/g,
                            ''
                          ))
                        }
                      />
                    </Form.Item>
                    <Form.Item
                      name="Date"
                      rules={[
                        {
                          required: true,
                          message: 'Please Enter Date',
                        },
                      ]}
                    >
                      <div
                        className="amountreceivedDate"
                        style={{ width: '120px' }}
                      >
                        {/* <label style={{ fontWeight: "600" }}>Date : </label> */}

                        <DatePicProd
                          canSelectPast={true}
                          cancelFuture={true}
                          onChange={DateChange}
                          valueData={AjustDate}
                          minDate={WSLastEntryDate}

                          // disabled={Checked}
                        />
                      </div>
                    </Form.Item>

                    <div style={{ display: 'flex', gap: '0.5rem' }}>
                      {EmployeePaymentModes.map((item) => {
                        return (
                          <div
                            className="saveBTNOB"
                            key={item.ConfigId}
                            style={{
                              backgroundColor:
                                item.ConfigId === selectedPaymentMode
                                  ? '#28AA3A'
                                  : 'rgb(174 174 174)',
                              color:
                                item.ConfigId === selectedPaymentMode
                                  ? '#FFF'
                                  : '#000',
                            }}
                            onClick={() =>
                              setSelectedPaymentMode(item.ConfigId)
                            }
                          >
                            {item.ConfigName}
                          </div>
                        );
                      })}
                    </div>

                    <div className="sumbitButtoProduct-entry">
                      <Buttons
                        buttonText="SUBMIT"
                        color="901D77"
                        icon={<ArrowRightOutlined />}
                        htmlType={true}
                        disabled={
                          SelectedCustomer == '0'
                            ? true
                            : ButtonDisabled || addnewAccess
                        }
                      />
                    </div>
                  </div>
                  {/* <div> */}
                </Form>
              </div>

              <div
                style={{
                  display: ' flex',
                  alignItems: 'center',
                  width: '100%',
                  justifyContent: 'space-between',
                }}
              >
                <p className="TransactionList-title">Transaction List</p>
              </div>
              <div
                className="AllEntryShowList"
                style={{ overflow: 'scroll', scrollbarWidth: 'none' }}
              >
                <div className="Re-Print-table">
                  <Tables
                    columns={columns}
                    data={FilterData}
                    dataSource={FilterData}
                    // data={PaidListData}
                    // dataSource={PaidListData}
                    pagination={handlePageChange}
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default PaymentReceivedRetail;
