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


export interface OverDueReceivablesDashboardProps {
  fromDate?: string;
  toDate?: string;
  unit?: number;
  buyer?:number;
  company?:number
}
// Helper function for Indian number formatting
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 OverDueReceivablesDashboard = (props?: OverDueReceivablesDashboardProps) => {
  const [overDueReceivables, setOverDueReceivables] = useState<any>();
  const [overDueReceivableRanges, setOverDueReceivablesRanges] = useState<any[]>([]);
  const [overDueReceivableInvoice, setOverDueReceivableInvoice] = useState<any[]>([]);
  const [isRangeModalVisible, setIsRangeModalVisible] = useState(false);
  const [isInvoiceModalVisible, setIsInvoiceModalVisible] = useState(false);
  const [totalReceivableInvoices, setTotalReceivablesInvoices] = useState<any[]>([]);
  const [isReceivedModalVisible, setIsReceivedModalVisible] = useState(false);

  const collectionsService = new CollectionsService();
  const plantId = JSON.parse(localStorage.getItem('unit_id'));


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

  const getOverDueReceivablesDashboard = (req?: PayablesDashboardReq) => {
    req = req || {};
    if(props.buyer > 0){
req.buyerId = props?.buyer}
    req.fromDate = props?.fromDate,
    req.toDate = props?.toDate,
    req.unitId =props?.unit,
    
    // req.buyerId = props?.buyer ,
    req.company=props?.company
    //  req.fromDate = props?.fromDate
    // req.toDate = props?.toDate
    collectionsService.getOverDueReceivables(req).then((res) => {
      if (res.status) {
        setOverDueReceivables(res.data);
      } else {
        setOverDueReceivables([]);
      }
    });
  };
 const getTotalReciveableInvoices = (req?: PayablesDashboardReq) => {

    collectionsService.getTotalReciveableInvoices(req).then((res) => {
      if (res.status) {
        setTotalReceivablesInvoices(res.data);
      } else {
        setTotalReceivablesInvoices([]);
      }
    });
  };

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

  const getOverDueReceivablesInvoices = (req?: PayablesDashboardReq) => {
    //    req = req || {};
    // req.fromDate = props?.fromDate,
    // req.toDate = props?.toDate
    collectionsService.getOverDueReceivablesinvoices(req).then((res) => {
      if (res.status) {
        setOverDueReceivableInvoice(res.data);
      } else {
        setOverDueReceivableInvoice([]);
      }
    });
  };
 const handleReceivedAmountClick = (record: any) => {
   const req = {
      fromDate: props?.fromDate,
      toDate: props?.toDate,
      unitId: props?.unit,
      buyerId:props.buyer > 0? props?.buyer:undefined,
      company:props?.company
    }
    getTotalReciveableInvoices(req);
    setIsReceivedModalVisible(true);
  };
  const handlePaidAmountClick = (record:any) => {
       const req = {
      fromDate: props?.fromDate,
      toDate: props?.toDate,
      unitId: props?.unit,
      buyerId:props.buyer > 0? props?.buyer:undefined,
      company:props?.company  
    }
    getOverDueReceivablesRanges(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
    };
    getOverDueReceivablesInvoices(request);
    setIsInvoiceModalVisible(true);
  };

  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: 'Customer Name',
      dataIndex: 'customer',
      key: 'customer',
      width: 100,
    },
     {
      title: 'Invoice Number',
      dataIndex: 'invoiceNumber',
      key: 'invoiceNumber',
      width: 130,
    },
    {
          title: 'Invoice Date',
          dataIndex: 'invoiceDate',
          key: 'invoiceDate',
          width: 130,
          render: (text: any) => {
            return text ? moment(text).format('DD-MM-YYYY') : '';
          }
        },
    {
      title: 'Invoice Amount',
      dataIndex: 'invoiceAmount',
      key: 'invoiceAmount',
      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 receivedInvoiceColumns = [
    {
      title: 'Customer Name',
      dataIndex: 'customerName',
      key: 'customerName',
      width: 100,
    },
     {
      title: 'Invoice Number',
      dataIndex: 'invoiceNumber',
      key: 'invoiceNumber',
      width: 130,
    },
    {
      title: 'Invoice Amount',
      dataIndex: 'invoiceAmount',
      key: 'invoiceAmount',
      width: 130,
      render: (text: any) => `$${formatIndianNumber(text)}`,
    },
      {
          title: 'Invoice Date',
          dataIndex: 'invoiceDate',
          key: 'invoiceDate',
          width: 130,
          render: (text: any) => {
            return text ? moment(text).format('DD-MM-YYYY') : '';
          }
        },
    {
      title: 'Payment Received',
      dataIndex: 'payment',
      key: 'payment',
      width: 130,
      render: (text: any) => `$${formatIndianNumber(text)}`,
    },
      {
          title: 'Received Date',
          dataIndex: 'receivedDate',
          key: 'receivedDate',
          width: 150,
          render: (text: any) => {
            return text ? moment(text).format('DD-MM-YYYY') : '';
          }
        },
   
  ];
  const invoiceTotals = overDueReceivableInvoice.reduce(
    (acc, record) => ({
      invoiceAmount: acc.invoiceAmount + (Number(record.invoiceAmount) || 0),
      dueAmount: acc.dueAmount + (Number(record.dueAmount) || 0),
    }),
    { invoiceAmount: 0, dueAmount: 0 }
  );
 const receivedTotals = totalReceivableInvoices.reduce(
    (acc, record) => acc + (Number(record.payment) || 0),
    0
  );
  const rangeTotals = overDueReceivableRanges.reduce(
    (acc, record) => acc + (Number(record.sum) || 0),
    0
  );

  const overDueAmount =
    Array.isArray(overDueReceivables) && overDueReceivables.length > 0
      ? Number(overDueReceivables[0]?.invoiceAmtUsd || 0) - Number(overDueReceivables[0]?.paidAmount || 0)
      : 0;
 const overDueAmountInr =
    Array.isArray(overDueReceivables) && overDueReceivables.length > 0
      ? Number(overDueReceivables[0]?.invoiceAmt || 0) - Number(overDueReceivables[0]?.collectionInr || 0)
      : 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' }}>OverDue Receivables</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: '8px', justifyContent: 'center' }}>
          <Card
            style={{
              flex: 1,
              padding: '6px',
              textAlign: 'center',
              borderRadius: '4px',
              boxShadow: '0 1px 2px rgba(0,0,0,0.1)',
            }}
            bodyStyle={{ padding: '6px' }}
            hoverable
            onClick={handleReceivedAmountClick}
          >
            <p style={{ margin: 0,fontWeight: 'bold', fontSize: '16px', color: '#05539a' }}>Total Received</p>
            <p style={{ margin: 0, fontWeight: 'bold', fontSize: '16px', cursor: 'pointer' }}>
              {`$${formatToCrOrLakh(overDueReceivables?.[0]?.paidAmount || 0)}`}
            </p>
             <p style={{ margin: 0, fontWeight: 'bold', fontSize: '16px', cursor: 'pointer' }}>
              {`₹${formatToCrOrLakh(overDueReceivables?.[0]?.collectionInr || 0)}`}
            </p>
          </Card>
          <Card
            style={{
              flex: 1,
              padding: '6px',
              textAlign: 'center',
              borderRadius: '4px',
              boxShadow: '0 1px 2px rgba(0,0,0,0.1)',
            }}
            bodyStyle={{ padding: '6px' }}
            hoverable
            onClick={handlePaidAmountClick}
          >
            <p style={{ margin: 0, fontSize: '16px',fontWeight: 'bold', color: '#f69026' }}>OverDue</p>
            <p style={{ margin: 0, fontWeight: 'bold', fontSize: '16px', cursor: 'pointer' }}>
              {`$${formatToCrOrLakh(overDueAmount)}`}
            </p>
             <p style={{ margin: 0, fontWeight: 'bold', fontSize: '16px', cursor: 'pointer' }}>
              {`₹${formatToCrOrLakh(overDueAmountInr)}`}
            </p>
          </Card>
        </div>
      </Card>

      <Modal
        // title={<span style={{ fontSize: '14px' }}>Receivables By Ranges</span>}
        visible={isRangeModalVisible}
        onCancel={() => setIsRangeModalVisible(false)}
        footer={null}
        width={400}
        style={{ top: 20 }}
      >
        <Table
          columns={rangeColumns}
          dataSource={overDueReceivableRanges}
          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>
          )}
        />
      </Modal>

      <Modal
        // title={<span style={{ fontSize: '14px' }}>Receivables Of Invoices</span>}
        visible={isInvoiceModalVisible}
        onCancel={() => setIsInvoiceModalVisible(false)}
        footer={null}
        width={600}
        style={{ top: 20 }}
      >
        <Table
          columns={invoiceColumns}
          dataSource={overDueReceivableInvoice}
          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, textAlign: 'right' }}>
                {`$${formatIndianNumber(invoiceTotals.invoiceAmount)}`}
              </span>
              <span style={{ width: invoiceColumns[2].width, textAlign: 'right' }}>
                {`$${formatIndianNumber(invoiceTotals.dueAmount)}`}
              </span>
              <span style={{ width: invoiceColumns[3].width }}></span>
            </div>
          )}
        />
      </Modal>
      <Modal
        // title={<span style={{ fontSize: '14px' }}>Receivables By Ranges</span>}
        visible={isReceivedModalVisible}
        onCancel={() => setIsReceivedModalVisible(false)}
        footer={null}
        width={600}
        style={{ top: 20 }}
      >
        <Table
          columns={receivedInvoiceColumns}
          dataSource={totalReceivableInvoices}
          rowKey="invoiceNumber"
          // 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: receivedInvoiceColumns[0].width }}>Total</span>
              <span style={{ width: receivedInvoiceColumns[1].width, textAlign: 'right' }}>
                {`$${formatIndianNumber(receivedTotals)}`}
              </span>
            </div>
          )}
        />
      </Modal>
      <style>{`
        .compact-row {
          height: 24px;
        }
        .compact-row td {
          padding: 4px !important;
          font-size: 12px !important;
        }
      `}</style>
    </div>
  );
};

export default OverDueReceivablesDashboard;