import React from "react"
import  { useEffect, useRef, useState } from 'react';
import {Button, Card, Col, DatePicker, Divider, Form, Input, Modal, Popconfirm, Radio, Row, Select, Table, Tooltip} from 'antd'
import './pages-finance-collections.css';
import { CheckCircleOutlined, CloseCircleOutlined, RightSquareOutlined, EyeOutlined, EditOutlined, FormOutlined,SearchOutlined ,IssuesCloseOutlined} from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import moment from 'moment';
import TextArea from "antd/lib/input/TextArea";
import { CollectionsService } from "libs/shared-services/finance/src";
import { CollectionIdRequest, SaleReq, liscenceInfoReq } from "libs/shared-models/finance/src";
import { AlertMessages } from "@gtpl/shared-utils/alert-messages";
import {PortOfEntryCodes, PortOfEntryInput} from 'libs/shared-models/sale-management/src'

export interface SaleProps {
  tab:string
  }
  
  export function Sale(props: SaleProps) {
    const [page, setPage] = useState(1);
    const [pageSize, setPageSize] = useState<number>(100);
    const [data, setData] = useState([])
    const [searchText, setSearchText] = useState("");
    const [searchedColumn, setSearchedColumn] = useState("");
    const searchInput = useRef(null);
    const [isModalVisible,setIsModalVisible] = useState<boolean>(false)
    const { Option } = Select;
    const [form] = Form.useForm();
    const [form1] = Form.useForm();
    const [infoModalVisible,setInfoModalVisible] = useState<boolean>(false)
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [selectedData, setSelectedData] = useState<any[]>([]); // New state variable to store selected data
    const service = new CollectionsService()
    const [soData, setSoData] = useState<any>()
    const [selectedRow, setSelectedRow] = useState<any>()
    const [infoData, setInfoData] = useState([])


    useEffect(() => {
      getData(props.tab)
  }, [props.tab])

  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };
  const handleReset = (clearFilters) => {
    clearFilters();
    setSearchText("");
  };
  const getData = (val) => {
    
    service.getSalePoData().then((res)=>{
      if(res.status){
setData(res.data)
      }
      else {
        setData([])
      }
    })
  }
  const getColumnSearchProps = (dataIndex: string) => ({
    filterDropdown: ({
      setSelectedKeys,
      selectedKeys,
      confirm,
      clearFilters,
    }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={searchInput}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={(e) =>
            setSelectedKeys(e.target.value ? [e.target.value] : [])
          }
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{ width: 188, marginBottom: 8, display: "block" }}
        />
        <Button
          type="primary"
          onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
          icon={<SearchOutlined />}
          size="small"
          style={{ width: 90, marginRight: 8 }}
        >
          Search
        </Button>
        <Button
          size="small"
          style={{ width: 90 }}
          onClick={() => {
            handleReset(clearFilters);
            setSearchedColumn(dataIndex);
            confirm({ closeDropdown: true });
          }}
        >
          Reset
        </Button>
      </div>
    ),
    filterIcon: (filtered) => (
      <SearchOutlined
        type="search"
        style={{ color: filtered ? "#1890ff" : undefined }}
      />
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        ? record[dataIndex]
          .toString()
          .toLowerCase()
          .includes(value.toLowerCase())
        : false,
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => searchInput.current.select());
      }
    },
    render: (text) =>
      text ? (
        searchedColumn === dataIndex ? (
          <Highlighter
            highlightStyle={{ backgroundColor: "#ffc069", padding: 0 }}
            searchWords={[searchText]}
            autoEscape
            textToHighlight={text.toString()}
          />
        ) : (
          text
        )
      ) : null,
  });
//   const data =[
//     {liscenceoiceNumber:'465esw',key:1},
//     {liscenceoiceNumber:'78gred',key:2},
//     {liscenceoiceNumber:'87f',key:3},
// ]
  const brcUpdate =(val) =>{
    setIsModalVisible(true)
    }
    const getPortName = (portOfLoading) => {
      const port = PortOfEntryCodes.find((item) => item.value === Number(portOfLoading));
      return port ? port.name : '-';
    };
  const columns: any[] = [
    {
      title: 'S No', dataIndex: 'sNo', render: (text, object, index) => {
        if (index == data.length) {
          return null;
        } else {
          return index + 1
        }
      },
      width: 60,

    },
    {
        title: 'LISCENSE NUMBER', 
       dataIndex: 'liscenceNum',
 
         render: (text: any, record: any) => { return record.liscenceNum ? record.liscenceNum : '-' } ,
         sorter: (a, b) => a.liscenceNum.localeCompare(b.liscenceNum),
       sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('liscenceNum')},
    
     {
      title: 'LISCENSE DATE', 
     dataIndex: 'liscenceDate',

       render: (text: any, record: any) => { return record.liscenceDate ? moment(record.liscenceDate).format('DD-MM-YYYY') : '-' },
       sorter: (a, b) => a.liscenceDate.localeCompare(b.liscenceDate),
     sortDirections: ['descend', 'ascend'],
    },
    {
      title: 'LISCENSE VALUE', 
     dataIndex: 'liscenceAmt',

       render: (text: any, record: any) => { return record.liscenceAmt ? record.liscenceAmt : '-' } ,
       sorter: (a, b) => a.liscenceAmt.localeCompare(b.liscenceAmt),
     sortDirections: ['descend', 'ascend'],
    ...getColumnSearchProps('liscenceAmt')},

    {
      title: 'PORT CODE',
      key: 'portCode',
      dataIndex:'portCode',
      width: '70px',
      responsive: ['md'],
      align: 'left',
      ...getColumnSearchProps('portCode'),
      sorter: (a, b) => a.portCode-b.portCode,
      sortDirections: ['descend', 'ascend'],
      render: (text, record) => getPortName(record.portCode),

  },
    //  {
    //   title: 'LISCENCE USD', 
    //  dataIndex: 'liscenceAmt',
    //    render: (text: any, record: any) => { return record.liscenceAmt ?  record.liscenceAmt : '-' },
    //    sorter: (a, b) => a.liscenceAmt.localeCompare(b.liscenceAmt),
    //  sortDirections: ['descend', 'ascend'],
    // },
   
     {
        title: `Iinvoice Info`,
        dataIndex: 'action',
        fixed: 'right',
        render: (text, rowData) => {
        return(
            <>
            <EyeOutlined title="Update" style={{ color: 'green' }} onClick={()=>scriptInfo(rowData)} />
            </> )
       }
      },
      
     
  ]
  const infoColumns: any[] = [
    {
      title: 'S No', dataIndex: 'sNo', render: (text, object, index) => {
        if (index == infoData.length) {
          return null;
        } else {
          return index + 1
        }
      },
      width: 60,

    },
    {
        title: 'PO number', 
       width: 200,
       dataIndex: 'poNum',
 
         render: (text: any, record: any) => { return record.poNum ? record.poNum : '-' } ,
         sorter: (a, b) => a.poNum.localeCompare(b.poNum),
       sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('poNum')},
    {
       title: 'Invoice Number', 
      width: 200,
      dataIndex: 'invoiceNumber',

        render: (text: any, record: any) => { return record.invoiceNumber ? record.invoiceNumber : '-' } ,
        sorter: (a, b) => a.invoiceNumber.localeCompare(b.invoiceNumber),
      sortDirections: ['descend', 'ascend'],
     ...getColumnSearchProps('invoiceNumber')},
     
    {
       title: 'SHIPPING BILL NO.', 
      width: 200,
      dataIndex: 'shippingBillNo',

        sorter: (a, b) => a.shippingBillNo.localeCompare(b.shippingBillNo),
      sortDirections: ['descend', 'ascend'],
     },
     {
      title: 'SHIPPING BILL DATE', 
     width: 200,
     dataIndex: 'shippingBillDate',

       render: (text: any, record: any) => { return record.shippingBillDate ? moment(record.shippingBillDate).format('DD-MM-YYYY') : '-' },
       sorter: (a, b) => a.shippingBillDate.localeCompare(b.shippingBillDate),
     sortDirections: ['descend', 'ascend'],
    },
    {
       title: 'LEO DATE', 
       width: 200,
       dataIndex: 'eta',
         render: (text: any, record: any) => { return record.eta ? moment(record.eta).format('DD-MM-YYYY') : '-' },
         sorter: (a, b) => a.eta.localeCompare(b.eta),
       sortDirections: ['descend', 'ascend'],
     },
     {
        title: 'NET WEIGHT', 
       width: 200,
       dataIndex: 'qty',
         render: (text: any, record: any) => { return record.qty ?  record.qty : '-' },
         sorter: (a, b) => a.qty.localeCompare(b.qty),
       sortDirections: ['descend', 'ascend'],
      },
     {
      title: 'INV VALUE USD', 
     width: 200,
     dataIndex: 'invAmt',
       render: (text: any, record: any) => { return record.invAmt ?  record.invAmt : '-' },
       sorter: (a, b) => a.invAmt.localeCompare(b.invAmt),
     sortDirections: ['descend', 'ascend'],
    },
   
    {
       title: 'FOB VALUE', 
      width: 100,
      dataIndex: 'fob',

        render: (text: any, record: any) => { return record.fob ? record.fob : '-' },
        sorter: (a, b) => a.fob.localeCompare(b.fob),
      sortDirections: ['descend', 'ascend'],
    //  ...getColumnSearchProps('qtyStock')
     },
     {
      title: 'FOB VALUE(INR)', 
      width: 100,
      dataIndex: 'fobValueInr',
      render: (text: any, record: any) => {
        return record.fobValueInr ? Number(record.fobValueInr).toFixed(2) : '-';
      },
      sorter: (a, b) => a.fobValueInr - b.fobValueInr, 
      sortDirections: ['descend', 'ascend'],
    },
    
    {
      title: 'BRC Number', 
     width: 200,
     dataIndex: 'brcNo',
       render: (text: any, record: any) => { return record.brcNo ?  record.brcNo : '-' },
       sorter: (a, b) => a.brcNo.localeCompare(b.brcNo),
     sortDirections: ['descend', 'ascend'],
    },
    {
      title: 'BRC DATE', 
      width: 200,
      dataIndex: 'brcDate',
        render: (text: any, record: any) => { return record.brcDate ? moment(record.brcDate).format('DD-MM-YYYY') : '-' },
        sorter: (a, b) => a.brcDate.localeCompare(b.brcDate),
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: 'BRC VALUE', 
     width: 100,
     dataIndex: 'brcRealisedValue',

       render: (text: any, record: any) => { return record.brcRealisedValue ? record.brcRealisedValue : '-' },
       sorter: (a, b) => a.brcRealisedValue.localeCompare(b.brcRealisedValue),
     sortDirections: ['descend', 'ascend'],
   //  ...getColumnSearchProps('brcRealisedValue')
    },
     {
        title: 'Buyer', 
       width: 200,
       dataIndex: 'buyer',
         render: (text: any, record: any) => { return record.buyer ?  record.buyer : '-' },
         sorter: (a, b) => a.buyer.localeCompare(b.buyer),
       sortDirections: ['descend', 'ascend'],
      },
    {
        title: 'CHA', 
       width: 100,
       dataIndex: 'cha',
 
        //  render: (text: any, record: any) => { return record.cha ? record.cha : '-' },
        //  sorter: (a, b) => a.cha.localeCompare(b.cha),
       sortDirections: ['descend', 'ascend'],
     //  ...getColumnSearchProps('qtyStock')
      },
      {
        title: 'Port Code',
        dataIndex: 'port',
        // render: (text, record) => {record.port ?PortOfEntryInput.find((e)=>e.value ===record.port).name : "-"},
        render: (text, record) => {
         
          return(getPortName(record.port))},
        width:"50px"
      },
       {
        title: 'SCROLL DATE', 
        width: 200,
        dataIndex: 'scrollDate',
          render: (text: any, record: any) => { return record.scrollDate ? moment(record.scrollDate).format('DD-MM-YYYY') : '-' },
          sorter: (a, b) => a.scrollDate.localeCompare(b.scrollDate),
        sortDirections: ['descend', 'ascend'],
      },
       {
        title: 'SCROLL No', 
       width: 100,
       dataIndex: 'scrollNo',
 
         render: (text: any, record: any) => { return record.scrollNo ? record.scrollNo : '-' },
         sorter: (a, b) => a.scrollNo.localeCompare(b.scrollNo),
       sortDirections: ['descend', 'ascend'],
     //  ...getColumnSearchProps('qtyStock')
      },
      {
        title: 'RODTEP(Ice Gate)', 
       width: 100,
       dataIndex: 'rodtep',
 
         render: (text: any, record: any) => { return record.rodtep ? record.rodtep : '-' },
         sorter: (a, b) => a.rodtep.localeCompare(b.rodtep),
       sortDirections: ['descend', 'ascend'],
     //  ...getColumnSearchProps('qtyStock')
      },
    //   {
    //     title: 'BRC Amount(total)', 
    //    width: 100,
    //    dataIndex: 'brcAmt',
 
    //      render: (text: any, record: any) => { return record.brcAmt ? record.brcAmt : '-' },
    //      sorter: (a, b) => a.brcAmt.localeCompare(b.brcAmt),
    //    sortDirections: ['descend', 'ascend'],
    //  //  ...getColumnSearchProps('qtyStock')
    //   },
    
      
     
  ]
  // const infoColumns: any[] = [
  //   {
  //     title: 'S No', dataIndex: 'sNo', render: (text, object, index) => {
  //       if (index == data.length) {
  //         return null;
  //       } else {
  //         return index + 1
  //       }
  //     },
  //     width: 60,

  //   },
  //   {
  //       title: 'IMRN NO', 
  //      width: 200,
  //      dataIndex: 'imrnNum',
 
  //        render: (text: any, record: any) => { return record.imrnNum ? record.imrnNum : '-' } ,
  //        sorter: (a, b) => a.imrnNum.localeCompare(b.imrnNum),
  //      sortDirections: ['descend', 'ascend'],
  //     ...getColumnSearchProps('imrnNum')},
  //     {
  //       title: 'BRC No', 
  //      width: 200,
  //      dataIndex: 'brcNo',
  
  //        render: (text: any, record: any) => { return record.brcNo ? moment(record.brcNo).format('DD-MM-YYYY') : '-' },
  //        sorter: (a, b) => a.brcNo.localeCompare(b.brcNo),
  //      sortDirections: ['descend', 'ascend'],
  //     },
  //    {
  //     title: 'BRC DATE', 
  //    width: 200,
  //    dataIndex: 'brcDate',

  //      render: (text: any, record: any) => { return record.brcDate ? moment(record.brcDate).format('DD-MM-YYYY') : '-' },
  //      sorter: (a, b) => a.brcDate.localeCompare(b.brcDate),
  //    sortDirections: ['descend', 'ascend'],
  //   },
    
  //    {
  //     title: 'BMR VALE (USD)', 
  //    width: 200,
  //    dataIndex: 'brcVal',
  //      render: (text: any, record: any) => { return record.brcVal ?  record.brcVal : '-' },
  //      sorter: (a, b) => a.brcVal.localeCompare(b.brcVal),
  //    sortDirections: ['descend', 'ascend'],
  //   },
   
     
  // ]
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log("selectedRowKeys changed: ", newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const hasSelected = selectedRowKeys.length > 0;

  let createdUser = "";
  const cancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  const save = (val) =>{
    let request =[]
    selectedRowKeys.map((e)=> request.push(new liscenceInfoReq(e)))
    // const req = new CollectionIdRequest()
    // const request = new BrcReq(val.brcNo,val.brcValue,createdUser,soData.poNum,val.brcDate,val.irmNo,soData.scrollNo,soData.scrollDate,soData.receivedAmt,soData.buyerId,soData.soId,soData.invoiceNumber,soData.eta)
    const req = new SaleReq(request,createdUser,val.invoiceNumber,val.invoiceDate,val.saleAmount,val.finalSaleAmount,val.discountRate,val.customer)
    
    service.createSale(req).then((res)=>{
      if(res.status){
        AlertMessages.getSuccessMessage(res.internalMessage)
        // console.log('oooooooooooooooooooooooooftrgc');
        form.resetFields()
        setIsModalVisible(false)
        getData(props.tab)
        setSelectedRowKeys([])
      }
    })
  }

  
const start = () => {
    
  const selectedRowsData = selectedRowKeys.map((key) => data.find((item) => item.liscenceNum === key));
  const totalAmount = selectedRowsData.reduce((sum, row) => sum +Number(row.liscenceAmt), 0);
  // selectedRow(totalAmount)
  form.setFieldsValue({'saleAmount':totalAmount})
  setIsModalVisible(true);
};
const scriptInfo =(val) =>{
  setInfoModalVisible(true)
  const req = new CollectionIdRequest(val.collectionId,val.liscenceNum)
  service.getLicsenseInfo(req).then((res)=>{
    if(res.status){
    setInfoData(res.data)
    }
  })
  }
const infoCancel = () =>{
  setInfoModalVisible(false)
}
const DiscountChange = (val) => {
  const saleAmount = Number(form.getFieldValue('saleAmount'));
  const discount = Number(val.target.value);
  const finalAmt = saleAmount - ((discount / 100) * saleAmount);
  form.setFieldsValue({'finalSaleAmount':finalAmt.toFixed(3)})

}
    return (
        <>
        <Table rowSelection={rowSelection} columns={columns} dataSource={data} rowKey={(record) => record.liscenceNum} size="small"/>
         <div style={{ marginBottom: 16 }}>
        <Button type="primary" onClick={start} disabled={!hasSelected}>
         Create Sale
        </Button>
        
         </div>
        <Modal width={'90%'} footer={null} visible={isModalVisible} style={{ background: '#69c0ff', textAlign: 'center', color: 'white' }} onCancel={cancel}>
            <Card size="small" title={<span style={{ color: 'white' }} >Sale</span>}
            style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
            >
                <Form form={form} onFinish={save}>
                    <Row gutter={24}>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 6 }} xl={{ span: 8 }}>
          <Form.Item label='Invoice Number' name='invoiceNumber' rules={[{ required: true, message: 'Missing Invoice Number' }]}>
                <Input placeholder="Enter Invoice Number"  />
              </Form.Item>
          </Col>
           <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 6 }} xl={{ span: 8 }}>
          <Form.Item label='Invoice Date' name='invoiceDate' rules={[{ required: true, message: 'Missing Invoice Date' }]}>
          <DatePicker style={{width:'100%'}}/>
          </Form.Item>
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 6 }} xl={{ span: 8 }}>
          <Form.Item label='Customer' name='customer' rules={[{ required: true, message: 'Missing Customer' }]}>
                <Input placeholder="Enter Customer"  />
              </Form.Item>
          </Col> 
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 6 }} xl={{ span: 8 }}>
          <Form.Item label='Sale Amount' name='saleAmount' rules={[{ required: true, message: 'Missing Sale Amount' }]}>
                <Input placeholder="Enter Sale Amount"  disabled />
              </Form.Item>
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 6 }} xl={{ span: 8 }}>
          <Form.Item label='Discount Rate' name='discountRate' rules={[{ required: true, message: 'Missing Discount Rate' }]}>
                <Input placeholder="Enter Discount Rate"  onChange={DiscountChange}/>
              </Form.Item>
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 6 }} xl={{ span: 8 }}>
          <Form.Item label='Final Sale Amount' name='finalSaleAmount' rules={[{ required: true, message: 'Missing Final Sale Amount' }]}>
                <Input placeholder="Enter Final Sale Amount" disabled />
              </Form.Item>
          </Col>
          
                      
                    </Row>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
                        <Form.Item>
                            <Button type='primary' htmlType='submit'>Submit</Button>
                        </Form.Item>
                    </Col>
                </Form>
            </Card>
        </Modal>
        <Modal width={'90%'} footer={null} visible={infoModalVisible} style={{ background: '#69c0ff', textAlign: 'center', color: 'white' }} onCancel={infoCancel}>
          <Card size="small" title={<span style={{ color: 'white' }} >Script Generation Info</span>}
            style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
            >
       <Table columns={infoColumns} dataSource={infoData} size="small" scroll={{x:'max-content'}} pagination={false}/>   
       </Card>    
       </Modal>
        </>
    )
  }
  export default Sale
   