import React, { useEffect, useRef, useState } from 'react';
import Table, { ColumnProps } from 'antd/lib/table';
import { Card, Col, Form, Modal, Row, Tag, Tooltip, DatePicker, Typography, Button, Input, } from 'antd';
import { CollectionsService } from '@gtpl/shared-services/finance';
import { RmDateReq } from '@gtpl/shared-models/finance';
import moment, { Moment } from "moment";
import Highlighter from 'react-highlight-words';
import { SearchOutlined, FilePdfOutlined, DownloadOutlined } from '@ant-design/icons';
import { SupplierTypeEnum } from '@gtpl/shared-models/common-models';
import { PayablesDashboardReq } from '@gtpl/shared-models/raw-material-procurement';



export interface props {
  fromDate?: string;
  toDate?: string;
  unit?:number;
  supplier?: number;
  vendor?: number;
  company?:any
      year?:number
  month?:number
}

const PaybleAndDueComponent = (props:props) =>{
  const {fromDate ,toDate,unit} = props
  const [form] = Form.useForm();
  const [payModel, setPayModel] = useState<boolean>(false)
  const [dueModel, setDueModel] =  useState<boolean>(false)
  const [agingtableVisible, setAgingtableVisible] = useState<boolean>(false)

  const [invoicePaidData, setInvoicePaidData] = useState<any[]>([])
  const [invoiceDueData, setInvoiceDueData] = useState<any[]>([])
  const [agingData, setAgingData] = useState<any[]>([])
  const [amount, setAmount]  = useState<any[]>([])


  const [dueAmount, setDueAmount] = useState<any>(0)
  const  [paidAmount, setPaidAmount] = useState<any>(0)

    const [page, setPage] = useState(1);
    const [pageSize, setPageSize] = useState<number>(10);


  const collectionService = new CollectionsService()
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const searchInput = useRef(null);
console.log(props,'ppppppppp');

  useEffect(() =>{
    getRmPaidAmountData()
    rmDueData()
    // getRMDueAmountData('AGING',undefined)
  },[props?.fromDate, props?.toDate, props?.unit,props?.supplier,props?.vendor,props?.company,props?.year,props?.month])

  const getRmagingDuesData = (req?: PayablesDashboardReq) =>{
    // const req = new RmDateReq()
    // req.invoiceFromDate=fromDate
    // req.invoiceToDate=toDate
    // req.unit = unit
    // req.supplierId = props?.supplier
    // req.vendorId = props?.vendor
    // req.company=props?.company
    collectionService.getRmagingDuesData(req).then(res =>{
      if(res.status){
        setAgingData(res.data)
      }else{
        setAgingData([])
      }
    })
  }

 const rmDueData =() =>{
     const req = new PayablesDashboardReq()
  //  req = req || {};
    req.fromDate = props?.fromDate,
    req.toDate = props?.toDate,
    req.unitId =props?.unit,
    req.supplierId = props?.supplier ,
    req.company=props?.company
        req.year=props?.year
    req.month=props?.month
  collectionService.rmDueData(req).then(res =>{
    if(res.status){
      setAmount(res.data)
    }else{
      setAmount([])
    }
  })
 }
        // console.log(paidAmount)

// console.log(amount[0]?.dueAmount)
  const getRmPaidAmountData = () =>{
    const req = new RmDateReq()
    req.invoiceFromDate=fromDate
    req.invoiceToDate=toDate
    req.unit = unit
    req.supplierId = props?.supplier
    req.vendorId = props?.vendor
    req.company=props?.company
        req.year=props?.year
    req.month=props?.month
    collectionService.getRmPaidAmountData(req).then(res =>{
      if(res.status){
        setInvoicePaidData(res.data)
        console.log(res.data)
        const totalPayable = res.data.reduce((sum, item) => {
          return sum + Number(item.paidAmount || 0);
        }, 0);
        // console.log(totalPayable)
        // setPaidAmount(totalPayable.toFixed(2));  
      }else{
        setInvoicePaidData([])
      }
    })
  }
        // console.log(paidAmount)


  const getRMDueAmountData = (req?: PayablesDashboardReq) =>{
    // const req = new RmDateReq()
    // req.invoiceFromDate=fromDate
    // req.invoiceToDate=toDate
    // req.noOfDays=daysCount
    // req.model = model
    // req.unit = unit
    // req.supplierId = props?.supplier
    // req.vendorId = props?.vendor
    // req.company=props?.company
    collectionService.getRMDueAmountData(req).then(res =>{
      if(res.status){
        setInvoiceDueData(res.data) 
        console.log(res.data,'ooooooooooo');
        
      }else{
        setInvoiceDueData([])
      }
    })
  }
  const handleRangeClick = (record) =>{
    console.log(record,'record');
    
    if(record.sum !== 0){
      const request = {
       // unitId: plantId || '1',
       fromDate: record.fromDate ,
       toDate: record.toDate ,
       unitId: props?.unit,
       company:props?.company,
       year:props?.year,
      month:props?.month
     };
     setDueModel(true)
     getRMDueAmountData(request)
    }
  }
 
  const handleCancel = () =>{
    setDueModel(false)
    // getRMDueAmountData('AGING',undefined)

  }
  const agingtableOncancel = () =>{
    setAgingtableVisible(false);
    rmDueData()
    
  }

  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 agingColumn: ColumnProps<any>[] =[
  {
      title: 'Range',
      dataIndex: 'range',
      key: 'range',
      width: 100,
    },
    {
      title: 'Due Amount',
      dataIndex: 'sum',
      key: 'sum',
      width: 100,
      render: (text: any) => `${formatIndianNumber(text)}`,
    },
  ];
      const paybleColumn: ColumnProps<any>[] = [
        {
          title: 'Vendor',
          dataIndex: 'vendor',
          render:(text, record)=>{return record.brokerName!=null?record.brokerName:record.farmerName},
          // ...getColumnSearchProps('vendor')
        },
        {
          title: 'Vendor Type',
          dataIndex: 'supplierType',
          ...getColumnSearchProps('supplierType')
       
        },
        {
          title: 'Invoice Number',
          dataIndex: 'invoice_number',
          ...getColumnSearchProps('invoice_number')
        },
        {
          title: 'Invoice Date',
          dataIndex: 'invoice_date',
          render:(value,record) =>{
            return record.invoice_date?moment(record.invoice_date).format('YYYY-MM-DD'):'-'
          },
          // ...getColumnSearchProps('vendorName')
        },
        {
          title: 'Recived Date',
          dataIndex: 'paymentRecivedDate',
          render:(value,record) =>{
            return record.paymentRecivedDate?moment(record.paymentRecivedDate).format('YYYY-MM-DD'):'-'
          },
          ...getColumnSearchProps('paymentRecivedDate')
       
        },
        {
          title: 'Invoice Amount',
          dataIndex: 'paybleAmount',
         render:(val,rec)=>{
            return rec.paybleAmount?Number(rec.paybleAmount).toFixed(2):'0'
          },
          ...getColumnSearchProps('paybleAmount')
        },
         {
          title: 'Taxable Amount',
          dataIndex: 'deduction',
         render:(val,rec)=>{
            return rec.deduction?Number(rec.deduction).toFixed(2):'0'
          },
          ...getColumnSearchProps('deduction')
        },
        {
          title: 'Paid Amount',
          dataIndex: 'paidAmount',
          render:(val,rec)=>{
            return rec.paidAmount?Number(rec.paidAmount).toFixed(2):'0'
          },
          ...getColumnSearchProps('paidAmount')
        },
     
      ];
      
      const dueColumn: ColumnProps<any>[] = [
        {
          title: 'Vendors',
          dataIndex: 'farmerName',
          render:(text,record)=>(
<span>{record.supplierType != SupplierTypeEnum.DEALER?record.farmerName:record.brokerName}</span>
          ),
          //   console.log(record,'due column')
            
          //   return( )
          // },
         ...getColumnSearchProps('vendor')
       
        },
        {
          title: 'Vendor Type',
          dataIndex: 'supplierType',
          ...getColumnSearchProps('supplierType')
        },
        {
          title: 'Invoice Number',
          dataIndex: 'invoice_number',
          ...getColumnSearchProps('invoice_number')
        },
        {
          title: 'Invoice Date',
          dataIndex: 'invoice_date',
          render:(value,record) =>{
            return record.invoice_date?record.invoice_date:'-'
          },
          // ...getColumnSearchProps('vendorName')
       
        },
        {
          title: 'Invoice Amount',
          dataIndex: 'totalAmount',
         render:(val,rec)=>{
            return (<span>{rec.totalAmount?((rec.totalAmount).toFixed(2)):'0'}</span>)
          },
          ...getColumnSearchProps('totalAmount')
        },
        {
          title: 'Paid Amount',
          dataIndex: 'paidAmount',
       render:(val,rec)=>{
            return (<span>{rec.paidAmount?((rec.paidAmount).toFixed(2)):'0'}</span>)
          },
          ...getColumnSearchProps('paidAmount')
        },
        {
          title: 'Taxable Amount',
          dataIndex: 'tdsval',
         render:(val,rec)=>{
            return rec.tdsval?Number(rec.tdsval).toFixed(2):'0'
          },
          ...getColumnSearchProps('tdsval')
        },
        {
          title: 'Due Amount',
          dataIndex: 'invoiceAmt',
          render:(val,rec)=>{
            return rec.invoiceAmt ?Number(Number(rec.invoiceAmt)-Number(rec.paidAmount)).toFixed(2):'0'
          },
          // ...getColumnSearchProps('invoiceAmt')
        },
     
      ];

      const colors = {
        primary: '#2D3A4B',
        secondary: '#4A90E2',
        accent: '#FF6B6B',
        background: '#F8F9FA',
        textSecondary: '#6C757D',
        success: '#28A745',
        warning: '#FFC107',
        headerBg: 'powderblue',
        headerText: '#FFFFFF',
        cardHover: '#F8F9FA'
      };

      useEffect(() =>{
      if(fromDate != undefined && toDate != undefined){
        rmDueData()
        getRmPaidAmountData()
      }
      },[fromDate,toDate,unit,props.supplier,props.vendor])


  
     const handleCardClick = (type: string) => {
      if(type === 'PAID'){
        setPayModel(true)
    setAgingtableVisible(false)

      }
      if(type === 'DUE' && amount?.[0]?.dueAmount > 1){
        console.log('hii')
          const req = {
      fromDate: props?.fromDate,
      toDate: props?.toDate,
      unitId: props?.unit,
      supplier: props?.supplier,
      company:props?.company  ,
      year:props?.year,
      month:props?.month
    }
        setPayModel(false)
    setAgingtableVisible(true)
    getRmagingDuesData(req)
      }
      if(type === 'DUE' && amount?.[0]?.dueAmount < 1 ){
        console.log('else condition')
       
    setPayModel(false)
    setAgingtableVisible(true)
        setAgingData([])
      }
    setPage(1);
    setPageSize(10);
    };

  const formatIndianNumber = (num: number | string): string => {
  const number = Number(num);
  if (isNaN(number)) return '₹0.00';
  const [integer, decimal = '00'] = number.toFixed(2).split('.');
  const lastThree = integer.slice(-3);
  const otherDigits = integer.slice(0, -3);
  const formattedInteger = otherDigits
    ? otherDigits.replace(/\B(?=(\d{2})+(?!\d))/g, ',') + ',' + lastThree
    : lastThree;
  return `₹${formattedInteger}.${decimal}`;
};

  const formatToCrOrLakh = (amount: number): string => {
    
    if (amount >= 1e7) {
      return `${(((amount / 1e7) * 100) / 100).toFixed(2)} Cr`;
    } else if (amount >= 1e5) {
  
      return `${(((amount / 1e5) * 100) / 100).toFixed(2)} L`;
    } else {
      return formatIndianNumber(amount);
    }
  };
  const rangeTotals = agingData.reduce(
    (acc, record) => acc + (Number(record.due) || 0),
    0
  );
   const invoiceTotals = invoiceDueData.reduce(
    (acc, record) => acc + (Number(Number(record.invoiceAmt)-Number(record.paidAmount)) || 0),
    0
  );
  return(
  <div style={{ padding: '8px', background: colors.background }}>
     <div><Card
            title={<span style={{ color: 'white', fontSize: '16px' }}>RM Vendor Payments Overview & Dues</span>}
            style={{
              textAlign: 'center',
              width: '100%',
              maxWidth: '400px',
              margin: '0 auto',
              borderRadius: '8px',
            }}
            headStyle={{
              backgroundColor: '#587b9b',
              border: 0,
              padding: '2px 2px',
              minHeight: '10px',
            }}
            bodyStyle={{ padding: '12px' }}
          >
            <div style={{ display: 'flex', gap: '12px', justifyContent: 'center' }}>
              <Card
                style={{
                  flex: 1,
                  padding: '8px',
                  textAlign: 'center',
                  borderRadius: '6px',
                  boxShadow: '0 1px 3px rgba(0,0,0,0.1)',
                  transition: 'transform 0.2s, box-shadow 0.2s',
                  
                }}
                bodyStyle={{ padding: '8px' }}
                hoverable
              >
                <p style={{ margin: 0, fontSize: '16px', color: '#05539a' }}>Payment Amount</p>
                <p style={{ margin: 0, fontWeight: 'bold',fontSize: '16px' }} onClick={() => handleCardClick('PAID')}>
                  {formatToCrOrLakh(Number(amount?.[0]?.paidAmount ?? 0))}
                  {/* ₹{paidAmount ? paidAmount.toLocaleString('en-IN') : '0'} */}
                  </p>
              </Card>
              <Card
                style={{
                  flex: 1,
                  padding: '8px',
                  textAlign: 'center',
                  borderRadius: '6px',
                  boxShadow: '0 1px 3px rgba(0,0,0,0.1)',
                  transition: 'transform 0.2s, box-shadow 0.2s',
                }}
                bodyStyle={{ padding: '8px' }}
                hoverable
              >
                <p style={{ margin: 0, fontSize: '16px', color: '#f69026' }}>Due Amount</p>
                <p style={{ margin: 0, fontWeight: 'bold',fontSize: '16px' }} onClick={() => handleCardClick('DUE')}>
                  ₹{formatToCrOrLakh(Number(amount?.[0]?.dueAmount ?? 0))}
                   {/* {amount[0]?.dueAmount?Number(amount[0]?.dueAmount).toFixed(2) : '0'} */}
                  </p>
              </Card>
            </div>
          </Card></div>
   
         <Modal
        key={'modal' + Date.now()}
        width={'80%'}
        style={{ top: 30, alignContent: 'right' }}
        visible={payModel}
        title={<React.Fragment>
        </React.Fragment>}
        onCancel={() =>setPayModel(false)}
        footer={[
        ]}
        >
          <Card
          title="Detailed Paid Invoices"
          headStyle={{
            background: 'powderblue',
            padding: '3px 6px',
            lineHeight: '0.2px',
            fontSize: 14,
            fontWeight: 600,
            borderRadius: '8px 8px 0 0',
            borderBottom: 0
          }}
          >
            <Table
            columns={paybleColumn}
            dataSource={invoicePaidData}
            pagination={false}
            scroll={{ x: 200, y: 400 }}
            size="middle"
            bordered />
            </Card>
      </Modal>

      <Modal
        visible={agingtableVisible}
        closable
          footer={null}
        width={400}
        style={{ top: 20 }}
        onCancel={() => {
          agingtableOncancel()
        }}
      >
          <Table
            columns={agingColumn}
            dataSource={agingData}
            pagination={false}
          size="small"
          rowKey="range"
          onRow={(record) => ({
            onClick: () => handleRangeClick(record),
          })}
          rowClassName={() => 'compact-row'}
          style={{ fontSize: '12px' }}
            footer={() => (
            <div style={{ fontWeight: 'bold', display: 'flex', justifyContent: 'space-between', padding: '4px 8px' }}>
              <span style={{ width: agingColumn[0].width }}>Total</span>
              <span style={{ width: agingColumn[1].width, textAlign: 'right' }}>
                  ₹{formatToCrOrLakh(Number(amount?.[0]?.dueAmount ?? 0))}

                {/* {amount[0]?.dueAmount?Number(amount[0]?.dueAmount).toFixed(2) : '0'} */}
              </span>
            </div>
          )}
           />
      </Modal> 

      <Modal
        visible={dueModel}
        closable
        footer={false}
        width={'80%'}
        onCancel={() => {
          handleCancel()
          // setDueModel(false);
        }}
      >
        <Card
          title="Detailed Due Invoices"
          headStyle={{
            background: 'powderblue',
            padding: '3px 6px',
            lineHeight: '0.2px',
            fontSize: 14,
            fontWeight: 600,
            borderRadius: '8px 8px 0 0',
            borderBottom: 0
          }}
        >
            <Table
                    columns={dueColumn}
                    dataSource={invoiceDueData}
                    rowKey="invoiceId"
                     scroll={{ x: 200, y: 400 }}
                    // pagination={false}
                    size="small"
                    rowClassName={() => 'compact-row'}
                    style={{ fontSize: '12px' }}
                    footer={() => (
                      <div style={{ fontWeight: 'bold', display: 'flex', justifyContent: 'space-between', padding: '4px 8px' }}>
                        <span style={{ width: dueColumn[2].width }}>Total</span>
                        <span style={{ width: dueColumn[4].width }}></span>
                        <span style={{ width: dueColumn[7].width, textAlign: 'right' }}>
                          {`${formatIndianNumber(invoiceTotals)}`}
                        </span>
                        {/* <span style={{ width: dueColumn[3].width, textAlign: 'right' }}>
                          {}
                        </span> */}
                        {/* <span style={{ width: dueColumn[4].width }}></span> */}
                      </div>
                    )}
                  />
          {/* <Table
            columns={dueColumn}
            dataSource={invoiceDueData}
            pagination={false}
            scroll={{ x: 200, y: 400 }}
            size="middle"
            bordered
              footer={() => (
            <div style={{ fontWeight: 'bold', display: 'flex', justifyContent: 'space-between', padding: '4px 8px' }}>
              <span style={{ width: dueColumn[4].width }}>Total</span>
              <span style={{ width: dueColumn[5].width, textAlign: 'right' }}>
                 {`₹${formatIndianNumber(invoiceTotals)}`}
              </span>
            </div>
          )} /> */}
            </Card>
      </Modal> 
    </div>
  )
}
export default PaybleAndDueComponent;

