import { RmInvoiceReportReq } from '@gtpl/shared-models/production-management'
import { RMGrnService } from '@gtpl/shared-services/raw-material-procurement'
import { AlertMessages } from '@gtpl/shared-utils/alert-messages'
import { Button, Card, Col, DatePicker, Form, Input, Row, Select, Table, Tag } from 'antd'
import moment from 'moment'
import React, { useEffect, useRef, useState } from 'react'
import { UndoOutlined,SearchOutlined,DownloadOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import { Excel } from 'antd-table-saveas-excel'
import { TeamRequest } from '@gtpl/shared-models/hrms'



const GrnInvoiceReport = () => {
const service=new RMGrnService()
const [grnInvoiceReport,setGrnInvoiceReport]=useState([])
const [farmers, setFarmers] = useState([]);
const [batches, setBatches] = useState([]);
const [category, setCategory] = useState([]);
const [harvestType, setHarvestType] = useState([]);
const { RangePicker } = DatePicker;
const [form] = Form.useForm();
const [searchText, setSearchText] = useState('');
const [searchedColumn, setSearchedColumn] = useState('');
const searchInput = useRef(null);
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState<number>(null);
const [isVisible,setIsVisible]=useState<boolean>(false)


useEffect(()=>{
    getGrnInvoiceReport() 
    getAll()
},[])

const getAll = () =>{

  service.getBatchNumbers ().then((res)=>{
    if(res.status){
        setBatches(res.data)
    }
}) 
service.getFarmers ().then((res)=>{
  if(res.status){
      setFarmers(res.data)
  }
})
service.getCategorys ().then((res)=>{
    if(res.status){
        setCategory(res.data)
    }
  })
  service.getHarvestType ().then((res)=>{
    if(res.status){
        setHarvestType(res.data)
    }
  })
  }

const getGrnInvoiceReport=()=>{
    const req=new RmInvoiceReportReq()
    if (form.getFieldValue('invoiceDate') !== undefined) {
        req.grnfromDate = (form.getFieldValue('invoiceDate')[0]).format('YYYY-MM-DD')
      }
      if (form.getFieldValue('invoiceDate') !== undefined) {
      req.grnToDate = (form.getFieldValue('invoiceDate')[1]).format('YYYY-MM-DD')
      }
      if (form.getFieldValue('batchNum') !== undefined) {
        req.batchNum=form.getFieldValue('batchNum')
        }
        if (form.getFieldValue('farmer') !== undefined) {
          req.farmer=form.getFieldValue('farmer')
          }
          if (form.getFieldValue('category') !== undefined) {
            req.category=form.getFieldValue('category')
            }
            if (form.getFieldValue('harvestType') !== undefined) {
                req.harvestType=form.getFieldValue('harvestType')
                }
    service.getRmInvoiceReport(req).then((res)=>{
        if(res.status){
            setGrnInvoiceReport(res.data) 
        }else{
            setGrnInvoiceReport([])
            AlertMessages.getErrorMessage(res.internalMessage);
        }
    })
}

function handleSearch(selectedKeys, confirm, dataIndex) {
  confirm();
  setSearchText(selectedKeys[0]);
  setSearchedColumn(dataIndex);
};
function handleReset(clearFilters) {
  clearFilters();
  setSearchText('');
};
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 onClick={() => handleReset(clearFilters)} size="small" style={{ width: 90 }}>
              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 onFinish = (val) => {
    getGrnInvoiceReport()
    setIsVisible(true)
    };
  
    const onReset = () => {
      form.resetFields();
      // getGrnInvoiceReport();
      setIsVisible(false)
    };

const Columns:any=[
  {
    title: 'S.No',
    width:"20px",
    render: (text, object, index) => (page - 1) * pageSize + (index + 1)

  },
    {   
        title:"Date",
        dataIndex:"invoiceDate",
        // ...getColumnSearchProps('invoiceDate'),
        sorter: (a, b) => moment(a.invoiceDate).unix() - moment(b.invoiceDate).unix(),
        sortDirections: ['descend', 'ascend'],
        render: (date) => moment(date).format('DD-MM-YYYY'),
    },
    {
        title:"Farmer Name",
        dataIndex:"farmerName",
        sorter: (a, b) => a.farmerName?.localeCompare(b.farmerName),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('farmerName')
    },
        
    {
        title:"Bill To Type",
        dataIndex:"billToType",
        sorter: (a, b) => a.billToType?.localeCompare(b.billToType),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('billToType'),
        render: (value, record) => record?.billToType ?record?.billToType :  "-",
    },
       {
        title:"Bill To",
        dataIndex:"billTo",
        sorter: (a, b) => a.billTo?.localeCompare(b.billTo),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('billTo'),
        render: (value, record) => record?.billTo ?record?.billTo :  "-",

    },
    {
        title:"Batch No",
        dataIndex:"batchNumber",
        sorter: (a, b) => a.batchNumber?.localeCompare(b.batchNumber),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('batchNumber')
    },
     {
        title:"Product",
        dataIndex:"productName",
        sorter: (a, b) => a.productName?.localeCompare(b.productName),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('productName')
    },
    {
        title:"Category",
        dataIndex:"category",
        sorter: (a, b) => a.category?.localeCompare(b.category),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('category')
    },
    {
        title:"Place",
        dataIndex:"place",
     ...getColumnSearchProps('place'),
      render: (e, val) => (val.place ? val.place : '-')

    },
    {
        title:"Count",
        dataIndex:"count",
        sorter: (a, b) => a.count?.localeCompare(b.count),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('count'),
        render: (text, record) => {
          const qty = Number(record.count);
          return !isNaN(qty) 
              ? qty % 1 === 0 
                  ? qty.toFixed(0) 
                  : qty.toFixed(2)
              : '-';
      }
    },
    {
      title: "Purchase / Plant Weight(In Kgs)",
      dataIndex: "totalQuantity",
      sorter: (a, b) => a.totalQuantity - b.totalQuantity, 
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('totalQuantity'),
      render: (value) => {
          const formattedValue = new Intl.NumberFormat('en-IN', { 
              minimumFractionDigits: 0, 
              maximumFractionDigits: 2  
          }).format(parseFloat(value));
          return formattedValue;
      },
  },
  
    {
        title:"Good Price",
        dataIndex:"unitPrice",
        sorter: (a, b) => a.unitPrice?.localeCompare(b.unitPrice),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('unitPrice'),
        render: (value) => parseFloat(value)?.toString(),

    },
    // {
    //     title:"Ice Rate",
    //     dataIndex:"iceRate",
    //     ...getColumnSearchProps('iceRate'),
    //     sorter: (a, b) => a.iceRate - b.iceRate,
    //     sortDirections: ['descend', 'ascend'],
    // },
    {
      title: "Invoice Amount",
      dataIndex: "totalAmount",
      render: (text, record) => {
          // const unitPrice = parseFloat(record.unitPrice) || 0;
          // const iceRate = parseFloat(record.iceRate) || 0;
          // const totalQuantity = parseFloat(record.totalQuantity) || 0;
          // const totalAmount = totalQuantity * (unitPrice );
          
          return new Intl.NumberFormat('en-IN', { minimumFractionDigits: 0, maximumFractionDigits: 2 })?.format(record.totalAmount);
        },
        sorter: (a, b) => a.totalAmount?.localeCompare(b.totalAmount),
        sortDirections: ['descend', 'ascend'],
  },
  {
    title: " TDS Amount",
    dataIndex: "tdsAmount",
    render: (text, record) => { 
        return new Intl.NumberFormat('en-IN', { minimumFractionDigits: 0, maximumFractionDigits: 2 })?.format(record.tdsAmount);
      },
      sorter: (a, b) => a.tdsAmount?.localeCompare(b.tdsAmount),
      sortDirections: ['descend', 'ascend'],
},
{
  title: "Final Amount",
  dataIndex: "finalAMount",
  render: (text, record) => { 
      return new Intl.NumberFormat('en-IN', { minimumFractionDigits: 0, maximumFractionDigits: 2 })?.format(record.finalAMount);
    },
    sorter: (a, b) => a.finalAMount?.localeCompare(b.finalAMount),
    sortDirections: ['descend', 'ascend'],
},
    
    {
        title:"Harvest Type",
        dataIndex:"harvestType",
        sorter: (a, b) => a.harvestType?.localeCompare(b.harvestType),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('harvestType')
    },
    {
        title:"Supervisor",
        dataIndex:"supervisorName",
        sorter: (a, b) => a.supervisorName?.localeCompare(b.supervisorName),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('supervisorName'),
        render: (e, val) => (val.supervisorName ? val.supervisorName : '-')
    },
    // {
    //     title:"Vehicle Type",
    //     dataIndex:"vehicleType",
    //     sorter: (a, b) => a.vehicleType?.localeCompare(b.vehicleType),
    //     sortDirections: ['descend', 'ascend'],
    //     ...getColumnSearchProps('vehicleType'),
    //     render: (e, val) => (val.vehicleType ? val.vehicleType : '-')

    // },
       {
        title:"Vehicle Number",
        dataIndex:"vehicleNumber",
        sorter: (a, b) => a.vehicleNumber?.localeCompare(b.vehicleNumber),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('vehicleNumber'),
        render: (e, val) => (val.vehicleNumber ? val.vehicleNumber : '-')

    },
]
const excelDataReport :any[]=  [
  {
    title: 'S No',
    dataIndex: 'sno',
    render: (text, record) => (record.count === 'Total' ? '' : text),
  },
    {   
        title:"Date",
        dataIndex:"invoiceDate",
        // ...getColumnSearchProps('invoiceDate'),
        sorter: (a, b) => moment(a.invoiceDate).unix() - moment(b.invoiceDate).unix(),
        sortDirections: ['descend', 'ascend'],
        render: (date) => (date ? moment(date).format('DD-MM-YYYY') : undefined),
    },
    {
        title:"Farmer Name",
        dataIndex:"farmerName",

    },
        {
        title:"Bill To Type",
        dataIndex:"billToType",
        render: (text) => (text ? text : '-'),
    },

     {
        title:"Bill To",
        dataIndex:"billTo",
        render: (text) => (text ? text : '-'),
    },
    {
        title:"Batch No",
        dataIndex:"batchNumber",

    },
     {
        title:"Product",
        dataIndex:"productName",

    },
    {
        title:"Category",
        dataIndex:"category",
    
     
    },
    {
        title:"Place",
        dataIndex:"place",
        render:(text,record)=>{
       const farmerAddress=record.place?record.place:"-"
       return farmerAddress;
        },
      
    },
    {
        title:"Count",
        dataIndex:"count",
 
    },
    {
        title:"Purchase / Plant Weight",
        dataIndex:"totalQuantity",

    },
    {
        title:"Good Price",
        dataIndex:"unitPrice",

    },
    {
        title:"Ice Rate",
        dataIndex:"iceRate",

    },
    {
      title: "Invoice Amount",
      dataIndex: "finalTotalAmount",
      
    },
    {
      title: " TDS Amount",
      dataIndex: "finaltdsAmount",
      
    },    {
      title: "Final Amount",
      dataIndex: "completeAMount",
      
    },
    
    {
        title:"Harvest Type",
        dataIndex:"harvestType",
       
    },
    {
        title:"Supervisor",
        dataIndex:"supervisorName",
        render: (e, val) => (val.supervisorName ? val.supervisorName : '-'),

    },
    // {
    //     title:"Vehicle Type",
    //     dataIndex:"vehicleType",
    //     render: (e, val) => (val.vehicleType ? val.vehicleType : '-'),

    // },
    {
        title:"Vehicle Number",
        dataIndex:"vehicleNumber",
        render: (e, val) => (val.vehicleNumber ? val.vehicleNumber : '-'),

    },
];
const exportExcel = () => {
  let totalWeight = 0;
  let totalAmt = 0;
  let tdsAmt = 0;
  let finalAmt = 0;

  const exportData = grnInvoiceReport.map((record, index) => {
    const unitPrice = parseFloat(record.unitPrice) || 0;
    const iceRate = parseFloat(record.iceRate) || 0;
    const totalQuantity = parseFloat(record.totalQuantity) || 0;
    const totalAmount = parseFloat(record.totalAmount)
    const tdsAmount= parseFloat(record.tdsAmount) || 0;
    const finalAMount = parseFloat(record.finalAMount) || 0;
    totalWeight += parseFloat(record.totalQuantity) || 0;
    totalAmt += totalAmount;
    tdsAmt += tdsAmount;
    finalAmt += finalAMount;
console.log(totalWeight,'oooo');

    return {
      ...record,
      sno: index + 1,
      finalTotalAmount: totalAmount.toFixed(2),
      finaltdsAmount: tdsAmount.toFixed(2),
      completeAMount: finalAMount.toFixed(2),
    };
  });

  const totalRow = {
    sno: undefined,
    invoiceDate: undefined,
    farmerName: undefined,
    batchNumber: undefined,
    category: undefined,
    place: undefined,
    count: 'Total',
    totalQuantity: totalWeight.toFixed(2),
    unitPrice: undefined,
    iceRate: undefined,
    finalTotalAmount: totalAmt.toFixed(2),
    finaltdsAmount: tdsAmt.toFixed(2),
    completeAMount: finalAmt.toFixed(2),
    harvestType: undefined,
    supervisorName: undefined,
  };

  // Append total row
  exportData.push(totalRow);

  const excel = new Excel();
  excel
    .addSheet('RM Invoice Report')
    .addColumns(excelDataReport)
    .addDataSource(exportData, { str2num: true })
    .saveAs('rm-Invoice-report.xlsx');
};
  return (
    <div>
           <Card title={<span style={{color:'white'}}>RM Invoice Report</span>}
    style={{textAlign:'center'}} headStyle={{backgroundColor: '#69c0ff', border: 0 }}
    extra={
      <div>
        <Button icon={<DownloadOutlined />} onClick={() => { exportExcel(); }} style={{marginRight:30}}>
          Get Excel
        </Button></div>}
         >
        <Form form={form} onFinish={onFinish} layout='vertical'>
            <Row gutter={24}>
            <Col xs={24} sm={12} md={8} lg={6} xl={6}>
            <Form.Item name="batchNum" label="Batch Number">
              <Select
                showSearch
                placeholder="Select Batch Number"
                optionFilterProp="children"
                allowClear
              >
                {batches.map((qc: any) => (
                  <Select.Option key={qc.batch_number} value={qc.batch_number}>
                    {qc.batch_number}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
            </Col>
            <Col xs={24} sm={12} md={8} lg={6} xl={6}>
            <Form.Item name="farmer" label="Farmer">
              <Select
                showSearch
                placeholder="Select Farmer"
                optionFilterProp="children"
                allowClear
              >
                {farmers.map((qc: any) => (
                  <Select.Option key={qc.farmer} value={qc.farmer}>
                    {qc.farmerName}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>   
          </Col>
         <Col span={6}>
            <Form.Item label="Invoice Date" name="invoiceDate">
              <RangePicker />
            </Form.Item>
          </Col>
          <Col xs={24} sm={12} md={8} lg={6} xl={6}>
            <Form.Item name="category" label="Category">
              <Select
                showSearch
                placeholder="Select Category"
                optionFilterProp="children"
                allowClear
              >
                {category.map((qc: any) => (
                  <Select.Option key={qc.category} value={qc.category}>
                    {qc.category}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>   
          </Col>
          <Col xs={24} sm={12} md={8} lg={6} xl={6}>
            <Form.Item name="harvestType" label="Harvest Type">
              <Select
                showSearch
                placeholder="Select Harvest Type"
                optionFilterProp="children"
                allowClear
              >
                {harvestType.map((qc: any) => (
                  <Select.Option key={qc.harvestType} value={qc.harvestType}>
                    {qc.harvestType}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>   
          </Col>
          <Col xs={12} sm={6} md={4} lg={3} xl={2} style={{paddingTop:"30px"}}>
            <Form.Item>
              <Button
                htmlType='submit'
                type="primary"
                style={{ width: '94px', marginRight: "10px" }}>
                Get Report
              </Button>
            </Form.Item>
          </Col>
          <Col xs={12} sm={6} md={4} lg={4} xl={3} style={{paddingTop:"30px",marginLeft:20}}>
            <Form.Item>
              <Button
                type="primary"
                icon={<UndoOutlined />}
                onClick={onReset}
                style={{ width: "94px" }}
              >
                Reset
              </Button>
            </Form.Item>
          </Col>
            </Row>
            </Form>
            {isVisible&&(

                <><Row gutter={16} style={{ height: '45px' }}>
            <Col span={5}>
              <Tag color="#92d8b4" style={{ display: 'flex', color: 'black', justifyContent: 'center', alignItems: 'center', height: 35, padding: '6px' }}>
                Total No.Of RM invoice : {grnInvoiceReport.length || 0}
              </Tag></Col>
                <Col span={3}>
              <Tag color="#e2bfcb" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: 35, padding: '6px',color: 'black' }}>
              Total Qty : {grnInvoiceReport.reduce((sum, record) => sum + (parseFloat(record.totalQuantity) || 0), 0).toFixed(2)}

              </Tag></Col>
              <Col span={4}>
              <Tag color="#f7d186" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: 35, padding: '6px',color: 'black' }}>
             Total Amount : ₹ {grnInvoiceReport
  .reduce((sum, record) => sum + (parseFloat(record.totalAmount) || 0), 0)
  .toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}

              </Tag></Col>
          </Row><Table columns={Columns} dataSource={grnInvoiceReport}
            pagination={{
              pageSize: 500,
              onChange(current, pageSize) {
                setPage(current)
              }
            }} 
             scroll={{ x: 'max-content' }} 
              summary={(pageData) => {
                          let totalWeight = 0;
                          let totalAmt = 0;
                          let tdsAmt=0;
                          let finalAmt=0;
                        
                          pageData.forEach(({ totalQuantity,totalAmount,tdsAmount,finalAMount }) => {
                              totalWeight += parseFloat(totalQuantity) || 0;
                              totalAmt += parseFloat(totalAmount) || 0;
                              tdsAmt+=parseFloat(tdsAmount) || 0;
                              finalAmt+=parseFloat(finalAMount) || 0;
                            });
                        console.log(totalWeight);
                        
                          return (
                            <Table.Summary.Row>
                              <Table.Summary.Cell index={8} colSpan={9}>
                                Total
                              </Table.Summary.Cell>
                              <Table.Summary.Cell index={9}>
                                {totalWeight.toFixed(2)}
                              </Table.Summary.Cell>
                              <Table.Summary.Cell index={10}>
                              </Table.Summary.Cell>
                              {/* <Table.Summary.Cell index={9}>
                              </Table.Summary.Cell> */}
                              <Table.Summary.Cell index={11}>
                              ₹ {totalAmt.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                              </Table.Summary.Cell>
                              <Table.Summary.Cell index={12}>
                              ₹ {tdsAmt.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                              </Table.Summary.Cell>
                              <Table.Summary.Cell index={13}>
                              ₹ {finalAmt.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                              </Table.Summary.Cell>
                            </Table.Summary.Row>
                          );
                        }} 
            /></>
          )}

    </Card>
    </div>
  )
}

export default GrnInvoiceReport