import { Bar } from "@ant-design/plots";
import { Card, Empty, Spin } from "antd"
import React, { useEffect, useState } from "react"
import {RMGrnService} from '@gtpl/shared-services/raw-material-procurement'
import { AlertMessages } from "@gtpl/shared-utils/alert-messages";
import { PayableRequest } from "@gtpl/shared-models/finance";
import { PaybleComponentReq } from "@gtpl/shared-models/analytics-data";
import { SaleOrderService } from "@gtpl/shared-services/sale-management";

export interface CollectionInvAmountVsBuyerProps{
  fromDate?:any
  toDate?:any
  buyerId?:number
  type?:string
  division?:number
  unit?:number
  onBuyerHover? : (id:number) => void

}

const colors = {
  primary: '#2D3A4B',
  secondary: '#4A90E2',
  background: '#F8F9FA',
  headerBg: '#4A90E2',
  headerText: '#FFFFFF',
  tableBorder: '#B3E5FC',
  danger: '#EF5350',
  success: '#28A745'
};

const colorPalette = [
  '#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1',
  '#13c2c2', '#eb2f96', '#fa541c', '#a0d911', '#2f54eb'
];

export const CollectionInvAmountVsBuyer = (props:CollectionInvAmountVsBuyerProps) => {
  const [invInfo,setInvInfo] = useState<any[]>([])
  const saleService = new SaleOrderService()
  const  cardHeight = '500px'
    const [loading, setLoading] = useState(false);
      const [selectedBuyer,setSelectedBuyer] = useState<number>()
      const [highlighted, setHighlighted] = useState<string | null>(null);
  

  useEffect(() => {
    getInvInfo()
  },[])

      useEffect(() => {
      getInvInfo()
    },[props.fromDate,props.division,props.buyerId,props.type,props.unit,props.toDate])

  const getInvInfo = () => {
    const req = new PaybleComponentReq(null,null,null,null,null)
    if(props.fromDate != undefined){
      req.fromDate = props.fromDate
      req.toDate = props.toDate
    }
    if(props.buyerId != undefined){
      req.vendorId = props.buyerId
    }
    if(props.type != undefined){
      req.type = props.type
    }
    if(props.division != undefined){
      req.division = props.division
    }
    if(props.unit != undefined){
      req.unit = props.unit
    }
    saleService.getTop10InvAmountVendorsList(req).then(res => {
      setLoading(true)
      if(res.status){
      setLoading(false)
       const updatedData = res.data.map((item: any) => ({
        ...item,
        amount: parseFloat(item.amount),
      }));
        setInvInfo(updatedData)
      }else{
        setInvInfo([])
      setLoading(false)
        AlertMessages.getErrorMessage(res.internalMessage)
      }
    })
  }


 const config = {
    data: invInfo.sort((a,b) => b.amount - a.amount),
    xField: 'amount',
    yField: 'buyer',
    seriesField: 'buyer', 
    color: (datum: any, defaultColor?: string) => {
      const index = invInfo.findIndex(item => item.buyer === datum.buyer);
      const baseColor = colorPalette[index % colorPalette.length];
      
      // Apply opacity if this is not the highlighted item
      if (highlighted && datum.buyer !== highlighted) {
        // Convert hex to rgba with reduced opacity
        const r = parseInt(baseColor.slice(1, 3), 16);
        const g = parseInt(baseColor.slice(3, 5), 16);
        const b = parseInt(baseColor.slice(5, 7), 16);
        return `rgba(${r}, ${g}, ${b}, 0.3)`;
      }
      
      return baseColor;
    },
    interactions: [{ type: 'element-selected' }],
    state: {
      selected: {
        style: {
          fillOpacity: 1,
          stroke: '#000',
          lineWidth: 2,
        },
      },
      inactive: {
        style: {
          fillOpacity: 0.4,
        },
      },
    },
      tooltip: {
        showMarkers: false,
        customContent: (title, items) => {
          return `
            <div style="padding: 8px;">
              ${items
                .map(
                  item => `
                  <div>
                    <span style="color:${item.color}; margin-right: 8px;">●</span>
                   <strong> ${item.name}: ${Number(item.value).toLocaleString('en-IN')}</strong>
                  </div>
                `
                )
                .join('')}
            </div>
          `;
        },
      },
       columnStyle: {
        radius: [20, 20, 0, 0],
      },
    label: {
      // This fixes the typing error
      formatter: (datum: any) => ``,
        // style: {
        //   fontWeight: 'bolder'
        // }
    },

      xAxis: {
        title: {
        text: 'Amount In INR',
        style: {
          fontSize: 14,
          fill: 'rgb(5, 83, 154)',
        },
      },
    label: {
        style: {
           fill: 'black', // Color for x-axis labels (e.g., Amount)
        },
      formatter: (val: string) => Number(val).toLocaleString('en-IN'),
    },
  },
  yAxis: {
     title: {
        text: 'Buyer',
          rotate: 33,
        style: {
          fontSize: 14,
          fill: 'rgb(5, 83, 154)',
        },
      },
      label: {
        style: {
          fill: 'black',

        },
      },
  }
  };



    return(
        <Card title='Top 10 Invoiced Buyers' bordered={false}
              headStyle={{background: 'powderblue', color: 'black', fontWeight: 600, borderRadius: '12px 12px 0 0', padding: '3px 12px', lineHeight: '0.2px', borderBottom:0 }}
              style={{
                borderRadius: '8px',
                boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)',
                background: colors.background,
                height: cardHeight,
                display: 'flex',
                flexDirection: 'column'
              }}
              bodyStyle={{ padding: 0, height: '100%', display: 'flex', flexDirection: 'column' }}>

          <Spin spinning={loading}>
              <div style={{ position: 'relative', height: '100%' }}>
                {invInfo.length > 0 ? (
                  <Bar {...config}    
                    onReady={(plot) => {
                      // Listen for hover
                      // plot.on('element:mouseenter', (evt) => {
                      //   const data = evt.data?.data;
                      //   if (data) {
                      //     setHighlighted(data.buyer);
                      //     if (props.onBuyerHover) {
                      //       props.onBuyerHover(data.end_customer_id);
                      //     }
                      //   }
                      // });
  
                       // Remove highlight when mouse leaves
                        plot.on('element:mouseleave', () => {
                          setHighlighted(null);
                          props.onBuyerHover && props.onBuyerHover(0);
                        });

                         // Click for selection
                        plot.on('element:click', (evt) => {
                          const data = evt.data?.data;
                          if (data) {
                            setHighlighted(data.buyer);
                          if (props.onBuyerHover) {
                            props.onBuyerHover(data.end_customer_id);
                          }
                          }
                        });
                    }}
                  />
                ) : (
                // <Alert message='No data available☹️' type='info' showIcon style={{width: '181px', margin: 'auto'}}/>
                <Empty description="No records found" />
              )}
              </div>
            </Spin>
        </Card>
    )
}

export default CollectionInvAmountVsBuyer