import { CalendarOutlined } from '@ant-design/icons';
import { Column, ColumnConfig, Line, LineConfig } from '@ant-design/plots';
import { DateRangeReq } from '@gtpl/shared-models/analytics-data';
import { ProductWiseTargetStockReq } from '@gtpl/shared-models/sale-management';
import { MainDashboardService, WarehouseDashboardService } from '@gtpl/shared-services/analytics';
import { SaleOrderService } from '@gtpl/shared-services/sale-management';
import { Alert, Card, Col, DatePicker, Empty, Grid, Row, Spin, Table, Typography, message } from 'antd';
import appSettings from 'apps/services/config';
import axios from 'axios';
import dayjs from 'dayjs';
import { keys } from 'highcharts';
import moment, { Moment } from 'moment';
import React, { Children, useEffect, useState } from 'react';
const { Title } = Typography;
const { useBreakpoint } = Grid;

interface ChartDataItem {
    type: string;
    netWeightInKgs: number;
    grossWeightInKgs: number;
    slab: number;
    grossWeight: number;
}

interface CardData {
    totalDC: number;
    totalGII: number;
    totalBKN: number;
    totalBlk: number;
    totalIqf: number;
}

interface YieldData {
    lotNo: string;
    count: number;
    actualYield: number;
    sampleYield: number;
    honQnt: string;
    gradingHlsoQnt: string;
    deHeadingHlsoQty: string;
    totalHONQTy: number;
}

interface VarietyYieldData {
    varietyName: string;
    yieldPercentage: number;
    soakInKgs: string;
    productionInKgs: string;
}

const aquaticColors = {
    primary: '#1E88E5',
    secondary: '#4DB6AC',
    accent: '#FF7043',
    lightBlue: '#E1F5FE',
    darkBlue: '#0D47A1',
    sand: '#FFF3E0',
    success: '#81C784',
    danger: '#EF5350',
    tableHeader: '#B3E5FC'
};

const colors = {
    primary: '#2D3A4B',
    secondary: '#4A90E2',
    accent: '#FF6B6B',
    background: '#F8F9FA',
    textSecondary: '#6C757D',
    success: '#28A745',
    warning: '#FFC107',
    headerBg: 'powderblue',
    headerText: 'black',
    cardHover: '#F8F9FA'
  };

  const cardStyles = {
    main: {
        borderRadius: '12px',
        boxShadow: '0 4px 6px rgba(0, 0, 0, 0.05)',
        border: '1px solid #e8e8e8'
    },
    header: {
        background: colors.headerBg,
        color: colors.headerText,
        fontSize: '16px',
        fontWeight: 600,
        borderRadius: '12px 12px 0 0',
        padding: '3px 12px',
        lineHeight: '0.2px',
        borderBottom: 0
    }
  };

const ProductionDashboard = () => {
    const [data, setData] = useState<ChartDataItem[]>([]);
    const [cardData, setCardData] = useState<CardData>({
        totalDC: 0,
        totalGII: 0,
        totalBKN: 0,
        totalBlk: 0,
        totalIqf: 0
    });
    const [selectedDate, setSelectedDate] = useState<string>(dayjs().subtract(1,'days').format('YYYY-MM-DD'));
    const [loading, setLoading] = useState<boolean>(false);
    const [cardsLoading, setCardsLoading] = useState<boolean>(false);
    const [yieldData, setYieldData] = useState<YieldData[]>([]);
    const [yieldLoading, setYieldLoading] = useState(false);
    const [varietyYieldData, setVarietyYieldData] = useState<VarietyYieldData[]>([]);
    const [varietyYieldLoading, setVarietyYieldLoading] = useState(false);
    const screens = useBreakpoint();
    const [ targetPending, setTargetPending ] = useState<any[]>([])
    const [page, setPage] = useState(1);
    const service = new SaleOrderService();
    const [dateRange, setDateRange] = useState<Moment>(moment());
    const warehouseService = new WarehouseDashboardService()

    const getTargetPending=(date)=>{
      setLoading(true)
      const req = new ProductWiseTargetStockReq(date.format('YYYY-MM'))
      service.getProductWiseTargetStock(req).then((res)=>{
        if(res.status){
          setTargetPending(res.data)
          setLoading(false)  
        }else{
          setTargetPending([])
          setLoading(false)
        }
      }).catch(err=>{
        console.error(err)
        setLoading(false)
      })
    }

    // const updateDaywiseOpeningStockInfo=()=>{
    //   warehouseService.updateDaywiseOpeningStockInfo().then(res=>{
    //     console.log(res)
    //   })
    // }

    const handleDateChange=(date)=>{
      setDateRange(date)
      getTargetPending(date)
    }

    const fetchYieldData = async (date: string) => {
        setYieldLoading(true);
        try {
          const response = await axios.post(
            `${appSettings.anlytics_url}/mainDashboard/getYieldProductionReport`,
            { date }
          );
      
          if (response.data?.status) {
            const apiData = response.data.data;
      
            const dataMap = apiData.reduce((acc: Record<string, string[]>, item: any) => {
              const key = Object.keys(item)[0];
              acc[key] = item[key];
              return acc;
            }, {});
      
            const lotNos = dataMap["Lot No"] || [];
            const honQnts = dataMap["HON QNT"] || [];
            const gradingHlsoQnts = dataMap["GRADEING HLSO QNT"] || [];
            const yieldPers = dataMap["YIELD PER"] || [];
            const sampleYields = dataMap["SAMPLE YIELD"] || [];
            const deHeadingHlsoQtys = dataMap["DE HEADING HLSO QTY"] || [];
            const totalHONQTy = dataMap["Total HON Qty"] || 0;
      
            const transformedData = lotNos.map((lotNo: string, index: number) => ({
              lotNo: lotNo || '',
              count: index + 1,
              actualYield: parseFloat(yieldPers[index]) || 0,
              sampleYield: parseFloat(sampleYields[index]) || 0,
              honQnt: honQnts[index] || "0.000",
              gradingHlsoQnt: gradingHlsoQnts[index] || "0.000",
              deHeadingHlsoQty: deHeadingHlsoQtys[index] || "0.000",
              totalHONQTy: totalHONQTy ||0
            }));
      
            setYieldData(transformedData);
          }else{
            setYieldData([])
          }
        } catch (error) {
          console.error('Error fetching yield data:', error);
          message.error('Failed to load yield data');
          setYieldData([]);
        } finally {
          setYieldLoading(false);
        }
      };
      
    

    const fetchVarietyYieldData = async (date: string) => {
        setVarietyYieldLoading(true);
        try {
            const response = await axios.post(
                `${appSettings.anlytics_url}` + `/mainDashboard/getSoakingDataForProductionReport`
                ,
                { date }
            );

            if (response.data?.status) {
                const apiData = response.data.data;
                const products = apiData[1]?.product || [];
                const yieldPercentages = apiData[0]?.yieldPer || [];
                const soakInKgs = apiData[2]?.soakInKgs || [];
                const productionInKgs = apiData[3]?.productionInKgs || [];

                const transformedData = products.map((product: string, index: number) => ({
                    varietyName: product,
                    yieldPercentage: yieldPercentages[index] || 0,
                    soakInKgs: soakInKgs[index] || "0.000",
                    productionInKgs: productionInKgs[index] || "0.000"
                }));

                setVarietyYieldData(transformedData);
            }else{
              setVarietyYieldData([])
            }
        } catch (error) {
            console.error('Error fetching variety yield data:', error);
            message.error('Failed to load variety yield data');
            setVarietyYieldData([]);
        } finally {
            setVarietyYieldLoading(false);
        }
    };



    const fetchCardData = async (date: string) => {
        setCardsLoading(true);
        try {
            const [response1, response2] = await Promise.all([
                axios.post(`${appSettings.production_url}` + `/prod-log/getValueAdditionQuantitiesForProduction`, { date }),
                axios.post(`${appSettings.production_url}` + `/prod-log/getValueAdditionFourForProduction`, { date })
            ]);

            if (response1.data?.status && response2.data?.status) {
                setCardData({
                    totalDC: response1.data.data.totalDC || 0,
                    totalGII: response1.data.data.totalGII || 0,
                    totalBKN: response1.data.data.totalBKN || 0,
                    totalBlk: response2.data.data.totalBlk || 0,
                    totalIqf: response2.data.data.totalIqf || 0
                });
            }
        } catch (error) {
            console.error('Error fetching card data:', error);
            message.error('Failed to load production card data');
        } finally {
            setCardsLoading(false);
        }
    };

    const fetchProductionData = async (date: string) => {
        setLoading(true);
        try {
            const response = await axios.post(
                `${appSettings.anlytics_url}` + `/mainDashboard/getTotalProductionForDashboard`
                ,
                { date }
            );

            if (response.data?.status) {
                const apiData = response.data.data;
                const categories = apiData[0]?.category || [];
                const slabs = apiData[1]?.slab || [];
                const grossWeights = apiData[2]?.grossWeight || [];
                const netWeights = apiData[3]?.netWeightInKgs || [];
                const grossWeightsKgs = apiData[4]?.grossWeightInKgs || [];

                const transformedData = categories.map((category: string, index: number) => ({
                    type: category,
                    slab: slabs[index] || 0,
                    grossWeight: grossWeights[index] || 0,
                    netWeightInKgs: netWeights[index] || 0,
                    grossWeightInKgs: grossWeightsKgs[index] || 0
                }));

                setData(transformedData);
            }else{
              setData([])
            }
        } catch (error) {
            console.error('Error fetching production data:', error);
            message.error('Failed to load production data');
            setData([]);
        } finally {
            setLoading(false);
        }
    };

    const onDateChange = (date: moment.Moment | null, dateString: string) => {
        setSelectedDate(dateString);
        fetchCardData(dateString);
        fetchProductionData(dateString);
        fetchYieldData(dateString);
        fetchVarietyYieldData(dateString);
    };

    useEffect(() => {
        fetchCardData(selectedDate);
        fetchProductionData(selectedDate);
        fetchYieldData(selectedDate);
        fetchVarietyYieldData(selectedDate);
        getTargetPending(dateRange)
        // updateDaywiseOpeningStockInfo()
    }, []);

    const formatNumber = (num: number) => {
        return num.toLocaleString('en-IN', { maximumFractionDigits: 2 });
    };

    const getChartConfig = (): ColumnConfig => {
      return {
          data: data.map(item => ({
              type: item.type,
              value: item.slab,
              netWeightInKgs: item.netWeightInKgs,
              grossWeightInKgs: item.grossWeightInKgs,
              grossWeight: item.grossWeight
          })),
          xField: 'type',
          yField: 'value',
          height: screens.xs ? 300 : 400,
          label: {
              position: 'top',
              style: {
                  fill: '#000',
                  fontSize: screens.xs ? 10 : 12,
                  fontWeight: 500,
              },
              formatter: (val: any) => `${val.value.toLocaleString()}`,
          },
          yAxis: {
              label: {
                  formatter: (val: string) => `${val.toLocaleString()}`,
              },
              title: {
                  text: 'Slab Count',
              },
          },
          xAxis: {
              label: {
                  rotate: screens.xs ? -90 : -45,
                  autoHide: false,
                  style: {
                      textAlign: 'right',
                      fontSize: screens.xs ? 8 : 10,
                  },
              },
          },
          columnStyle: {
              widthRatio: screens.xs ? 0.4 : 0.6,
          },
          color: aquaticColors.primary,
          tooltip: {
              customContent: (title: string, items: any[]) => {
                  const itemData = data.find(d => d.type === title);
                  if (!itemData) return null;
  
                  return (
                      <div style={{ padding: '8px', background: '#fff' }}>
                          <div style={{ fontWeight: 'bold'}}>{title}</div>
                          <div style={{ fontWeight: 'bold', marginBottom: '8px' }}>Slab: {itemData.slab}</div>
                          <div>Gross/unit: {itemData.grossWeight}</div>
                          <div>Net: {itemData.netWeightInKgs} KG</div>
                          <div>Gross: {itemData.grossWeightInKgs} KG</div>
                      </div>
                  );
              }
          },
          theme: {
              colors10: [aquaticColors.primary],
              colors20: [aquaticColors.primary],
          },
      };
  };

    const getLineChartConfig = (): LineConfig => {
        // Create a modified dataset that ensures unique handling internally
        const uniqueVarietyData = varietyYieldData.map((item, index) => ({
            ...item,
            // Keep original name for display
            displayName: item.varietyName,
            // Create a unique name for rendering
            uniqueName: `${item.varietyName}__${index}`,
            dataIndex: index,
        }));
    
        return {
            data: uniqueVarietyData,
            xField: 'uniqueName', // Use uniqueName to ensure separation of duplicate entries
            yField: 'yieldPercentage',
            color: () => '#007bff', // Line color set to blue
            lineStyle: {
                lineWidth: 2,
            },
            point: {
                size: 6,
                shape: 'circle',
                style: (datum) => ({
                    fill: datum.yieldPercentage >= 0 ? aquaticColors.success : aquaticColors.danger,
                    stroke: '#fff',
                    lineWidth: 2,
                }),
            },
            yAxis: {
                nice: true,
                title: {
                    text: 'Yield Percentage (%)',
                    style: { fill: '#666' }
                },
                label: {
                    formatter: (val: string) => `${val}%`,
                },
                grid: {
                    line: {
                        style: {
                            stroke: '#eee',
                            lineDash: [4, 4],
                        },
                    },
                },
            },
            xAxis: {
                title: {
                    text: 'Variety Name',
                    style: { fill: '#666' }
                },
                label: {
                    autoRotate: true,
                    formatter: (val: string) => {
                        // Extract the original display name by removing the unique suffix
                        return val.split('__')[0];
                    },
                    style: {
                        fontSize: screens.xs ? 8 : 10,
                    }
                }
            },
            tooltip: {
                showCrosshairs: true,
                customContent: (title: string, items: any[]) => {
                    if (!items || items.length === 0) return null;
                    
                    const dataIndex = items[0].data.dataIndex;
                    const originalData = varietyYieldData[dataIndex];
                    
                    const formatPercentage = (value: number) => {
                        const absValue = Math.abs(value);
                        return value < 0 ? `-${absValue}%` : `${absValue}%`;
                    };
    
                    return (
                        <div style={{ padding: '8px', background: '#fff' }}>
                            <div style={{ fontWeight: 'bold', marginBottom: '8px' }}>
                                Variety: {originalData.varietyName}
                            </div>
                            <div style={{ 
                                color: originalData.yieldPercentage < 0 ? aquaticColors.danger : aquaticColors.success,
                                fontWeight: 'bold'
                            }}>
                                Yield: {formatPercentage(originalData.yieldPercentage)}
                            </div>
                            <div>Soak Quantity: {originalData.soakInKgs} KG</div>
                            <div>Production: {originalData.productionInKgs} KG</div>
                        </div>
                    );
                }
            },
        };
    };
    

    const getGroupedColumnConfig = (): ColumnConfig => {
        // Transform data for grouped column chart using reduce instead of flatMap
        const chartData = yieldData.reduce((acc: Array<{
            // type: number;
            category: string;
            value: number;
            actualYield: number;
            sampleYield: number;
            honQnt: string;
            gradingHlsoQnt: string;
            deHeadingHlsoQty: string;
            lotNo: string,
        }>, item) => {
            acc.push({
                // type: item.count,
                lotNo: item.lotNo,
                category: 'Actual Yield',
                value: item.actualYield,
                actualYield: item.actualYield,
                sampleYield: item.sampleYield,
                honQnt: item.honQnt,
                gradingHlsoQnt: item.gradingHlsoQnt,
                deHeadingHlsoQty: item.deHeadingHlsoQty
            });
            acc.push({
                // type: item.count,
                lotNo: item.lotNo,
                category: 'Sample Yield',
                value: item.sampleYield,
                actualYield: item.actualYield,
                sampleYield: item.sampleYield,
                honQnt: item.honQnt,
                gradingHlsoQnt: item.gradingHlsoQnt,
                deHeadingHlsoQty: item.deHeadingHlsoQty
            });
            
            return acc;
        }, []);
    
        return {
            data: chartData,
            xField: 'lotNo',
            yField: 'value',
            seriesField: 'category',
            isGroup: true,
            height: screens.xs ? 300 : 400,
            color: ({ category }) => category === 'Actual Yield' ? aquaticColors.primary : aquaticColors.success,
            legend: { position: 'top' },
            yAxis: {
                label: { formatter: (val) => `${val}%` },
                title: { text: 'Yield Percentage (%)' }
            },
            xAxis: {
                label: {
                  rotate: -45,
                  offset: 10,
                  style: {
                    fontSize: 12, textAlign: 'right',
                  },
                },
                title: {
                  text: 'Lot No',
                },
              },                          
            columnStyle: { radius: [4, 4, 0, 0] },
            interactions: [{ type: 'element-active' }],
            tooltip: {
                showTitle: true,
                title: (title, items) => `Lot No: ${title}`,
                shared: false,
                showMarkers: true,
                customContent: (title, items) => {
                    if (!items || items.length === 0) return null;
                    
                    const itemData = items[0].data;
                    const formatPercentage = (val) => `${Math.round(val * 100) / 100}%`;
    
                    return (
                        <div style={{ 
                            padding: '8px', 
                            background: '#fff',
                            minWidth: '200px'
                        }}>
                            <div style={{ fontWeight: 'bold', marginBottom: '8px' }}>
                                {title}
                            </div>
                            <div style={{ 
                                display: 'flex', 
                                justifyContent: 'space-between',
                                marginBottom: '4px'
                            }}>
                                <span>Actual Yield:</span>
                                <span style={{ color: aquaticColors.primary, fontWeight: 500 }}>
                                    {formatPercentage(itemData.actualYield)}
                                </span>
                            </div>
                            <div style={{ 
                                display: 'flex', 
                                justifyContent: 'space-between',
                                marginBottom: '4px'
                            }}>
                                <span>Sample Yield:</span>
                                <span style={{ color: aquaticColors.success, fontWeight: 500 }}>
                                    {formatPercentage(itemData.sampleYield)}
                                </span>
                            </div>
                            <div style={{ marginTop: '8px', borderTop: '1px solid #f0f0f0', paddingTop: '8px' }}>
                                <div>HON Quantity: {itemData.honQnt} KG</div>
                                <div>Grading HLSO: {itemData.gradingHlsoQnt} KG</div>
                                <div>De-heading HLSO: {itemData.deHeadingHlsoQty} KG</div>
                            </div>
                        </div>
                    );
                }
            }
        };
    };


    const productionCards = [
        { title: 'DC Kgs', value: formatNumber(cardData.totalDC), color: aquaticColors.primary },
        { title: 'GII Kgs', value: formatNumber(cardData.totalGII), color: aquaticColors.secondary },
        { title: 'BKN Kgs', value: formatNumber(cardData.totalBKN), color: aquaticColors.accent },
        { title: 'IQF', value: formatNumber(cardData.totalIqf), color: aquaticColors.success },
        { title: 'BLK', value: formatNumber(cardData.totalBlk), color: aquaticColors.danger }
    ];

    const pendingTargetColumns: any = [
      {
        title: 'S No',
        dataIndex: 'key',
        key: 'key',
        responsive: ['sm'],
        width: 80,
        render: (text, object, index) => index + 1 
      },
      {
        title: 'Product',
        dataIndex: 'product',
        key: 'product',
      },
      {
        title: <div style={{textAlign: 'center'}}>Month Target (Tons)</div>,
        dataIndex: 'quantity',
        key: 'quantity',
        align: 'right',
        render:(text)=> text.toFixed(2)
      },
      {
        title: 'Target Achieved (Tons)',
        children:[
          {
            title: <div style={{textAlign: 'center'}}>Existing Shock</div>,
            dataIndex: 'exist',
            key: 'exist',
            align: 'right',
            render:(text)=> text.toFixed(2)
          },
          {
            title: <div style={{textAlign: 'center'}}>Fresh Production</div>,
            dataIndex: 'fresh',
            key: 'fresh',
            align: 'right',
            render:(text)=> text.toFixed(2)
          }
        ]
      },
      {
        title: <div style={{textAlign: 'center'}}>Target Production (Tons)</div>,
        dataIndex: 'target',
        key: 'target',
        align: 'right',
        render:(text)=> text.toFixed(2)
      },
      {
        title: <div style={{textAlign: 'center'}}>Target (%)</div>,
        dataIndex: 'targetPer',
        key: 'targetPer',
        align: 'right',
        render:(text)=> text.toFixed(2)
      }
    ]


    const totalTarget = targetPending.reduce((sum, item) => sum + (item.quantity || 0), 0);
    const totalAchieved = targetPending.reduce((sum, item) => sum + ((item.exist || 0) + (item.fresh || 0)),0);    
    const pending = targetPending.reduce((sum, item) => sum + (item.target || 0), 0);
    
    const achievedPercent = totalTarget > 0 ? ((totalAchieved / totalTarget) * 100).toFixed(0) : 0;
    const pendingPercent = totalTarget > 0 ? ((pending / totalTarget) * 100).toFixed(0) : 0;
    
    

    return (
        <div style={{ padding: '24px', background: colors.background }}>
          <Row justify="space-between" align="middle" style={{ marginBottom: 24 }}>
            <Col>
              <Title level={3} style={{ margin: 0, color: colors.primary }}>
                Production Dashboard
              </Title>
              {/* <Typography.Text type="secondary" style={{ color: colors.textSecondary }}>
                Real-time production metrics and analytics
              </Typography.Text> */}
            </Col>
            <Col>
              <DatePicker
                onChange={onDateChange}
                defaultValue={moment(selectedDate)}
                allowClear={false}
                format="YYYY-MM-DD"
                style={{ 
                  width: 280,
                  borderRadius: '8px',
                  borderColor: "#1890ff",
                }}
                suffixIcon={<CalendarOutlined style={{ color: "#1890ff" }} />}
                size="large"
              />
            </Col>
          </Row>
    
          <Spin spinning={loading || cardsLoading}>
            <Row gutter={[24, 24]} style={{ marginBottom: 24 }}>
              <Col xs={24}>
                <Card
                  title="Production Overview"
                  headStyle={{...cardStyles.header, textAlign: 'center'}}
                  style={cardStyles.main}
                  bodyStyle={{ padding: '16px', height: data.length > 0 ? 350: 'auto' }}
                >
                  {data.length > 0 ? (
                    <Column {...getChartConfig()} />
                  ) : (
                    // <Alert message='No data available☹️' type='info' showIcon style={{ width: "181px", margin: "auto" }}/>
                    <Empty description="No records found" />
                  )}
                </Card>
              </Col>
            </Row>

            <Row gutter={[24, 24]} style={{ marginTop: '24px', flexWrap: 'nowrap' }} wrap={false}>
              {productionCards.map((card, index) => (
                <Col key={index} flex={1}>
                  <Card
                    title={card.title}
                    headStyle={{
                      ...cardStyles.header,
                      background: card.color,
                      fontSize: screens.xs ? '14px' : '16px',
                      textAlign: 'center',
                    }}
                    style={cardStyles.main}
                    bodyStyle={{ 
                      padding: '16px',
                      textAlign: 'center',
                      fontSize: '20px',
                      fontWeight: 600,
                      minHeight: screens.xs ? 'auto' : '50px'
                    }}
                  >
                    {card.value}
                  </Card>
                </Col>
              ))}
            </Row>

            <Row gutter={[24, 24]} style={{marginTop: '24px'}}>
              <Col xs={24} md={12}>
                <Card
                  title="HON TO HLSO YIELD"
                  headStyle={{...cardStyles.header, textAlign: 'left'}}
                  style={cardStyles.main}
                  bodyStyle={{ padding: '16px', height: yieldData.length > 0 && varietyYieldData.length> 0 ? 400: 'auto'}}
                  extra={
                    <Typography.Text strong type="secondary" style={{ color: "black", padding: '4px 8px',whiteSpace: 'nowrap'}}>
                      Total HON Qty: {(yieldData[0]?.totalHONQTy || 0).toLocaleString()} KG's
                    </Typography.Text>
                  }
                >
                  {yieldData.length > 0 ? (
                    <Column {...getGroupedColumnConfig()} />
                  ) : (
                    // <Alert message='No data available☹️' type='info' showIcon style={{width: '181px', margin: 'auto'}}/>
                    <Empty description="No records found" />
                  )}
                </Card>
              </Col>

              <Col xs={24} md={12}>
                <Card
                  title="Soaking Report"
                  headStyle={{...cardStyles.header, textAlign: 'left'}}
                  style={cardStyles.main}
                  bodyStyle={{ padding: '16px', height: yieldData.length > 0 && varietyYieldData.length > 0 ? 400 : 'auto' }}
                >
                  {varietyYieldData.length > 0 ? (
                    <Line {...getLineChartConfig()} />
                  ) : (
                    // <Alert message='No data available☹️' type='info' showIcon style={{width: '181px', margin: 'auto'}}/>
                    <Empty description="No records found" />
                  )}
                </Card>
              </Col>
            </Row>
            <Row gutter={[24, 24]} style={{ marginTop: '24px', flexWrap: 'nowrap' }} wrap={false}>
              <Col xs={24}>
                <Card 
                  title='Target vs Achievement'
                  headStyle={{ ...cardStyles.header, textAlign: 'left' }}
                  style={cardStyles.main}
                  bodyStyle={{ padding: '16px', height: targetPending.length > 0 ? 400 : 'auto' }}
                  extra={
                    <DatePicker
                      onChange={handleDateChange}
                      value={dateRange}
                      picker='month'
                      size='large'
                      allowClear={false}
                      suffixIcon={<CalendarOutlined style={{ color: colors.primary }} />}
                    />
                  }
                >
                  <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
                    <Col span={8}>
                      <div style={{ 
                        background: '#f8d7da',
                        padding: '4px', 
                        textAlign: 'center', 
                        borderRadius: '8px', 
                        height: 'auto'
                      }}>
                        <h3 style={{ margin: '0 0 8px 0' }}>Production Target</h3>

                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '0 8px' }}>
                          <span style={{ fontWeight: 'bold', fontSize: '24px' }}>{totalTarget.toFixed(2)}</span>
                          <span style={{ fontSize: '16px' }}>Tons</span>
                          <span style={{ fontWeight: 'bold', fontSize: '20px' }}>100%</span>
                        </div>

                      </div>
                    </Col>

                    <Col span={8}>
                      <div style={{ 
                        background: '#c8e6c9',
                        padding: '4px', 
                        textAlign: 'center', 
                        borderRadius: '8px', 
                        height: 'auto'
                      }}>
                        <h3 style={{ margin: '0 0 8px 0' }}>Target Achieved</h3>

                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '0 8px' }}>
                          <span style={{ fontWeight: 'bold', fontSize: '24px' }}>{totalAchieved.toFixed(2)}</span>
                          <span style={{ fontSize: '16px' }}>Tons</span>
                          <span style={{ fontWeight: 'bold', fontSize: '20px' }}>{achievedPercent}%</span>
                        </div>

                      </div>
                    </Col>

                    <Col span={8}>
                      <div style={{ 
                        background: '#ef6c00',
                        padding: '4px', 
                        textAlign: 'center', 
                        borderRadius: '8px', 
                        height: 'auto',
                        color: '#fff'
                      }}>
                        <h3 style={{ margin: '0 0 8px 0' }}>Pending Production</h3>

                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '0 8px' }}>
                          <span style={{ fontWeight: 'bold', fontSize: '24px' }}>{pending.toFixed(2)}</span>
                          <span style={{ fontSize: '16px' }}>Tons</span>
                          <span style={{ fontWeight: 'bold', fontSize: '20px' }}>{pendingPercent}%</span>
                        </div>

                      </div>
                    </Col>
                  </Row>
                  {targetPending.length > 0 ? (
                    <Spin spinning={loading}>
                      <Table 
                        dataSource={targetPending}
                        pagination={false} 
                        size='middle' bordered rowKey='key'
                        columns={pendingTargetColumns}
                        scroll={{ x: 200,y: 210 }}
                        summary={() => {
                          let totalQuantity = 0;
                          let totalExist = 0;
                          let totalFresh = 0;
                          let target = 0;
                      
                          targetPending.forEach(item => {
                            totalQuantity += item.quantity || 0;
                            totalExist += item.exist || 0;
                            totalFresh += item.fresh || 0;
                            target += item.target || 0;
                          });
                      
                          return (
                            <Table.Summary.Row>
                              <Table.Summary.Cell index={0}></Table.Summary.Cell>
                              <Table.Summary.Cell index={1}><strong>Total</strong></Table.Summary.Cell>
                              <Table.Summary.Cell index={2}><strong>{totalQuantity.toFixed(2)}</strong></Table.Summary.Cell>
                              <Table.Summary.Cell index={3}><strong>{totalExist.toFixed(2)}</strong></Table.Summary.Cell>
                              <Table.Summary.Cell index={4}><strong>{totalFresh.toFixed(2)}</strong></Table.Summary.Cell>
                              <Table.Summary.Cell index={5}><strong>{target.toFixed(2)}</strong></Table.Summary.Cell>
                            </Table.Summary.Row>
                          );
                        }}
                      />
                    </Spin>
                  ) : (
                    // <Alert 
                    //   message="No data available ☹️" 
                    //   type="info" 
                    //   showIcon 
                    //   style={{ width: "186px", margin: "auto" }}
                    // />
                    <Empty description="No records found" />
                  )}
                </Card>
              </Col>
            </Row>
          </Spin>
        </div>
      )
}

export default ProductionDashboard;