import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
  getSession,
  extractLastNumber,
  dateTimeFormatChange,
} from '../../../Services/Others';
import { Tables } from '../../../Components/Tables/Table';
import { RadioGrpButton } from '../../../Components/Forms/RadioGroup.jsx';
import { Form, Popover } from 'antd';
import { InputField } from '../../../Components/Forms/InputField.jsx';
import Buttons from '../../../Components/Forms/Buttons.jsx';
import { PlusOutlined } from '@ant-design/icons';
import { DropDowns } from '../../../Components/Forms/DropDown.jsx';
import {
  getCustmentWholeSaleTran,
  getEmployeeWholeSaleTran,
  getWholeSalePayments,
  getWholeSaleTranList,
  PostCustempWholeSaleTran,
} from '../../../Features/WSTransaction/WSTransaction.js';
import { Messages } from '../../../Components/Notifications/Messages.jsx';

const OpeningBalance = () => {
  const dispatch = useDispatch();
  const formRef = useRef();
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');
  const UserId = getSession('UserId');

  const [page, setpage] = useState(1);
  const [SelectedCustomer, setSelectedCustomer] = useState();
  const [SelectedCustomerRole, setSelectedCustomerRole] = useState();
  const [customer, setCustomer] = useState();
  const [CustPaymentModes, setPaymentModesCust] = 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');

  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]);

  console.log(selectedPaymentMode, 'selectedPaymentMode');

  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: 'Name',
      key: 'UserName',
      dataIndex: 'UserName',
      render: (productDetails, record) => (
        <a style={{ color: 'black' }}>
          {record?.UserRole === 'Admin'
            ? `${record?.UserName} (Admin)`
            : 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: 'black' }}>{record?.Amount}</a>
      ),
    },
  ];

  const Custmercolumns = [
    // {
    //     title: "SI.NO",
    //     key: "sno",
    //     align: "center",
    //     width: "80px",
    //     render: (text, object, index) => (
    //         <a style={{ color: "black" }}>{index + 1}</a>
    //     ),
    // },
    // {
    //   title: "Name",
    //   dataIndex: 'CustSuppName',
    //   key: "CustSuppName",
    //   width: "150px",
    //   render: (text, row) => (
    //     <a style={{ color: "black", width: "200px" }}>{text}</a>
    //   ),

    //   onCell: (record) => ({
    //     onClick: () => {
    //       vieworders(record);
    //     },
    //   }),
    // },

    {
      title: 'OB',
      dataIndex: 'OpeningBalance',
      key: 'OpeningBalance',
      width: '110px',
      align: 'right',
      render: (text) => (
        <a style={{ color: text < 0 ? 'red' : 'Green' }}>
          {Math.abs(text)} {/* Show absolute value */}
        </a>
      ),
    },
    {
      title: 'Sales',
      dataIndex: 'NetAmount',
      key: 'NetAmount',
      width: '110px',
      align: 'right',
      render: (text) => <a style={{ color: 'black' }}>{text || 0}</a>,
    },

    {
      title: 'Commission',
      dataIndex: 'CommissionAmount',
      key: 'CommissionAmount',
      width: '110px',
      align: 'right',
      render: (text, row) => <a style={{ color: 'black' }}>{text || 0}</a>,
    },
    {
      title: 'Total Balance',
      dataIndex: 'Total',
      key: 'Total',
      width: '110px',
      align: 'right',
      render: (text, record) => (
        <a
          style={{
            color:
              (record?.OpeningBalance || 0) +
                (record?.NetAmount || 0) -
                (record?.CommissionAmount || 0) <
              0
                ? 'red' // Red if negative
                : 'green', // Green if positive
          }}
        >
          {Math.abs(
            (record?.OpeningBalance || 0) +
              (record?.NetAmount || 0) -
              (record?.CommissionAmount || 0)
          )}
        </a>
      ),
    },
  ];
  const onChangeOption = async (e) => {
    setPaymentType(e);
    formRef?.current?.setFieldsValue({ Customer: null });
    setSelectedCustomer(null);
    setSelectedCustomerRole(null);
  };

  const ChangeCustomer = (e, role) => {
    if (role === 'Employee') {
      let data = customer?.find((a) => a.UserId === e)?.RoleName;
      formRef?.current?.setFieldsValue({ Customer: e });
      setSelectedCustomer(e);
      setSelectedCustomerRole(data);
    } else {
      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();
  }, []);

  useEffect(() => {
    if (PaymentType === 'C') {
      fetchWholeSaleCustomer();
    } else {
      fetchWholeSaleEmployee();
    }
  }, [PaymentType, EmployeePaymentModes]);
  const fetchWholeSaleCustomer = async () => {
    const Data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
    };
    const gettingTableData = await dispatch(
      getCustmentWholeSaleTran(Data)
    ).unwrap();
    if (gettingTableData?.data?.statusCode === 1) {
      setCustomer(gettingTableData?.data?.data);
      console.log(CustPaymentModes);
      let cutDefaultValue = CustPaymentModes?.[0];
      setSelectedPaymentMode(cutDefaultValue?.ConfigId);
    } else {
      setCustomer([]);
      setSelectedPaymentMode('');
    }
  };

  const fetchWholeSaleEmployee = async () => {
    const Data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
    };
    const gettingTableData = await dispatch(
      getEmployeeWholeSaleTran(Data)
    ).unwrap();
    if (gettingTableData?.data?.statusCode === 1) {
      setCustomer(gettingTableData?.data?.data);
      let EmpDefaultValue = EmployeePaymentModes?.[0];
      setSelectedPaymentMode(EmpDefaultValue?.ConfigId);
    } else {
      setCustomer([]);
      setSelectedPaymentMode('');
    }
  };

  const onFinish = async (values) => {
    setButtonDisabled(true);
    const data = customer.find((a) => a?.CustSuppId === SelectedCustomer);

    const postData = {
      UserId: values?.Customer,
      ReceivedAmount: values?.Payment,
      PaymentType: selectedPaymentMode,
      CompId: CompId,
      AppId: AppId,
      BranchId: BranchId,
      PaymentStatus: 'S',
      UserRole: SelectedCustomerRole,
      BalanceType: 'OB',
      NetAmount: data?.NetAmount,
      CreatedBy: UserId,
      OpeningBalance: data?.OpeningBalance,
      OrderDetails: data?.OrderDetails,
      PaymentDetail: [
        {
          Amount: values?.Payment,
          PaymentType: selectedPaymentMode,
          PaymentStatus: 'S',
          // "Debit":credit?values?.Payment:0,
          // "Credit":!credit? values?.Payment:0
        },
      ],
    };

    const res = await dispatch(PostCustempWholeSaleTran(postData)).unwrap();
    if (res?.data?.statusCode === 1) {
      setMessageType('success');
      setMessageData('Amount Added Successfully');
      if (SelectedCustomerRole === 'Customer') {
        await fetchWholeSaleCustomer();
      } else {
        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();
  };

  const TranCompltList = async () => {
    const Data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      UserId: UserId,
    };
    const gettingTableData = await dispatch(
      getWholeSaleTranList(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);
  };

  return (
    <div className="OpeningBalance-Master">
      <Messages
        messageType={messageType}
        messageData={messageData}
        onComplete={onComplete}
      />
      <RadioGrpButton
        content={[
          { value: 'M', label: 'Mandi Fund' },
          { value: 'C', label: 'Customer' },
        ]}
        defaultSelect={PaymentType}
        Header={''}
        onSelectFuntion={(e) => onChangeOption(e)}
      />
      {PaymentType === 'C' && (
        <div className="formDiv">
          <Form ref={formRef} className="formDivAnt" onFinish={onFinish}>
            <div className="openingbalanceInput">
              <div className="openingbalanceInput2">
                <Form.Item
                  name="Customer"
                  rules={[
                    {
                      required: true,
                      message: 'Please Enter Customer',
                    },
                  ]}
                >
                  <DropDowns
                    defaultValue={SelectedCustomer}
                    options={customer?.map((option) => ({
                      value: option?.CustSuppId,
                      label: option?.CustShortName
                        ? option?.CustShortName
                        : option?.CustSuppName
                          ? option?.CustSuppName
                          : option?.CustMobile,
                    }))}
                    label={<label>Customer </label>}
                    className="field-DropDown"
                    onChangeFunction={(e) => ChangeCustomer(e, 'Customer')}
                    valueData={SelectedCustomer}
                  />
                </Form.Item>

                <div className="customerpayRequest">
                  <Form.Item
                    name="Payment"
                    rules={[
                      {
                        required: true,
                        pattern: /^[0-9]*\.?[0-9]+$/,
                        message: 'Please enter a valid Amount',
                      },

                      {
                        validator: (_, value) => {
                          if (value === undefined || value === null) {
                            return Promise.reject(
                              'Please enter a valid Amount'
                            );
                          }

                          return Promise.resolve();
                        },
                      },
                    ]}
                  >
                    <InputField
                      label={<label className="required">Amount</label>}
                      disabled={
                        CustPaymentModes.find(
                          (a) => a.ConfigId === selectedPaymentMode
                        )?.ConfigName === 'Credit'
                          ? true
                          : false
                      }
                      autocomplete="off"
                      isOnChange={
                        CustPaymentModes.find(
                          (a) => a.ConfigId === selectedPaymentMode
                        )?.ConfigName === 'Credit' && true
                      }
                    />
                  </Form.Item>
                  <div style={{ display: 'flex', gap: '0.5rem' }}>
                    {CustPaymentModes?.filter(
                      (item) =>
                        !(
                          item.ConfigName === 'Credit' &&
                          !customer.find(
                            (a) => a?.CustSuppId === SelectedCustomer
                          )?.OrderDetails?.length > 0
                        )
                    ).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>
                <div className="sumbitButtoProduct-entry">
                  <Buttons
                    buttonText="Add"
                    disabled={ButtonDisabled}
                    color="901D77"
                    icon={<PlusOutlined />}
                    htmlType={true}
                  />
                </div>
              </div>
              <div className="obcustomertable">
                {customer
                  .filter((a) => a?.CustSuppId === SelectedCustomer)
                  .map((filteredCustomer) => (
                    <div
                      className="customerpayRequest-One"
                      key={filteredCustomer.CustSuppId}
                    >
                      <p>
                        OB :
                        <span
                          style={{
                            color:
                              filteredCustomer?.OpeningBalance < 0
                                ? 'red'
                                : 'green',
                          }}
                        >
                          {Math.abs(filteredCustomer?.OpeningBalance)}
                        </span>
                      </p>
                      <p>Sales Amount : {filteredCustomer?.NetAmount || 0}</p>
                      <p>
                        {' '}
                        Total Balance Amount :{' '}
                        <span
                          style={{
                            color:
                              (filteredCustomer?.OpeningBalance || 0) -
                                (filteredCustomer?.NetAmount || 0) <
                              0
                                ? 'red' // Red if negative
                                : 'green', // Green if positive
                          }}
                        >
                          {' '}
                          {Math.abs(
                            (filteredCustomer?.OpeningBalance || 0) -
                              (filteredCustomer?.NetAmount || 0)
                          )}
                        </span>
                      </p>
                    </div>
                  ))}
              </div>
            </div>
          </Form>
        </div>
      )}

      {PaymentType === 'M' && (
        <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 Enter Customer',
                  },
                ]}
              >
                <div>
                  <DropDowns
                    defaultValue={SelectedCustomer}
                    options={customer?.map((option) => ({
                      value: option?.UserId,
                      label: option?.EmpFirstName
                        ? `${option?.EmpFirstName} ${option?.RoleName === 'Admin' ? '(Admin)' : ''}`
                        : option?.MobileNo,
                    }))}
                    label={<label>Owner / Employee </label>}
                    className="field-DropDown"
                    onChangeFunction={(e) => ChangeCustomer(e, 'Employee')}
                    valueData={SelectedCustomer}
                  />
                </div>
              </Form.Item>

              <Form.Item
                name="Payment"
                rules={[
                  {
                    required: true,
                    pattern: /^[0-9]*\.?[0-9]+$/,
                    message: 'Please enter a valid Amount',
                  },
                ]}
              >
                <InputField
                  label={<label className="required">Amount</label>}
                  autocomplete="off"
                />
              </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="Add"
                  color="901D77"
                  icon={<PlusOutlined />}
                  htmlType={true}
                />
              </div>
            </div>
            {/* <div> */}
          </Form>
        </div>
      )}
      <div
        style={{
          display: ' flex',
          alignItems: 'center',
          width: '100%',
          justifyContent: 'space-between',
        }}
      >
        <p className="TransactionList-title">Transaction List</p>
        <Popover
          content={
            <>
              {PaidListData?.[0]?.CashTotalAmount > 0 && (
                <div className="TransactionList-title">
                  Cash:{PaidListData?.[0]?.CashTotalAmount}
                </div>
              )}
              {PaidListData?.[0]?.UpiTotalAmount > 0 && (
                <div className="TransactionList-title">
                  UPI:{PaidListData?.[0]?.UpiTotalAmount}
                </div>
              )}
              {PaidListData?.[0]?.CardTotalAmount > 0 && (
                <div className="TransactionList-title">
                  Card:{PaidListData?.[0]?.CardTotalAmount}
                </div>
              )}
              {PaidListData?.[0]?.CreditTotalAmount > 0 && (
                <div className="TransactionList-title">
                  Credit:{PaidListData?.[0]?.CreditTotalAmount}
                </div>
              )}
            </>
          }
        >
          <p
            className="TransactionList-title"
            style={{ fontSize: '14px', cursor: 'pointer' }}
          >
            Total Amount :{' '}
            <span>{PaidListData?.[0]?.OverAllTotalAmount || 0}</span>
          </p>
        </Popover>
      </div>
      <div className="AllEntryShowList" style={{ overflow: 'scroll' }}>
        <div className="Re-Print-table">
          <Tables
            columns={columns}
            data={PaidListData}
            dataSource={PaidListData}
            pagination={handlePageChange}
          />
        </div>
      </div>
    </div>
  );
};

export default OpeningBalance;
