import { PayablesDashboardReq } from '@gtpl/shared-models/raw-material-procurement'
import { CollectionsService } from '@gtpl/shared-services/finance';
import { GrnService } from '@gtpl/shared-services/procurement'
import { Card, Modal, Table } from 'antd'
import moment from 'moment';
import React, { useEffect, useState } from 'react'

export interface RodtepReceivableDashboardProps {
  fromDate?: string;
  toDate?: string;
  unit?: number;
  buyer?: number;
  company?:number
}

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 RodtepReceivableDashboard = (props?: RodtepReceivableDashboardProps) => {
  const [totalReceivableData, setTotalReceivableData] = useState<any>()
  const service = new CollectionsService()
  const [isRangeModalVisible, setIsRangeModalVisible] = useState(false);
  const [overDueRanges, setOverDuePackingRanges] = useState<any[]>([]);
  const plantId = JSON.parse(localStorage.getItem('unit_id'));
  const [isInvoiceModalVisible, setIsInvoiceModalVisible] = useState(false);
  const [overDueInvoice, setOverDueInvoice] = useState<any[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [dueAmount, setDueAmount] = useState<any[]>([]);
  const [rangesAmount, setRangesAmount] = useState<any[]>([]);


  useEffect(() => {
    if (props?.fromDate && props?.toDate) {
      getTotalRodtepDueIncentive();
    }
  }, [props?.fromDate, props?.toDate,props?.unit,props?.buyer,props?.company]);

  const getTotalRodtepDueIncentive = (req?: PayablesDashboardReq) => {
  
    req = req || {};
             req.fromDate = props?.fromDate,
             req.toDate = props?.toDate,
              req.unitId = props?.unit ,
              // req.buyerId = props?.buyer,
              req.company=props?.company
              if(props?.buyer > 0){
                req.buyerId = props?.buyer
            }
    // request.fromDate =props?.fromDate
    // request.toDate = props?.toDate
    // request.unitId = props?.
    service.getTotalRodtepDueIncentive(req).then((res) => {
      if (res.status) {
        setDueAmount(res.data)
      } else {
        setDueAmount([])
      }
    })
  }

  const getRodtepDueRanges = (req?: PayablesDashboardReq) => {
    // req = req || {};
    //          req.fromDate = props?.fromDate,
    //          req.toDate = props?.toDate
    service.getRodtepDueRanges(req).then((res) => {
      if (res.status) {
        setRangesAmount(res.data)
      } else {
        setRangesAmount([])
      }
    })
  }

  const getRodtepDueInvoices = (req?: PayablesDashboardReq) => {
    // req = req || {};
    //          req.fromDate = props?.fromDate,
    //          req.toDate = props?.toDate
    service.getRodtepDueInvoices(req).then((res) => {
      if (res.status) {
        setOverDueInvoice(res.data);
      } else {
        setOverDuePackingRanges([]);
      }
    });
  };

//   const getOverDuePackinginvoices = (req?: PayablesDashboardReq) => {
//     const request = req
//     console.log(request, "requesttttttttt")
//     grnService.getOverDuePackinginvoices(request).then((res) => {
//       if (res.status) {
//         setOverDuePackingInvoice(res.data);
//       } else {
//         setOverDuePackingInvoice([]);
//       }
//     });
//   };

//   const invoiceTotals = overDueInvoice.reduce(
//     (acc, record, index) => {
//       const totalAmount = Number(record.totalAmount) || 0;
//       const overdue = Number(record.overdue) || 0;
//       const updated = {
//         invoiceAmount: acc.invoiceAmount + totalAmount,
//         dueAmount: acc.dueAmount + overdue,
//       };

//       return updated;
//     },
//     { invoiceAmount: 0, dueAmount: 0 }
//   );

//   const paidTotals = paidReport.reduce(
//     (acc, record, index) => {
//       const totalAmount = Number(record.totalAmount) || 0;
//       const payment = Number(record.payment) || 0;
//       const updated = {
//         totalAmount: acc.totalAmount + totalAmount,
//         payment: acc.payment + payment,
//       };

//       return updated;
//     },
//     { totalAmount: 0, payment: 0 }
//   );

//   const rangeTotals = overDueRanges.reduce(
//     (acc, record) => acc + (Number(record.sum) || 0),
//     0
//   );

  const rangeColumns = [
    {
      title: 'Range',
      dataIndex: 'range',
      key: 'range',
      width: 100,
    },
    {
      title: 'Due Amount',
      dataIndex: 'sum',
      key: 'sum',
      width: 100,
                  render: (text: any) => `₹${formatIndianNumber(text)}`,

    },
  ];

  const invoiceColumns = [
    {
      title: 'Party',
      dataIndex: 'customerName',
      key: 'customerName',
      width: 100,
    },
    {
      title: 'Invoice Date',
      dataIndex: 'invoiceDate',
      key: 'invoiceDate',
      width: 130,
      render: (text: any) => {
        return text ? moment(text).format('DD-MM-YYYY') : '';
      }
    },
    {
      title: 'Invoice No',
      dataIndex: 'invoiceNumber',
      key: 'invoiceNumber',
      width: 130,
    },
    // {
    //   title: 'Invoice Amount',
    //   dataIndex: 'totalAmount',
    //   key: 'totalAmount',
    //   width: 130,
    //   render: (text: any) => formatIndianNumber(text),
    // },
    {
      title: 'Due Amount',
      dataIndex: 'dueAmount',
      key: 'dueAmount',
      width: 130,
      render: (text: any) => `₹${formatIndianNumber(text)}`,
    },
    {
      title: 'Aging',
      dataIndex: 'aging',
      key: 'aging',
      width: 60,
    },
  ];
 const handlePaidAmountClick = () => {
    const req = {
      fromDate: props?.fromDate,
      toDate: props?.toDate,
      unitId: props?.unit,
      buyerId: props?.buyer > 0?props?.buyer:undefined,
      company:props?.company
    }
    getRodtepDueRanges(req);
    setIsRangeModalVisible(true);
  };

  const handleRangeClick = (record: any) => {
    const request = {
      // unitId: plantId || '1',
      fromDate: record.fromDate || '2024-01-01',
      toDate: record.toDate || '2025-12-01',
      unitId: props?.unit,
      buyerId: props?.buyer > 0?props?.buyer:undefined,
      company:props?.company
    };
    getRodtepDueInvoices(request);
    setIsInvoiceModalVisible(true);
  };
    const rangeTotals = rangesAmount.reduce(
    (acc, record) => acc + (Number(record.sum) || 0),
    0
  );
   const invoiceTotals = overDueInvoice.reduce(
    (acc, record) => acc + (Number(record.dueAmount) || 0),
    0
  );
  //   const invoiceTotals = overDueInvoice.reduce(
  //   (acc, record, index) => {
  //     const totaldueAmount = Number(record.dueAmount) || 0;
  //     // const payment = Number(record.payment) || 0;
  //     const updated = {
  //       totaldueAmount: acc.totalAmount + totaldueAmount,
  //       // payment: acc.payment + payment,
  //     };

  //     return updated;
  //   },
  //   { totaldueAmount: 0 }
  // );
   const formatToCrOrLakh = (amount: number): string => {
    if (amount >= 1e7) {
      return `${(amount / 1e7).toFixed(2)} Cr`;
    } else if (amount >= 1e5) {
      return `${(amount / 1e5).toFixed(2)} L`;
    } else if (amount >= 1e3) {
    return `${(amount / 1e3).toFixed(2)} K`;
  } else {
    return formatIndianNumber(amount);
  }
  };    
  return (
    <div>
      <Card
        title={<span style={{ color: 'white', fontSize: '16px' }}>RODTEP Receivable</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
            onClick={() => handlePaidAmountClick()}
          >
            <h2 style={{ margin: 0, fontWeight: 'bold' }}>{`₹${formatToCrOrLakh(Number(dueAmount?.[0]?.totalDueAmount ?? 0))}`}</h2>
          </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
            onClick={handleOverdueAmountClick}
          >
            <p style={{ margin: 0, fontSize: '12px', color: '#f69026' }}>Overdue</p>
            <p style={{ margin: 0, fontWeight: 'bold' }}>{formatIndianNumber(packingPaidData?.[0]?.overdue ?? 0)}</p>
          </Card> */}
        </div>
      </Card>
      <Modal
        visible={isRangeModalVisible}
        onCancel={() => setIsRangeModalVisible(false)}
        footer={null}
        width={400}
        style={{ top: 20 }}
      >
        <Table
          columns={rangeColumns}
          dataSource={rangesAmount}
          rowKey="range"
          onRow={(record) => ({
            onClick: () => handleRangeClick(record),
          })}
          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: rangeColumns[0].width }}>Total</span>
              <span style={{ width: rangeColumns[1].width, textAlign: 'right' }}>
                {`₹${formatIndianNumber(rangeTotals)}`}
              </span>
            </div>
          )}
          // footer={() => (
          //   <div style={{ fontWeight: 'bold', display: 'flex', justifyContent: 'space-between', padding: '4px 8px' }}>
          //     <span style={{ width: rangeColumns[0].width }}>Total</span>
          //     <span style={{ width: rangeColumns[1].width, textAlign: 'right' }}>
          //       {''}
          //     </span>
          //   </div>
          // )}
        />
      </Modal>
      {/* <Modal
        visible={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={700}
        style={{ top: 20 }}
      >
        <Table
          columns={in}
          dataSource={rangesAmount}
          rowKey="invoiceId"
          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: paidColumns[0].width }}>Total</span>
        //     //   <span style={{ width: paidColumns[1].width }}></span>
        //     //   <span style={{ width: paidColumns[4].width }}></span>
        //     //   <span style={{ width: paidColumns[2].width, textAlign: 'right' }}>
        //     //     {formatIndianNumber(paidTotals.totalAmount)}
        //     //   </span>
        //     //   <span style={{ width: paidColumns[3].width, textAlign: 'right' }}>
        //     //     {formatIndianNumber(paidTotals.payment)}
        //     //   </span>

        //     // </div>
        //   )}
        />
      </Modal> */}
      <Modal
        visible={isInvoiceModalVisible}
        onCancel={() => setIsInvoiceModalVisible(false)}
        footer={null}
        width={700}
        style={{ top: 20 }}
      >
        <Table
          columns={invoiceColumns}
          dataSource={overDueInvoice}
          rowKey="invoiceId"
          // 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: invoiceColumns[0].width }}>Total</span>
              <span style={{ width: invoiceColumns[1].width }}></span>
              <span style={{ width: invoiceColumns[2].width, textAlign: 'right' }}>
                {`₹${formatIndianNumber(invoiceTotals)}`}
              </span>
              {/* <span style={{ width: invoiceColumns[3].width, textAlign: 'right' }}>
                {}
              </span> */}
              <span style={{ width: invoiceColumns[4].width }}></span>
            </div>
          )}
        />
      </Modal>
      

      <style>{`
                            .compact-row {
                              height: 24px;
                            }
                            .compact-row td {
                              padding: 4px !important;
                              font-size: 12px !important;
                            }
                          `}</style>
    </div>
  )
}

export default RodtepReceivableDashboard