import { PayablesDashboardReq } from '@gtpl/shared-models/raw-material-procurement';
import { GrnService } from '@gtpl/shared-services/procurement';
import { Card, Modal } from 'antd';
import React, { useEffect, useState } from 'react';
import PayablesReportView from './paybles-report-view';

export interface PackingVendorPayProps {
    fromDate?: string;
    toDate?: string;
    unit?: number;
    supplier?: number;
    vendor?: number;
    company?:number;
    year?:number
  month?: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}`;
  };

export default function PackingVendorPay(props: PackingVendorPayProps) {

    const [packVendorPayablesData, setPackVendorPayablesdata] = useState([])
    const [modelData, setModelData] = useState([])
    const [modelVisible, setModelVisible] = useState(false)
    const grnService = new GrnService()

    useEffect(() => {
        if (props?.fromDate && props?.toDate) {
            getTotalPackingVendorPayables();
            getPayablesViewData();
        }
    }, [props?.fromDate, props?.toDate,props?.unit, props?.supplier, props?.vendor,props?.company,props?.year,props?.month]);

    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 {
          return formatIndianNumber(amount);
        }
      };

    const getTotalPackingVendorPayables = () => {
        const req = {
            fromDate: props?.fromDate,
            toDate: props?.toDate,
            unitId: props?.unit,
            supplierId: props?.supplier,
            vendorId: props?.vendor,
            company:props?.company,
             year:props?.year,
      month:props?.month
        }
        console.log("req---", req);
        grnService.getTotalPackingVendorPayables(req).then((res) => {
            if (res.status) {
                setPackVendorPayablesdata(res.data)
            } else {
                setPackVendorPayablesdata([])
            }
        })
    }

    const getPayablesViewData = () => {
        const req = {
            fromDate: props?.fromDate,
            toDate: props?.toDate,
            id: 6,
            unitId: props?.unit,
            supplierId: props?.supplier,
            vendorId: props?.vendor,
            company:props?.company,
             year:props?.year,
      month:props?.month
        }
        console.log("req---", req);
        grnService.getPayablesViewData(req).then((res) => {
            if (res.status) {
                setModelData(res.data)
            } else {
                setModelData([])
            }
        })
    }

    const handleModelClose = () => {
        setModelVisible(false);
        // setModelData([])
    }

    const handleModelOpen = () => {
        setModelVisible(true);
    }

    return (
        <>
            <Card
                title={<span style={{ color: 'white', fontSize: '16px' }}>Total Packing Vendor paybles</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' }}
            >
                <p onClick={handleModelOpen} style={{ margin: 16, fontWeight: 'bold', cursor: 'pointer',fontSize: '16px' }}>
                ₹{formatToCrOrLakh(Number(packVendorPayablesData?.[0]?.overdue ?? 0))}</p>
            </Card>
            <Modal
                title="Packing Vendor Payables Details"
                visible={modelVisible}
                onCancel={handleModelClose}
                footer={null}
                width={800} >
                <PayablesReportView data={modelData} />
            </Modal>

        </>



    );
}