import { PayablesDashboardReq } from '@gtpl/shared-models/raw-material-procurement'
import { GrnService } from '@gtpl/shared-services/procurement'
import { Card, Modal, Table, Button, Input, } from 'antd'
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react'
import Highlighter from 'react-highlight-words';
import { SearchOutlined, FilePdfOutlined, DownloadOutlined } from '@ant-design/icons';
export interface PackingPaidProps {
  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}`;
};

const PackingPaidDashboard = (props?: PackingPaidProps) => {
  const [packingPaidData, setpackingPaiddata] = useState<any>()
  const grnService = new GrnService()
  const [isRangeModalVisible, setIsRangeModalVisible] = useState(false);
  const [overDuePackingRanges, setOverDuePackingRanges] = useState<any[]>([]);
  const plantId = JSON.parse(localStorage.getItem('unit_id'));
  const [isInvoiceModalVisible, setIsInvoiceModalVisible] = useState(false);
  const [overDuePackingInvoice, setOverDuePackingInvoice] = useState<any[]>([]);
  const [isPaidModalVisible, setIsPaidModalVisible] = useState(false);
  const [paidPackingReport, setPaidpackingReport] = useState<any[]>([]);
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');
    const searchInput = useRef(null);

  useEffect(() => {
    if (props?.fromDate && props?.toDate) {
      getTotalPackingPaidsDashboard();
    }
  }, [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 getTotalPackingPaidsReport = (req?: PayablesDashboardReq) => {
    
    const request = req
    grnService.getTotalPackingPaidsReport(request).then((res) => {
      if (res.status) {
        setPaidpackingReport(res.data)
      } else {
        setPaidpackingReport([])
      }
    })
  }

  const getTotalPackingPaidsDashboard = (req?: PayablesDashboardReq) => {
    req = req || {};
  
    req.fromDate = props?.fromDate;
    req.toDate = props?.toDate;
   req.unitId = props?.unit;
   req.supplierId = props?.supplier;
   req.vendorId = props?.vendor;
   req.company=props?.company;
   req.year=props?.year
              req.month=props?.month
    grnService.getTotalPackingPaidsDashboard(req).then((res) => {
      if (res.status) {
        setpackingPaiddata(res.data);
      } else {
        setpackingPaiddata([]);
      }
    });
  };
  

  const getOverDuePackingRanges = (req?: PayablesDashboardReq) => {
    grnService.getOverDuePackingRanges(req).then((res) => {
      if (res.status) {
        setOverDuePackingRanges(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 = overDuePackingInvoice.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 = paidPackingReport.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 = overDuePackingRanges.reduce(
    (acc, record) => acc + (Number(record.sum) || 0),
    0
  );

    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 rangeColumns = [
    {
      title: 'Range',
      dataIndex: 'range',
      key: 'range',
      width: 100,
      render: (text: string, record: any) =>
        record?.sum > 0 ? (
          <span
            style={{ color: '#1890ff', cursor: 'pointer' }}
            onClick={() => handleRangeClick(record)}
          >
            {text}
          </span>
        ) : (
          <span>{text}</span>
        ),
    },
    {
      title: 'Due Amount',
      dataIndex: 'sum',
      key: 'sum',
      width: 100,
      render: (text: any) => formatIndianNumber(text),
    },
  ];

  const invoiceColumns = [
    {
      title: 'Vendor',
      dataIndex: 'vendorName',
      key: 'vendorName',
      width: 100,
      ...getColumnSearchProps('vendorName')

    },
    {
      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,
      ...getColumnSearchProps('invoiceNumber')

    },
    {
      title: 'Invoice Amount',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      width: 130,
      render: (text: any) => formatIndianNumber(text),
      ...getColumnSearchProps('totalAmount')

    },
    {
      title: 'Taxable Amount',
      dataIndex: 'taxableAmount',
      key: 'taxableAmount',
      width: 130,
      render: (text: any) => formatIndianNumber(text),
      ...getColumnSearchProps('taxableAmount')

    },
    {
      title: 'Payment',
      dataIndex: 'payment',
      key: 'payment',
      width: 130,
      render: (text: any) => formatIndianNumber(text),
      ...getColumnSearchProps('payment')

    },
    {
      title: 'Due Amount',
      dataIndex: 'overdue',
      key: 'overdue',
      width: 130,
      render: (text: any) => formatIndianNumber(text),
      ...getColumnSearchProps('overdue')

    },
    {
      title: 'Aging',
      dataIndex: 'aging',
      key: 'aging',
      width: 60,
    },
  ];

  const paidColumns = [
    {
      title: 'Vendor',
      dataIndex: 'vendorName',
      key: 'vendorName',
      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: 'Paid Amount',
      dataIndex: 'payment',
      key: 'payment',
      width: 130,
      render: (text: any) => formatIndianNumber(text),
    },
  ];

  const handleOverdueAmountClick = () => {
    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
    }
    getOverDuePackingRanges(req);
    setIsRangeModalVisible(true);
  };

  const handlePaidAmountClick = () => {
    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
    }
    getTotalPackingPaidsReport(req);
    setIsPaidModalVisible(true);
  };

  const handleRangeClick = (record: any) => {
    if(record.sum != 0) {
    // console.log(record, "recorddddd")
    const request = {
      // unitId: plantId || '1',
      fromDate: record.fromDate || '2024-01-01',
      toDate: record.toDate || '2025-12-01',
      unitId: props?.unit ,
      supplierId: props?.supplier,
      vendorId: props?.vendor,
      company:props?.company,
      year:props?.year,
      month:props?.month
    }
    // console.log('Clicked Range:', record.range);
    // console.log('Sending this request to getOverDuePackinginvoices:', request);
    getOverDuePackinginvoices(request);
    setIsInvoiceModalVisible(true);
  }
  };
  return (
    <div>
      <Card
        title={<span style={{ color: 'white', fontSize: '16px' }}>Packing/General Payments Overview & Report</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()}
          >
            <p style={{ margin: 0, fontSize: '16px', color: '#05539a' }}>Payble Amount</p>
            <p style={{ margin: 0, fontWeight: 'bold',fontSize: '16px' }}>₹{formatToCrOrLakh(Number(packingPaidData?.[0]?.payment ?? 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
            onClick={handleOverdueAmountClick}
          >
            <p style={{ margin: 0, fontSize: '16px', color: '#f69026' }}>Due Amount</p>
            <p style={{ margin: 0, fontWeight: 'bold',fontSize: '16px' }}>₹{formatToCrOrLakh(Number(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={overDuePackingRanges}
          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
        visible={isInvoiceModalVisible}
        onCancel={() => setIsInvoiceModalVisible(false)}
        footer={null}
        width={700}
        style={{ top: 20 }}
      >
        <Table
          columns={invoiceColumns}
          dataSource={overDuePackingInvoice}
          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.invoiceAmount)}
              </span>
              <span style={{ width: invoiceColumns[3].width }}></span>
              <span style={{ width: invoiceColumns[4].width }}></span>

              <span style={{ width: invoiceColumns[5].width, textAlign: 'right' }}>
                {formatIndianNumber(invoiceTotals.dueAmount)}
              </span>
              <span style={{ width: invoiceColumns[6].width }}></span>
            </div>
          )}
        />
      </Modal>
      <Modal
        visible={isPaidModalVisible}
        onCancel={() => setIsPaidModalVisible(false)}
        footer={null}
        width={800}
        style={{ top: 20 }}
      >
        <Table
          columns={paidColumns}
          dataSource={paidPackingReport}
          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>

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

export default PackingPaidDashboard