// import React, { useEffect, useState } from 'react';
// import { Column, ColumnConfig } from '@ant-design/plots';
// import { Card, DatePicker, Typography as AntTypography, Spin, message, Select, Grid, Col, Row, Typography, Tooltip } from 'antd';
// import type { RangePickerProps } from 'antd/es/date-picker';
// import axios from 'axios';
// import dayjs from 'dayjs';
// import appSettings from 'apps/services/config';
// import { AlertOutlined, CalendarOutlined, ExclamationCircleOutlined, UserOutlined } from '@ant-design/icons';
// import moment, { Moment } from 'moment';

// const { RangePicker } = DatePicker;
// const { Title } = Typography;
// const { Option } = Select;
// const { useBreakpoint } = Grid;

// interface ChartDataItem {
//   month: string;
//   type: 'Deliveries' | 'Orders';
//   status: string;
//   value: number;
// }

// interface ExportOrder {
//   month: string;
//   accepted: number;
//   pending: number;
// }

// interface EndCustomer {
//   endCustomerId: number;
//   endCustomerName: string;
// }

// const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

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

// const ExportDashboard = () => {
//   const [data, setData] = useState<ChartDataItem[]>([]);
//   const [year, setYear] = useState(moment().year());
//   const [dateRange, setDateRange] = useState<[Moment, Moment] | null>([
//     moment().subtract(2, 'days'),
//     moment()
//   ]);
//   const currentYear = moment().year();
//   const [overdueOrders, setOverdueOrders] = useState<number>(0);
//   const [loading, setLoading] = useState<boolean>(false);
//   const [endCustomers, setEndCustomers] = useState<EndCustomer[]>([]);
//   const [selectedCustomerId, setSelectedCustomerId] = useState<number | null>(null);
//   const screens = useBreakpoint();

//   const fetchEndCustomers = async () => {
//     try {
//       const response = await axios.post(`${appSettings.masters_url}` + `/endCustomers/getAllEndCustomersDropData`
//       );
//       if (response.data.status) {
//         setEndCustomers(response.data.data);
//       }
//     } catch (error) {
//       console.error('Error fetching end customers:', error);
//       message.error('Failed to load end customers');
//     }
//   };

//   const fetchDataWithYear = async (fromDate: string, toDate: string, customerId?: number, selectedYear?: number) => {
//     setLoading(true);
//     try {
//       const [overdueRes, monthlyRes] = await Promise.all([
//         axios.post(
//           `${appSettings.anlytics_url}` + `/mainDashboard/getOverDueSaleOrders`
//           , {
//             fromDate,
//             toDate
//           }, { timeout: 10000 }),
//         axios.post(
//           `${appSettings.anlytics_url}` + `/mainDashboard/getMonthWiseSaleOrders`
//           , {
//             buyerId: customerId || null, 
//             year: selectedYear || year // Use the provided year or fall back to state
//           }, { timeout: 10000 })
//       ]);

//       const overdueCount = overdueRes.data?.data?.[0]?.count || 0;
//       setOverdueOrders(parseInt(overdueCount));

//       const acceptedData = monthlyRes.data?.data?.[0]?.['Total Accepted'] || [];
//       const pendingData = monthlyRes.data?.data?.[1]?.['Total Pending'] || [];
//       const openData = monthlyRes.data?.data?.[2]?.['Open'] || [];
//       const closeData = monthlyRes.data?.data?.[3]?.['Close'] || [];
//       const cancelData = monthlyRes.data?.data?.[4]?.['Cancel'] || [];

//       const transformedData = monthNames.map((month, index) => ({
//         month,
//         accepted: parseInt(acceptedData[index]) || 0,
//         pending: parseInt(pendingData[index]) || 0,
//         open: parseInt(openData[index]) || 0,
//         close: parseInt(closeData[index]) || 0,
//         cancel: parseInt(cancelData[index]) || 0,
//       }));

//       const chartData = transformedData.reduce((acc: ChartDataItem[], item) => {
//         return acc.concat([
//           { month: item.month, type: 'Deliveries', status: 'Total Shipments', value: item.accepted },
//           { month: item.month, type: 'Deliveries', status: 'Overdue', value: item.pending },
      
//           { month: item.month, type: 'Orders', status: 'Open', value: item.open },
//           { month: item.month, type: 'Orders', status: 'Closed', value: item.close },
//           { month: item.month, type: 'Orders', status: 'Cancelled', value: item.cancel },
//         ]);
//       }, []);
      
      

//       setData(chartData);
//     } catch (error) {
//       console.error('Error fetching export data:', error);
//       message.error('Failed to load export data. Please check your connection.');
//       setOverdueOrders(0);
//       setData([]);
//     } finally {
//       setLoading(false);
//     }
//   };

//   const fetchData = async (fromDate: string, toDate: string, customerId?: number) => {
//     fetchDataWithYear(fromDate, toDate, customerId, year);
//   };

//   const handleDateChange = (dates, dateStrings) => {
//     setDateRange(dates);
//     if (dateStrings[0] && dateStrings[1]) {
//       fetchDataWithYear(dateStrings[0], dateStrings[1], selectedCustomerId || undefined, year);
//     }
//   };

//   const handleCustomerChange = (customerId: number) => {
//     setSelectedCustomerId(customerId);
//     if (dateRange && dateRange[0] && dateRange[1]) {
//       const dateStrings = [
//         dateRange[0].format('YYYY-MM-DD'),
//         dateRange[1].format('YYYY-MM-DD')
//       ];
//       fetchDataWithYear(dateStrings[0], dateStrings[1], customerId, year);
//     } else {
//       const currentYear = dayjs().format('YYYY');
//       const fromDate = `${currentYear}-01-01`;
//       const toDate = dayjs().format('YYYY-MM-DD');
//       fetchDataWithYear(fromDate, toDate, customerId, year);
//     }
//   };

//   const handleYearChange = (date) => {
//     const selectedYear = date.year();
//     setYear(selectedYear);
    
//     if (dateRange && dateRange[0] && dateRange[1]) {
//       const dateStrings = [
//         dateRange[0].format('YYYY-MM-DD'),
//         dateRange[1].format('YYYY-MM-DD')
//       ];
      
//       fetchDataWithYear(dateStrings[0], dateStrings[1], selectedCustomerId || undefined, selectedYear);
//     }
//   };

//   useEffect(() => {
//     fetchEndCustomers();
//     const defaultFromDate = dayjs().subtract(2, 'day').format('YYYY-MM-DD');
//     const defaultToDate = dayjs().format('YYYY-MM-DD');
//     fetchData(defaultFromDate, defaultToDate);
//   }, []);

//   const getConfig = (): ColumnConfig => {
//     return {
//       data,
//       isGroup: true,
//       isStack: true,
//       xField: 'month',
//       yField: 'value',
//       groupField: 'type',
//       seriesField: 'status',      
//       height: screens.md ? 400 : 300,
//       color: ({ status }) => {
//         switch (status) {
//           case 'Total Shipments': return colors.warning;
//           case 'Overdue': return colors.accent;
//           case 'Open': return colors.primary;
//           case 'Closed': return aquaticColors.success;
//           case 'Cancelled': return colors.textSecondary;
//           default: return '#ccc';
//         }
//       },
//       label: {
//         position: 'middle',
//         style: {
//           fill: '#fff',
//           fontSize: 12,
//           fontWeight: 500,
//         },
//         layout: [
//           { type: 'interval-adjust-position' },
//           { type: 'interval-hide-overlap' },
//           { type: 'adjust-color' },
//         ],
//       },            
//       legend: {
//         position: screens.xs ? 'bottom' : 'top-right',
//         itemName: { style: { fill: colors.primary } },
//       },
//       yAxis: {
//         title: { text: 'Total SOs' },
//         grid: { line: { style: { stroke: '#f0f0f0' } } },
//       },
//       xAxis: {
//         title: { text: 'Month' },
//         label: {
//           rotate: screens.xs ? -45 : 0,
//           style: { fontSize: screens.xs ? 10 : 12 },
//         },
//       },
//       tooltip: {
//         shared: true,
//         showMarkers: false,
//       },
//       columnStyle: {
//         radius: [4, 4, 0, 0],
//         widthRatio: screens.xs ? 0.4 : 0.3,
//       },
//     };
//   };
  
  
//   const colors = {
//     primary: '#2D3A4B',
//     secondary: '#4A90E2',
//     accent: '#FF6B6B',
//     background: '#FFFFFF',
//     textSecondary: '#6C757D',
//     success: '#28A745',
//     warning: '#FFC107',
//     headerBg: '#4A90E2',
//     headerText: '#FFFFFF',
//     chartBackground: '#F8FAFC'
//   };

//   return (
//     <div style={{ 
//       padding: '24px', 
//       background: colors.background,
//       borderRadius: '12px',
//       height: '100%',
//       display: 'flex',
//       flexDirection: 'column',
//       gap: '16px',
//       boxShadow: '0 8px 16px rgba(0,0,0,0.05)'
//     }}>
//       <Spin spinning={loading}>
//       <Row justify="space-between" align="middle" gutter={[16, 16]}>
//         <Col flex="auto">
//           <Title level={4} style={{ margin: 0, color: colors.primary }}>
//             Export Analytics
//             <AntTypography.Text type="secondary" style={{ 
//               display: 'block', 
//               fontSize: '14px',
//               color: colors.textSecondary
//             }}>
//               Sales order performance metrics
//             </AntTypography.Text>
//           </Title>
//         </Col>
//         <Col>
//         <Tooltip title="Year applies to below Graph">
//           <DatePicker
//             picker="year"
//             onChange={handleYearChange}
//             defaultValue={moment().year(year)}
//             style={{ width: 150 }}
//             suffixIcon={<CalendarOutlined style={{ color: colors.textSecondary }} />}
//             size="middle"
//             placeholder="Select Year"
//             disabledDate={(current) => current && current > moment().endOf('year')}
//           />
//         </Tooltip>
//       </Col>
//         <Col>
//           <Row gutter={[16, 16]} align="middle">
//             <Col>
//               <Select
//                 style={{ width: 250 }}
//                 placeholder="Select Buyer"
//                 onChange={handleCustomerChange}
//                 showSearch
//                 allowClear
//                 optionFilterProp="children"
//                 filterOption={(input, option) =>
//                   (option?.children as string)?.toLowerCase().includes(input.toLowerCase())
//                 }
//                 suffixIcon={<UserOutlined style={{ color: colors.textSecondary }} />}
//                 dropdownStyle={{
//                   borderRadius: '8px',
//                   boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
//                 }}
//                 size="middle"
//               >
//                 {endCustomers.map(customer => (
//                   <Option key={customer.endCustomerId} value={customer.endCustomerId}>
//                     {customer.endCustomerName}
//                   </Option>
//                 ))}
//               </Select>
//             </Col>

//             <Col>
//               <Tooltip title="Date range applies to overdue orders">
//                 <div style={{ position: 'relative', display: 'flex', alignItems: 'center' }}>
//                   <RangePicker
//                     onChange={handleDateChange}
//                     value={dateRange}
//                     style={{ width: 250 }}
//                     suffixIcon={<CalendarOutlined style={{ color: colors.textSecondary }} />}
//                     size="middle"
//                   />
//                 </div>
//               </Tooltip>
//             </Col>
            
//             <Col>
//               <Card
//                 bordered={false}
//                 style={{ 
//                   background: `${colors.accent}10`,
//                   borderRadius: '8px',
//                   width: 200,
//                   borderLeft: `4px solid ${colors.accent}`,
//                   boxShadow: '0 4px 12px rgba(0,0,0,0.05)'
//                 }}
//                 bodyStyle={{ 
//                   padding: '12px 16px',
//                   display: 'flex',
//                   alignItems: 'center',
//                   gap: '12px'
//                 }}
//               >
//                 <AlertOutlined style={{ 
//                   fontSize: '20px',
//                   color: colors.accent 
//                 }}/>
//                 <div>
//                   <AntTypography.Text strong style={{ 
//                     color: colors.textSecondary,
//                     fontSize: '12px'
//                   }}>
//                     Overdue Orders
//                   </AntTypography.Text>
//                   <Title level={3} style={{ 
//                     margin: '4px 0 0 0',
//                     color: colors.accent
//                   }}>
//                     {overdueOrders}
//                   </Title>
//                 </div>
//               </Card>
//             </Col>
//           </Row>
//         </Col>
//       </Row>


//         <Card
//           bordered={false}
//           bodyStyle={{ 
//             padding: '16px',
//             height: 400,
//             background: colors.chartBackground,
//             borderRadius: '12px'
//           }}
//           style={{
//             boxShadow: '0 4px 12px rgba(0,0,0,0.05)'
//           }}
//         >
//             <Column {...getConfig()} />
//         </Card>
//       </Spin>
//     </div>
//   );
// };

// export default ExportDashboard;