import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useLocation, useNavigate } from 'react-router-dom';
import { Messages } from '../../../Components/Notifications/Messages';
import FormHeader from '../../PageComponents/FormHeader';
import { Col, Form, Row } from 'antd';
import { DropDowns } from '../../../Components/Forms/DropDown';
import Buttons from '../../../Components/Forms/Buttons';
import {
  getWholeSaleExtraCharges,
  getWholeSaleExtraChargesConfig,
  getWholeSaleProducts,
  postConfigMaster,
  postWholeSaleExtraCharges,
  putWholeSaleExtraCharges,
} from '../../../Features/WholeSale/ProductEntry';
import { getSession, validateSafeInput } from '../../../Services/Others';
import { InputField } from '../../../Components/Forms/InputField';
import { Tables } from '../../../Components/Tables/Table';
import {
  PlusCircleOutlined,
  ArrowRightOutlined,
  EditFilled,
  DeleteFilled,
  InfoCircleOutlined,
  PlusOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import { Tooltip, Table, Input, DatePicker, Collapse, Space } from 'antd';
import { DefaultModal } from '../../../Components/Modal/DefaultModal';
import {
  configTypeActiveDataSelector,
  configTypeDataSelector,
  getConfigurationType,
  postConfigurationType,
  putConfigurationType,
} from '../../../Features/ConfigTypePage/ConfigTypePage';
import { RadioGrpButton } from '../../../Components/Forms/RadioGroup';
import { changeBreadCrumb } from '../../../Features/AppPage/CenterPage';

const subDirectory = import.meta.env.BASE_URL;

const ItemEntry = () => {
  const formRef = useRef(null);
  const [configRef] = Form.useForm();

  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [ProductData, setProductData] = useState([]);
  const [selectedProductData, setselectedProductData] = useState(null);
  const [ConfigId, setConfigId] = useState(null);
  const [selectedProductName, setselectedProductName] = useState(null);
  const [CommonDataFilter, setCommonDataFilter] = useState([]);
  const [editState, seteditState] = useState([]);
  const [page, setpage] = useState(1);
  const [open, setOpen] = useState(false);
  const [PaymentType, setPaymentType] = useState('P');
  const [configdatas, setconfigdatas] = useState([]);
  const [ConfigText, setConfigText] = useState([]);
  const location = useLocation()?.state;
  const [putState, setputState] = useState(false);

  console.log(CommonDataFilter?.[4], 'ProductDataProductDataj');

  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');
  const UserId = getSession('UserId');

  const items = [
    {
      name: 'Home',
      link: `${subDirectory}app-page/home`,
    },
    {
      name: 'ExtraCharges',
      link: `${subDirectory}setting/wholesale-extracharges`,
    },
  ];
  useEffect(() => {
    if (location !== null) {
      setCommonDataFilter(transformData(location));
      setputState(true);
    } else {
      setputState(false);
    }
  }, [location]);
  const transformData = (data) => {
    return data?.ProductDetails?.flatMap((product) =>
      product.ExtraChargeDetails.map((extraCharge) => ({
        ProdName: product.ProdName,
        ConfigName: extraCharge.ExtraChargeName || 'Commission',
        ConfigId: extraCharge.ExtraChargeType,
        Payment: extraCharge.Amount.toString(),
        PaymentType: extraCharge.AmountType,
        ProdId: product.ProdId,
        ExtraChargeId: data?.ExtraChargeId,
        ActiveStatus: extraCharge.ActiveStatus ? extraCharge.ActiveStatus : '',
      }))
    );
  };
  useEffect(() => {
    dispatch(changeBreadCrumb({ items: items }));
  }, []);

  const columns = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',

      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
      ),
    },

    {
      title: 'Product',
      dataIndex: 'ProdName',
      key: 'ProdName',
      render: (text, row) => <a style={{ color: 'black' }}>{row.ProdName}</a>,
    },
    {
      title: 'Extra Charge',
      dataIndex: 'ConfigName',
      key: 'ConfigName',
      render: (text, row) => <a style={{ color: 'black' }}>{row.ConfigName}</a>,
    },
    {
      title: 'Amount',
      dataIndex: 'PaymentValue',
      key: 'PaymentValue',
      align: 'right',
      render: (text, row) => (
        <a style={{ color: 'black' }}>
          {row.Payment}
          {row.PaymentType == 'P' ? '%' : '₹'}
        </a>
      ),
    },

    {
      title: 'Edit',
      key: 'Edit',
      dataIndex: 'Edit',
      width: '100px',
      align: 'center',
      render: (_, record, index) => (
        <Space size="middle">
          <EditFilled
            style={{ color: '#1292EE' }}
            onClick={() => ActionsFormatter(record, index)}
          />
        </Space>
      ),
    },
    {
      title: 'Delete',
      key: 'Delete',
      dataIndex: 'Delete',
      width: '100px',
      align: 'center',
      render: (_, record, index) => {
        return putState ? (
          <Space size="middle">
            {record?.ActiveStatus == 'D' ? (
              <ReloadOutlined
                style={{
                  color: '#52C41A',
                }}
                onClick={() => StatusFormatter2(record, index)}
              />
            ) : (
              <DeleteFilled
                style={{
                  color: '#FF4D4F',
                }}
                onClick={() => StatusFormatter2(record, index)}
              />
            )}
          </Space>
        ) : (
          <Space size="middle">
            <DeleteFilled
              style={{
                color: '#FF4D4F',
              }}
              onClick={() => StatusFormatter(record, index)}
            />
          </Space>
        );
      },
    },
  ];

  useEffect(() => {
    fetchWholeSaleProducts();
  }, []);

  useEffect(() => {
    onchangepaymentType(PaymentType);
  }, [PaymentType]);

  const ActionsFormatter = (record) => {
    console.log(record, 'fgfdggtrertret');
    setselectedProductData(record?.ProdId);
    seteditState(record);
    onchangepaymentType(record?.PaymentType);
    setPaymentType(record?.PaymentType);
    setConfigId(record?.ConfigId);
    formRef.current?.setFieldsValue(record);
    // formRef.current?.setFieldsValue({ ConfigId: record?.ConfigId })
    // formRef.current?.setFieldsValue({ PaymentType: record?.PaymentType })
  };
  const StatusFormatter = (record) => {
    setCommonDataFilter(
      CommonDataFilter?.filter(
        (item) =>
          !(item.ProdId === record.ProdId && item.ConfigId === record?.ConfigId)
      )
    );
  };
  const StatusFormatter2 = (record) => {
    console.log(
      { ...record, ActiveStatus: record?.ActiveStatus == 'A' ? 'D' : 'A' },
      'fgaggdddddddd8'
    );
    setCommonDataFilter(
      CommonDataFilter?.map((item) =>
        item.ProdId === record.ProdId && item.ConfigId === record?.ConfigId
          ? { ...item, ActiveStatus: record?.ActiveStatus === 'A' ? 'D' : 'A' } // Update the matching item
          : item
      )
    );
  };

  const fetchWholeSaleProducts = async () => {
    dispatch(getConfigurationType()).unwrap();
    let response = await dispatch(
      getWholeSaleProducts({ CompId: CompId, AppId: AppId, BranchId: BranchId })
    ).unwrap();

    if (response?.data?.statusCode == 1) {
      setProductData(response?.data?.data);
    }
    let res = await dispatch(getWholeSaleExtraChargesConfig()).unwrap();
    if (res?.data?.statusCode == 1) {
      console.log(res, 'resjkshdgfg');
      setconfigdatas(res?.data?.data);
    }
    console.log(await configRef.current.getFieldValue(), 'ihfshdfojs');
  };

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

  const onFinish = (values) => {
    console.log(values, 'sdgfgdgafdgfd45');
    let exteraDatas = {
      ProdName: ProductData?.filter((item) => item.ProdId == values.ProdId)?.[0]
        ?.ProdName,
      ConfigName: configdatas?.filter(
        (item) => item.ConfigId == values.ConfigId
      )?.[0]?.ConfigName,
      ConfigId: values?.ConfigId,
      Payment: values?.Payment,
      PaymentType: values?.PaymentType ? values?.PaymentType : PaymentType,
      ProdId: values?.ProdId,
      ExtraChargeId: CommonDataFilter?.[0]?.ExtraChargeId,
      ActiveStatus: CommonDataFilter?.filter(
        (item) =>
          item.ProdId == values.ProdId && item.ConfigId === values?.ConfigId
      )?.[0]?.ActiveStatus,
    };

    let Data = values;
    console.log(
      CommonDataFilter.filter(
        (item) =>
          !(item.ProdId === values.ProdId && item.ConfigId === values?.ConfigId)
      ),
      'sdg456fgdg'
    );
    setCommonDataFilter([
      ...CommonDataFilter?.filter(
        (item) =>
          !(item.ProdId === values.ProdId && item.ConfigId === values?.ConfigId)
      ),
      exteraDatas,
    ]);
    formRef.current?.resetFields();
    setselectedProductData();
    setselectedProductName();
    setConfigId();
    seteditState([]);
    setPaymentType('P');
  };
  const ProductDropDownChange = (e) => {
    // let alreadyexist = CommonDataFilter.some(item => item.ProdId === e)
    // if (!alreadyexist) {
    formRef.current?.setFieldsValue({ ProdId: e });
    setselectedProductData(e);
    setselectedProductName(
      ProductData.filter((item) => item.ProdId == e)?.[0]?.ProdName
    );
    // }
    // else {
    //     setMessageData("Do not allow a single product multiple times.");
    //     setMessageType("error");
    // }
  };

  const ConfigTypeChange = (e) => {
    let alreadyexist = CommonDataFilter.some(
      (item) => item.ProdId === selectedProductData && item.ConfigId === e
    );
    if (alreadyexist) {
      setMessageType('error');
      setMessageData("You can't add same Extracharges multiple time at a time");
    } else {
      formRef.current?.setFieldsValue({ ConfigId: e });
      setConfigId(e);
    }
  };

  const handlePageChange = (current) => {
    setpage(current);
  };
  const addConfig = () => {
    setOpen(true);
  };

  const handleSubmit = async () => {
    const values = await configRef.validateFields();
    const postData = {
      // ConfigName: values.ConfigName,
      // CreatedBy: getSession('UserId'),

      TypeId: configdatas?.[0]?.TypeId,
      ConfigName: ConfigText,
      CreatedBy: UserId,
    };
    let response = {};

    response = await dispatch(postConfigMaster(postData)).unwrap();

    if (response?.data?.statusCode == 1) {
      let res = await dispatch(getWholeSaleExtraChargesConfig()).unwrap();
      if (res?.data?.statusCode == 1) {
        setconfigdatas(res?.data?.data);
      }
      setMessageType('success');
      setMessageData(response?.data?.response);
      handleCancel();
      dispatch(getConfigurationType()).unwrap();
    } else {
      setMessageType('error');
      setMessageData(response?.data?.response);
    }
  };

  const handleCancel = () => {
    setOpen(false);
  };
  const PostValues = async () => {
    if (CommonDataFilter.length > 0) {
      let grouped = CommonDataFilter.reduce((acc, obj) => {
        if (!acc[obj.ProdName]) {
          acc[obj.ProdName] = [];
        }
        acc[obj.ProdName].push(obj);
        return acc;
      }, {});

      // Convert grouped data to an array of arrays
      let result = Object.values(grouped);

      let response = [];
      if (putState) {
        // let postData = {
        //     "AppId": AppId,
        //     "CompId": CompId,
        //     "BranchId": BranchId,
        //     "ExtraChargeId": CommonDataFilter?.[0]?.ExtraChargeId,
        //     "ProductDetails": CommonDataFilter.map((item) => ({
        //         "ProdId": item.ProdId,
        //         "ExtraChargeDetails": [
        //             {
        //                 "ExtraChargeType": item.ConfigId,
        //                 "Amount": item.Payment,
        //                 "AmountType": item.PaymentType,
        //                 "ActiveStatus": item?.ActiveStatus,
        //             },
        //         ],
        //     })),
        //     "UpdatedBy": UserId
        // }

        const postData = {
          AppId: AppId,
          CompId: CompId,
          BranchId: BranchId,
          ExtraChargeId: result[0]?.[0]?.ExtraChargeId,
          ProductDetails: result.map((group) => ({
            ProdId: group[0].ProdId,
            ExtraChargeDetails: group.map((item) => ({
              ExtraChargeType: item.ConfigId,
              Amount: item.Payment,
              AmountType: item.PaymentType,
              ActiveStatus:
                item?.ActiveStatus == ' ' ||
                item?.ActiveStatus == '' ||
                item?.ActiveStatus == undefined ||
                item?.ActiveStatus == null
                  ? 'A'
                  : item?.ActiveStatus,
            })),
          })),
          UpdatedBy: UserId,
        };
        response = await dispatch(putWholeSaleExtraCharges(postData)).unwrap();
      } else {
        const postData = {
          AppId: AppId,
          CompId: CompId,
          BranchId: BranchId,
          ProductDetails: result.map((group) => ({
            ProdId: group[0].ProdId,
            ExtraChargeDetails: group.map((item) => ({
              ExtraChargeType: item.ConfigId,
              Amount: item.Payment,
              AmountType: item.PaymentType,
            })),
          })),
          CreatedBy: UserId,
        };

        response = await dispatch(postWholeSaleExtraCharges(postData)).unwrap();
      }

      if (response?.data?.statusCode === 1) {
        console.log(response, 'postValueskjhfdsd');
        setMessageType('success');
        setMessageData(response?.data?.response);
        navigate(`${subDirectory}setting/wholesale-extracharges`);
      } else {
        setMessageType('error');
        setMessageData(response?.data?.response);
      }
    } else {
      setMessageData('Add all data');
      setMessageType('error');
    }
  };
  const onchangepaymentType = (value) => {
    formRef.current?.setFieldsValue({ PaymentType: value });
    setPaymentType(value);
  };
  const readConfigname = (value) => {
    console.log(value.target.value, 'dfsfggfds');
    setConfigText(value.target.value);
  };

  return (
    <div className="pageOverAll">
      <div className="userPage">
        <div className="userPageContent">
          <Messages
            messageType={messageType}
            messageData={messageData}
            onComplete={onComplete}
          />
          <div className="formAddNew">
            <div>
              <FormHeader title={'Extra Charges'} />
            </div>
            <div className="searchAddDiv">
              {/* <div className="formSearch">
                            <Search
                                placeholder='Search'
                                onSearch={onSearch}
                                onSearchChange={onSearchChange}
                            />
                        </div> */}

              <Form ref={formRef} className="formDivAnt" onFinish={onFinish}>
                <div className="formDiv4">
                  <Form.Item
                    name="ProdId"
                    rules={[
                      {
                        required: true,
                        message: 'Please Select Product Name',
                      },
                    ]}
                  >
                    <div className="WholeSaleProduct-entry">
                      <DropDowns
                        options={ProductData?.map((option) => ({
                          value: option.ProdId,
                          label: option.ProdName,
                        }))}
                        label={'Product'}
                        className="field-DropDown"
                        onChangeFunction={(e) => ProductDropDownChange(e)}
                        isOnChange={false}
                        valueData={selectedProductData}
                        defaultValue={selectedProductData}
                        // disabled={putState ? true : false}
                      />
                    </div>
                  </Form.Item>

                  <Form.Item
                    name="ConfigId"
                    rules={[
                      {
                        required: true,
                        message: 'Please Select Extra Charge',
                      },
                    ]}
                  >
                    <div className="WholeSaleProduct-entry">
                      <DropDowns
                        options={configdatas?.map((option) => ({
                          value: option.ConfigId,
                          label: option.ConfigName,
                        }))}
                        label={'Extra Charge'}
                        className="field-DropDown"
                        onChangeFunction={(e) => ConfigTypeChange(e)}
                        isOnChange={false}
                        valueData={ConfigId}
                        defaultValue={ConfigId}
                        // disabled={putState ? true : false}
                        // disabled={editState?.ProdId ? true : false}
                      />
                      <PlusCircleOutlined onClick={addConfig} />
                    </div>
                  </Form.Item>

                  <Form.Item name="PaymentType">
                    <RadioGrpButton
                      content={[
                        { value: 'P', label: 'Percentage' },
                        { value: 'F', label: 'fixed' },
                      ]}
                      // fieldState={true}
                      // defaultSelect={!editState?.Payment && PaymentType}
                      defaultSelect={PaymentType}
                      Header={'Amount Type'}
                      onSelectFuntion={(e) => onchangepaymentType(e)}
                    />
                  </Form.Item>

                  <Form.Item
                    name="Payment"
                    rules={[
                      {
                        required: true,
                        message: 'Please Enter Amount',
                      },
                      {
                        validator: async (_, value) => {
                          await validateSafeInput(value); // To block HTML tags & SQL keywords
                          return Promise.resolve();
                        },
                      },
                    ]}
                  >
                    <InputField
                      type="number"
                      autoComplete="off"
                      label={'Amount'}
                      // onChange={(e) => handleCommissionChange(e)}
                      isOnChange={editState?.Payment ? true : false}
                    />
                  </Form.Item>
                </div>
                {/* <div> */}
                <div className="sumbitButtoProduct-entry">
                  <Buttons
                    buttonText="Add"
                    color="901D77"
                    icon={<PlusOutlined />}
                    htmlType={true}
                  />
                </div>
              </Form>
            </div>
            <div className="">
              <Tables
                columns={columns}
                data={CommonDataFilter}
                pagination={handlePageChange}
              />
            </div>
            <div className="submitButton">
              <Buttons
                buttonText="Submit"
                color="901D77"
                handleSubmit={PostValues}
                icon={<ArrowRightOutlined />}
                htmlType={true}
              />
            </div>
          </div>
        </div>

        <DefaultModal
          open={open}
          title="Extra Charge"
          footer={true}
          children={
            <Form form={configRef}>
              <Row>
                <Col className="gutter-row" span={6}>
                  <Form.Item
                    name="TypeName"
                    rules={[
                      {
                        required: true,
                        pattern: /^(?!\s*$).+/,
                        message: 'Please Enter Extra Charge Name ',
                      },
                      {
                        validator: async (_, value) => {
                          await validateSafeInput(value); // To block HTML tags & SQL keywords
                          return Promise.resolve();
                        },
                      },
                    ]}
                  >
                    <InputField
                      onChange={readConfigname}
                      label={<label class="required">Extra Charge Name</label>}
                      autoComplete="off"
                      // isOnChange={editState ? true : false}
                    />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          }
          handleCancel={handleCancel}
          handleSubmit={handleSubmit}
        />
      </div>
    </div>
  );
};

export default ItemEntry;
