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";

export interface RMInvoiceAmountVendorsGraphProps{
  fromDate?:any
  toDate?:any
  farmerId?:number
  type?:string
  division?:any
  unit?:number;
  onSupplierHover? : (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 RMInvoiceAmountVendorsGraph = (props:RMInvoiceAmountVendorsGraphProps) => {
  const [invInfo,setInvInfo] = useState<any[]>([])
  const rmService = new RMGrnService()
  const  cardHeight = '500px'
    const [loading, setLoading] = useState(false);
    const [selectedSupplier,setSelectedSupplier] = useState<number>()
    const [highlighted, setHighlighted] = useState<string | null>(null);
  

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

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

  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.farmerId != undefined){
      req.vendorId = props.farmerId
    }
    if(props.type != undefined){
      req.type = props.type
    }
    if(props.division != undefined){
      req.division = props.division
    }
    if(props.unit != undefined){
      req.unit = props.unit
    }
    rmService.getInvoiceAmountAgainstVendor(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{
      setLoading(false)
        AlertMessages.getErrorMessage(res.internalMessage)
        setInvInfo([])
      }
    })
  }

  const formatIndianNumber = (num: number) => {
  if (num >= 10000000) {
    const crValue = num / 10000000;
    return crValue % 1 === 0 ? `${crValue.toFixed(0)} Cr` : `${crValue.toFixed(2)} Cr`;
  }
  if (num >= 100000) {
    const lValue = num / 100000;
    return lValue % 1 === 0 ? `${lValue.toFixed(0)} L` : `${lValue.toFixed(2)} L`;
  }
  if (num >= 1000) {
    const kValue = num / 1000;
    return kValue % 1 === 0 ? `${kValue.toFixed(0)} K` : `${kValue.toFixed(2)} K`;
  }
  return num.toString();
};


const config = {
    data: invInfo.sort((a,b) => b.amount - a.amount),
    xField: 'amount',
    yField: 'farmer',
    seriesField: 'farmer', 
     color: (datum: any, defaultColor?: string) => {
      const index = invInfo.findIndex(item => item.farmer === datum.farmer);
      const baseColor = colorPalette[index % colorPalette.length];
      
      // Apply opacity if this is not the highlighted item
      if (highlighted && datum.farmer !== 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}: ₹${formatIndianNumber(item.value)}</strong>
                </div>
              `
              )
              .join('')}
          </div>
        `;
      },
    },
    columnStyle: {
      radius: [20, 20, 0, 0],
    },
    label: {
      formatter: (datum: any) => ``,
    },
    xAxis: {
      title: {
        text: 'Amount in INR',
        style: {
          fontSize: 14,
          fill: 'rgb(5, 83, 154)',
        },
      },
      label: {
        style: {
          fill: 'black',
        },
        formatter: (value) => `₹${formatIndianNumber(Number(value))}`,
      },
    },
    yAxis: {
      title: {
        text: 'Supplier',
        rotate: 33,
        style: {
          fontSize: 14,
          fill: 'rgb(5, 83, 154)',
        },
      },
      label: {
        style: {
          fill: 'black',
        },
      },
    }
  };




    return(
        <Card title='Top 10 Invoiced Suppliers' 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) => {
                   // Hover to highlight
                    // plot.on('element:mouseenter', (evt) => {
                    //   const data = evt.data?.data;
                    //   if (data) {
                    //     setHighlighted(data.farmer);
                    //     if (props.onSupplierHover) {
                    //       props.onSupplierHover(data.supplier_id);
                    //     }
                    //   }
                    // });

                    // Remove highlight when mouse leaves
                    plot.on('element:mouseleave', () => {
                      setHighlighted(null);
                      props.onSupplierHover && props.onSupplierHover(0);
                    });

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

export default RMInvoiceAmountVendorsGraph