import { UnitcodeService, VendorsService, TaxesService, PackingMethodService, SkuService } from "@gtpl/shared-services/masters";
import { Button, Card, Col, Divider, Form, Input, Popconfirm, Row, Select, Table, Tag, Tooltip } from "antd"
import form from "antd/lib/form"
import React, { useEffect, useState } from "react"
import { EditOutlined, MinusCircleOutlined, PlusOutlined, UndoOutlined } from "@ant-design/icons";
import { PurchasesProductService } from "@gtpl/shared-services/finance";

interface IProps {
  tableData: any[];
  setTableData: React.Dispatch<React.SetStateAction<any[]>>

}
export const PurchasesProductForm = (props: IProps) => {
  const { Option } = Select;
  const [form] = Form.useForm();
  const unitService = new UnitcodeService()
  const [plants, setPlants] = useState([])
  const vendorsService = new VendorsService()
  const [vendors, setVendors] = useState([])
  const taxService = new TaxesService()
  const [taxes, setTaxes] = useState([])
  const [taxValue, setTaxValue] = useState('')
  const [selectedItem, setSelectedItem] = useState<any>(null);

  const packStyleService = new PackingMethodService()
  const [packStyles, setPackStyles] = useState([])
  const [packStyleName, setPackStyleName] = useState('')
  const purchaseService = new PurchasesProductService()
  const productService = new SkuService()
  const [products, setProducts] = useState([])
  const [productName, setProductName] = useState('')
  const [showPickRequestTable, setShowPickRequestTable] = useState<boolean>(false)
  const [data, setData] = useState([]);
  const [caseWe, setCaseWe] = useState(0);
  const [netWe, setNetWe] = useState(0);
  const { tableData, setTableData } = props;

  useEffect(() => {
    getTaxes()
    getPackStyles()
    getProducts()
    console.log('oooookkkkkkkkkkk')
  }, [])
  const getProducts = () => {
    purchaseService.getAllProducts().then((res) => {
      if (res.status) {
        setProducts(res.data)
      }
    })
  }
  const getTaxes = () => {
    taxService.getAllActiveTaxes().then((res) => {
      if (res.status) {
        setTaxes(res.data)
      }
    })
  }
  const getPackStyles = () => {
    packStyleService.getAllActivePackingMethods().then((res) => {
      if (res.status) {
        setPackStyles(res.data)
      }
    })
  }
  const onEdit = (record) => {
    setSelectedItem(record);
    form.setFieldsValue(record);
  };
  const onDelete = (record) => {
    const updatedData = tableData.filter((item) => item.id !== record.id);
    setTableData(updatedData);
    form.resetFields();
  };



  const columns = [
    {
      title: 'Product',
      dataIndex: 'productName',
      render: (text: any, record: any) => {

        return (
          <>
            {record.productName ? record.productName : '-'}
          </>
        )
      }
    },
    {
      title: 'Pack Style',
      dataIndex: 'packStyleName',

    },
    {
      title: 'Cases',
      dataIndex: 'cases',

    },
    {
      title: 'Case Weight',
      dataIndex: 'caseWeight',

    },
    {
      title: 'Unit Price',
      dataIndex: 'unitPrice',

    },
    {
      title: 'Net Weight',
      dataIndex: 'netWeight',

    },
    {
      title: 'Tax',
      dataIndex: 'taxValue',
      render:(val,res) =>{
        return (<span>{res.taxValue}%</span>)
      }

    },
    {
      title: 'Total Amount',
      dataIndex: 'totalAmount',

    },
    {
      title: "Action",
      dataIndex: 'action',
      render: (text: any, rowData: any, index: any) => (
        <span>
          <Tooltip placement="top" title='Edit'>
            <Tag >
              {/* <Popconfirm title='Sure to Edit?' onConfirm={e =>{setEditForm(rowData,index);}}> */}

              <EditOutlined className={'editSamplTypeIcon'} type="edit"
                onClick={() => onEdit(rowData)}
                style={{ color: '#1890ff', fontSize: '14px' }}
              />
              {/* </Popconfirm> */}
            </Tag>
          </Tooltip>
          <Divider type="vertical" />

          <Tooltip placement="top" title='delete'>
            <Tag >
              <Popconfirm title='Sure to delete?'
                onConfirm={() => onDelete(rowData)}                >
                <MinusCircleOutlined

                  style={{ color: '#1890ff', fontSize: '14px' }} />
              </Popconfirm>
            </Tag>
          </Tooltip>
        </span>
      )
    }
  ]
  const productChange = (res, val) => {
    setProductName(val.product)
    form.setFieldsValue({ 'productName': val.product })
    
  }
  const onPackStyle = (res, val) => {
    console.log(val, 'pack style');
    const pouch = val.pouches * val.pouchPer
    setPackStyleName(val.pack)
    form.setFieldsValue({ 'packStyleName': val.pack })
    
    form.setFieldsValue({ 'caseWeight': pouch })
    if(form.getFieldValue('cases')!== undefined){
      const net = pouch* form.getFieldValue('cases')
setNetWe(net)
      form.setFieldsValue({ 'netWeight': net })
      const amt = netWe*Number(val.target.value)//netweight*unitprice
  const taxAmt = Number(Number(taxValue)/ 100)*Number(amt) //tax*amt
  const totAmt = taxAmt+amt
  form.setFieldsValue({ totalAmount: totAmt })
    }

    
  }

  useEffect(() => {
  }, [tableData])

  const onCancel = () => {
    setSelectedItem(null);
    form.resetFields();
  };
  const priceChange = (val) => {
    console.log(val.target.value, 'pppppppppppp');

    const total = val.target.value * netWe
    console.log(total, 'oooooooooooooooooo');

    // const currentValues = form.getFieldsValue();
    //   const updatedValues = [...currentValues.purchasesProductInfo]; // Assuming `purchasesProductInfo` is an array

    //   updatedValues[index] = {
    //     ...updatedValues[index],
    //     totalAmount: total
    //   };

    // form.setFieldsValue({ purchasesProductInfo: updatedValues });
    form.setFieldsValue({ 'totalAmount': total })
    console.log(taxValue,'oooooooooo');
    
if(netWe !==undefined && taxValue!== undefined){
  console.log('pppppppppppppppp');
  console.log(netWe,'nettttttttttttt');
  console.log(taxValue,'oooooooooo');
  const amt = netWe*Number(val.target.value)//netweight*unitprice
  const taxAmt = Number(Number(taxValue)/ 100)*Number(amt) //tax*amt
  const totAmt = taxAmt+amt
  form.setFieldsValue({ totalAmount: totAmt })
}
  }
  const casesChange = (val) => {
    setCaseWe(Number(val.target.value) * form.getFieldValue('caseWeight'))
    const netWe = Number(val.target.value) * form.getFieldValue('caseWeight')
    setNetWe(netWe)
    form.setFieldsValue({ netWeight: netWe });
    const amt = form.getFieldValue('netWeight')*Number(form.getFieldValue('unitPrice'))//netweight*unitprice
    const taxAmt = Number(Number(taxValue)/ 100)*Number(amt) //tax*amt
    const totAmt = taxAmt+amt
    form.setFieldsValue({ totalAmount: totAmt })
  }
  const taxChange = (res, val) => {
    setTaxValue(val.tax)
    form.setFieldsValue({ taxValue: val.tax })
      const amt = Number(netWe)* Number(form.getFieldValue('unitPrice'))//netweight*unitprice
      const taxAmt = Number(val.tax / 100)*Number( Number(netWe)* Number(form.getFieldValue('unitPrice'))) //tax*amt
      const totAmt= taxAmt+amt
      form.setFieldsValue({ totalAmount: totAmt })
   
  }
  const onAdd = (values) => {
    console.log(values, 'oooooooooooooo');
    console.log(form.getFieldValue('productId'));
    console.log(values.productId,'oooooooooo');
    
  let array =[]
  array.push({productName:productName,packStyle:packStyleName,tax:taxValue,productId:values.productId,taxId:values.taxId,totalAmount:values.totalAmount,cases:values.cases,caseWeight:values.caseWeight,netWeight:values.netWeight,packStyleId:values.packStyleId,unitprice:values.unitPrrice})
  
    form.validateFields().then(() => {
      let updatedData = [...tableData];
      console.log(selectedItem,'ppppppppppppp');
      if (selectedItem) {
        const index = updatedData.findIndex((item) => item.id === selectedItem.id);
        if (index != -1) {
          console.log(index,'iiiiiii');
          updatedData[index] = { ...values, id: selectedItem.id }; // Update existing item with the same id
          setTableData(updatedData);
          setSelectedItem(null);
          form.resetFields();
        }
      } else {
        console.log('44444444444444');
        const newItem = { ...values, id: updatedData.length + 1 }; // Add id with indexing
        updatedData.push(newItem);
        setTableData(updatedData);
        form.resetFields();
      }
    });
    console.log(array,'pppppppppppppp666666666666');
    
  };
const onCaseWeight = (val) =>{
  const netWe = Number(val.target.value) * form.getFieldValue('cases')
  form.setFieldsValue({ netWeight: netWe})
  setNetWe(netWe)
}
const netChange = (val) => {
  const amt = val.target.value*Number(val.target.value)//netweight*unitprice
  const taxAmt = Number(Number(taxValue)/ 100)*Number(amt) //tax*amt
  const totAmt = taxAmt+amt
  form.setFieldsValue({ totalAmount: totAmt })

}
  return (
    <div>
      <Card>
        <Form layout='vertical' onFinish={onAdd} form={form}>
          <Row gutter={24}>
            <Form.Item name={'purchaseProductId'} hidden><Input /></Form.Item>
            <Form.Item name={'productName'} hidden><Input /></Form.Item>
            <Form.Item name={'packStyleName'} hidden><Input /></Form.Item>
            <Form.Item name={'taxValue'} hidden><Input /></Form.Item>
            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 8 }} lg={{ span: 5 }} xl={{ span: 4 }} >


              <Form.Item name="productId" label="Product"     >
                <Select
                  dropdownMatchSelectWidth={false}
                  placeholder='Select Product'
                  allowClear
                  showSearch
                  optionFilterProp="children"
                  onChange={(val, res) => productChange(val, res)}

                >
                  {
                    products.map((e) => {
                      return <Option key={e.productId} value={e.productId} product={e.shortCode}>{e.shortCode ? e.shortCode: "-"}</Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>
            <Col >
              <Form.Item label='Pack Style' name='packStyleId'
              // rules={[
              //   {
              //     required: true,
              //     message: 'Pack Style is required'
              //   }
              // ]}
              >
                {/* <Input placeholder="Enter Pack Style" /> */}
                <Select
                  dropdownMatchSelectWidth={false}
                  placeholder='Select Pack Style'
                  allowClear
                  showSearch
                  optionFilterProp="children"
                  onChange={(val, res) => onPackStyle(val, res)}

                >
                  {
                    packStyles.map((e) => {
                      return <Option key={e.packingMethodId} value={e.packingMethodId} pouches={e.noOfPouches} pouchPer={e.pouchesPerRow} pack={e.packingMethodName}>{e.packingMethodName}</Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>
           
            <Col>
              <Form.Item label='Case Weight' name='caseWeight'
              // rules={[
              //   {
              //     required: true,
              //     message: 'Case Weight is required'
              //   }
              // ]}
              >
                <Input placeholder="Enter Case Weight" disabled onChange={onCaseWeight}/>
              </Form.Item>
            </Col>
            <Col>
              <Form.Item label='Cases' name='cases'
              // rules={[
              //   {
              //     required: true,
              //     message: 'Cases is required'
              //   }
              // ]}
              >
                <Input placeholder="Enter Cases" onChange={(val) => casesChange(val)} />
              </Form.Item>
            </Col>
            <Col>
              <Form.Item label='Net Weight' name='netWeight'
              // rules={[
              //   {
              //     required: true,
              //     message: 'Net Weight is required'
              //   }
              // ]}
              >
                <Input placeholder="Enter Net Weight" disabled onChange={netChange}/>
              </Form.Item>
            </Col>
            <Col>
              <Form.Item label='Unit Price' name='unitPrice'
              // rules={[
              //   {
              //     required: true,
              //     message: 'Unit Price is required'
              //   }
              // ]}
              >
                <Input placeholder="Enter Unit Price" onChange={priceChange} />
              </Form.Item>
            </Col>
            <Col>
              <Form.Item label='Tax' name='taxId'
              // rules={[
              //   {
              //     required: true,
              //     message: 'Tax is required'
              //   }
              // ]}
              >
                {/* <Input placeholder="Select UOM" /> */}
                <Select
                  showSearch
                  allowClear
                  optionFilterProp="children"
                  placeholder="Select Tax"
                  onChange={(val, res) => taxChange(val, res)}
                // onChange={(value,row)=>onUomChange(value,index,row)}
                >
                  {taxes.map((e) => {
                    return (
                      <Option key={e.taxId} value={e.taxId} tax={e.taxPercentage}>{e.taxName}</Option>
                    )
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col>
              <Form.Item label='Total Amount' name='totalAmount'
              // rules={[
              //   {
              //     required: true,
              //     message: 'Total Amount is required'
              //   }
              // ]}
              >
                <Input placeholder="Enter Total Amount" disabled />
              </Form.Item>
            </Col>
          </Row>
          <Row justify="end">
            <Col span={4}>
              {!selectedItem ? (
                <Button type="primary" htmlType="submit" >
                  ADD
                </Button>
              ) : (
                <div>
                  <Button type="primary" onClick={() => onAdd(form.getFieldsValue())} style={{ backgroundColor: "green", color: "white" }}>
                    Update
                  </Button>
                  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  <Button onClick={onCancel} type="dashed" danger>Cancel</Button>
                </div>
              )}
            </Col>
          </Row>
        </Form>
        <br />
        <Col >
          {tableData.length > 0 && (
            <Table columns={columns} dataSource={tableData} rowKey={(record) => record.id} bordered scroll={{ x: true }}
              pagination={false} />
          )}
        </Col>
      </Card>
    </div>
  )
}
export default PurchasesProductForm