import React from "react"
import  { useEffect, useRef, useState } from 'react';
import {Button, Card, Col, DatePicker, Divider, Form, Input, Modal, Popconfirm, Radio, Row, Select, Space, 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, PurchasesProductService } from "libs/shared-services/finance/src";
import { BrcReq, PaymentTypeReq } from "libs/shared-models/finance/src";
import { AlertMessages } from "@gtpl/shared-utils/alert-messages";
import {PortOfEntryCodes, PortOfEntryInput} from 'libs/shared-models/sale-management/src'
import {  SaleOrderService } from '@gtpl/shared-services/sale-management';
export interface BrcGateProps {
  tab:string
  }
  
  export function BRC(props: BrcGateProps) {
    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 [paymentModalVisible,setPaymentModalVisible] = useState<boolean>(false)
    const service = new CollectionsService()
    const [soData, setSoData] = useState<any>()
    const [years,setYears] = useState<any[]>([])
      const invoiceDataService = new SaleOrderService;
        const [factoriesData, setFactoriesData] = useState([]);
          const purchaseService = new PurchasesProductService()

      
    useEffect(() => {
      getData(props.tab)
      getAllFinancialYear()
      getAllCompanyNames()
  }, [props.tab])
  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };
  const handleReset = (clearFilters) => {
    clearFilters();
    setSearchText("");
  };

        const getAllCompanyNames = () => {
    purchaseService.getAllCompanys().then((res) => {
        if (res.status) {
            setFactoriesData(res.data)
        }
    })
}

 const getAllFinancialYear  = () => {
    invoiceDataService.getAllFinancialYear().then(res => {
      if (res.status) {
        setYears(res.data);
      } else {
        if (res.intlCode) {
          setYears([]);
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      setYears([]);
      AlertMessages.getErrorMessage(err.message);
    })
  }
  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 getData = (val) => {
    const req = new PaymentTypeReq(props.tab)
           
            if(form.getFieldValue('financialYear') !== undefined){
              req.financeYear = form.getFieldValue('financialYear')
            }
              if(form.getFieldValue('unit') !== undefined){
          req.unitId = form.getFieldValue('unit')
        }
    service.getBrcPoData(req).then((res)=>{
      if (res.status) {
        setData(res.data); 
      } else {
        setData([]);       
      }
    }).catch((err) => {
      console.error('Error fetching data:', err);
      setData([]);
    });
  }
  // const data =[{
  //   invoiceNumber:'465esw'
  // }]
  const brcUpdate =(val) =>{
    setIsModalVisible(true)
    setSoData(val)
    }
    const getPortName = (portOfLoading) => {
      const port = PortOfEntryCodes.find((item) => Number(item.value) === Number(portOfLoading));
      
      return port ? port.name : portOfLoading;
    };
  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: '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: '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 || ''), // safer string comparison
       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) => getPortName(record.port),
        sorter: (a, b) => (a.port || '').localeCompare(b.port || ''), // safer string comparison
        sortDirections: ['descend', 'ascend'],
        width:"50px"
        
      },
       {
        title: 'SCROLL DATE', 
        width: 300,
        dataIndex: 'scrollDate',
        sorter: (a, b) => a.scrollDate?.localeCompare(b.scrollDate),
          render:(text,record) => {
            return(
              <>
              {record.scrollDate ? moment(record.scrollDate).format('DD-MM-YYYY') : '-'}
              </>
            )
          }
      },
       {
        title: 'SCROLL No', 
       width: 200,
       dataIndex: 'scrollNo',
       sorter: (a, b) => a.scrollNo?.localeCompare(b.scrollNo),
       render: (value, record) => (record.scrollNo ? record.scrollNo : "-"),
       sortDirections: ["descend", "ascend"] ,
     //  ...getColumnSearchProps('qtyStock')
      },
      {
        title: 'RODTEP(Ice Gate)', 
       width: 100,
       dataIndex: 'rodtep',
        fixed:'right',
         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 Update`,
        // dataIndex: 'action',
        fixed: 'right',
        render: (text, rowData) => {
          const exportReceivablesCount = Number(rowData.exportReceivablesCount);
    const rodtepCount = Number(rowData.rodtepCount);
// console.log(exportReceivablesCount,rodtepCount,'000000');
let isDisable
let isPartialDisable
if(exportReceivablesCount== rodtepCount){
  isDisable = true
  isPartialDisable =true
}else {
  isDisable = false
  isPartialDisable = false
}

    // const isPartialUpdateDisabled = (exportReceivablesCount - 1 === rodtepCount) 
    // const isUpdateDisabled = exportReceivablesCount === rodtepCount;
          // console.log(isPartialDisable,isDisable,rowData.poNum);
          
    return (
        <>
        <Button title="BRC Update" 
                onClick={() => brcUpdate(rowData)} 
                // disabled={ isPartialDisable }  
                >
            <FormOutlined 
                
            />
            </Button>
            {/* <Divider type="vertical"/>
            <Button title="Update" 
                style={{ color: 'green' }} 
                onClick={() => brcUpdate(rowData)} 
                disabled={isDisable} >
            <FormOutlined 
                
            />
            </Button> */}
        </>
    );}
      //   return(
      //       <>
      //       {/* {rowData.exportReceivablesCount === rowData.rodtepCount} */}
      //       <FormOutlined title="Partial Update"  onClick={() => console.log('not update')} disabled={Number(rowData.exportReceivablesCount-1) == rowData.rodtepCount || rowData.exportReceivablesCount === rowData.rodtepCount?true:false}/>
      //       <Divider type="vertical"/>
      //       <FormOutlined title="Update" style={{ color: 'green' }} onClick={() => brcUpdate(rowData)} disabled={rowData.exportReceivablesCount == rowData.rodtepCount?true:false} />
      //       </> )
      //  }
      },
      
     
  ]
  let createdUser="";
  // let unitId = localStorage.getItem("unit_id")

  const cancel = () =>{
    setIsModalVisible(false)
    form.resetFields()
  }
 
  const save = (val) =>{
    const req = new BrcReq(val.brcNo,val.brcValue,createdUser,Number(soData.unitId),soData.poNum,val.brcDate,val.irmNo,soData.scrollNo,soData.scrollDate,soData.receivedAmt,soData.buyerId,soData.soId,soData.invoiceNumber,soData.eta,soData.rodtepCount,soData.exportReceivablesCount)
    service.brcUpdate(req).then((res)=>{
      if(res.status){
        AlertMessages.getSuccessMessage(res.internalMessage)
        // console.log('oooooooooooooooooooooooooftrgc');
        form.resetFields()
        getData(props.tab)
        setIsModalVisible(false)
      }
    })
  }
  const onReset = () => {
    form.resetFields();
  }
  const search =() =>{
    getData(props.tab)
   }
    return (
        <>
         <Form form={form} onFinish={search}>
                                      <Row gutter={24}>
                <Col xs={{span:24}} sm={{span:24}} md={{span:6}} lg={{span:6}} xl={{span:6}}>
                                  <Form.Item name="unit" label="Unit" rules={[{ required: false }]}>
                                        <Select
                                            showSearch
                                            optionFilterProp="children"
                                            filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                            placeholder=" Select Unit"
                                            allowClear
                                            dropdownMatchSelectWidth={false}
                                        >
                                              {factoriesData.map(dropData => {
                                                console.log(factoriesData,'factoriesDatafactoriesDatafactoriesData')
                                                return <Option value={dropData.companyId}>{dropData.company}</Option>
                                            })}
                                        </Select>
                                        </Form.Item>
                    
                    
                    
                                        </Col >
                                          <Col xs={24} sm={12} md={6} lg={6} xl={6}>
                              <Form.Item name="financialYear" label="Financial Year">
                                <Select
                                  showSearch
                                  placeholder="Select Financial Year"
                                  optionFilterProp="children"
                                  allowClear
                                >
                                  {years.filter(year => year.financialYear !== null).map((y: any) => (
                                    <Select.Option key={y.financialYear} value={y.financialYear}>
                                      {y.financialYear}
                                    </Select.Option>
                                  ))}
                                </Select>
                              </Form.Item>
                            </Col>
                                          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
                                          <Form.Item>
                              <Space>
                                <Button type="primary" htmlType="submit">
                                  Search
                                </Button>
                                <Button type="primary" htmlType="reset" onClick={() => onReset()}>
                                  Reset
                                </Button>
                              </Space>
                            </Form.Item>
                                          </Col>
                                      </Row>
                                  </Form>
        <Table
         columns={columns} 
         dataSource={data} 
        //  scroll={{x:'max-connected',y:1500}} 
         size="small"/>
        <Modal width={'90%'} footer={null} visible={isModalVisible} style={{ background: '#69c0ff', textAlign: 'center', color: 'white' }} 
            onCancel={cancel}>
            <Card size="small" title={<span style={{ color: 'white' }} >BRC Update</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='IRM NO' name='irmNo' rules={[{ required: true, message: 'Missing IRM No' }]}>
                <Input placeholder="Enter IRM NO"  />
              </Form.Item>
          </Col>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 6 }} xl={{ span: 8 }}>
          <Form.Item label='BRC NO' name='brcNo' rules={[{ required: true, message: 'Missing BRC No' }]}>
                <Input placeholder="Enter BRC No"  />
              </Form.Item>
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 6 }} xl={{ span: 8 }}>
          <Form.Item label='BRC Date' name='brcDate' rules={[{ required: true, message: 'Missing BRC 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='BRC Value (USD)' name='brcValue'>
                                <Input placeholder="Enter BRC Value" />
                            </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>
       
        </>
    )
  }
  export default BRC
   