'use client';

import React, { useEffect, useState } from 'react';
import { apiRequest } from '@/lib/api';
import { useAuth } from '@/context/auth-context';
import Link from 'next/link';
import OverviewCharts from '@/components/dashboard/OverviewCharts';
import {
  DollarSign,
  ShoppingBag,
  MessageCircle,
  RefreshCw,
  Clock,
  CheckCircle,
  AlertCircle,
  TrendingUp,
  Zap,
  Activity,
  Calendar,
  Download,
  FileText,
  X,
} from 'lucide-react';

interface OrderItem {
  id: string;
  productName: string;
  quantity: number;
  lineTotal: number;
  unitPrice: number;
}

interface Order {
  id: string;
  orderNumber: string;
  totalAmount: number;
  status: string;
  paymentStatus: string;
  customerName: string;
  createdAt: string;
  items?: OrderItem[];
}

interface SyncLog {
  id: string;
  syncType: string;
  status: string;
  recordsProcessed: number;
  recordsFailed: number;
  startedAt: string;
}

function formatTimeAgo(dateStr: string) {
  try {
    const diffMs = Date.now() - new Date(dateStr).getTime();
    const diffMins = Math.floor(diffMs / 60000);
    if (diffMins < 1) return 'Just now';
    if (diffMins < 60) return `${diffMins} min${diffMins > 1 ? 's' : ''} ago`;
    const diffHrs = Math.floor(diffMins / 60);
    if (diffHrs < 24) return `${diffHrs} hr${diffHrs > 1 ? 's' : ''} ago`;
    const diffDays = Math.floor(diffHrs / 24);
    return `${diffDays} day${diffDays > 1 ? 's' : ''} ago`;
  } catch {
    return 'Some time ago';
  }
}

export default function DashboardHome() {
  const { user, updateUser } = useAuth();
  const [orders, setOrders] = useState<Order[]>([]);
  const [syncLogs, setSyncLogs] = useState<SyncLog[]>([]);
  const [sessionsCount, setSessionsCount] = useState(0);
  const [loading, setLoading] = useState(true);
  const [timeRange, setTimeRange] = useState<'24h' | '7d' | '30d' | 'all'>('7d');
  const [dropdownOpen, setDropdownOpen] = useState(false);

  // Report Generator States
  const [isReportModalOpen, setIsReportModalOpen] = useState(false);
  const [reportType, setReportType] = useState<'today' | 'hourly' | 'weekly' | 'monthly'>('today');

  const timeRangeLabels = {
    '24h': 'Last 24 Hours',
    '7d': 'Last 7 Days',
    '30d': 'Last 30 Days',
    'all': 'All Time',
  };

  // Store Settings States
  const [businessName, setBusinessName] = useState(user?.name || '');
  const [sellerPhone, setSellerPhone] = useState(user?.phone || '');
  const [walletAddress, setWalletAddress] = useState(user?.walletAddress || '');
  const [saving, setSaving] = useState(false);
  const [copied, setCopied] = useState(false);

  useEffect(() => {
    if (user) {
      setBusinessName(user.name);
      setSellerPhone(user.phone || '');
      setWalletAddress(user.walletAddress || '');
    }
  }, [user]);

  const handleCopyWallet = () => {
    navigator.clipboard.writeText(walletAddress || '0x71C2d4B2F5c78a0d2f5a6d34e0c3a5b28a9b2c3d');
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };

  const handleSaveSettings = async (e: React.FormEvent) => {
    e.preventDefault();
    if (saving || !user) return;
    setSaving(true);
    try {
      const res = await apiRequest('api/auth/profile', 'POST', {
        name: businessName,
        contactPhone: sellerPhone,
        walletAddress: walletAddress,
      });
      if (res.success && res.business) {
        updateUser(res.business);
        alert('Store profile updated successfully!');
      } else {
        throw new Error(res.message || 'Failed to update profile');
      }
    } catch (err: any) {
      alert(`Error updating profile: ${err.message}`);
    } finally {
      setSaving(false);
    }
  };

  useEffect(() => {
    async function fetchDashboardData() {
      if (!user || user.subscriptionStatus === 'UNSUBSCRIBED' || user.subscriptionStatus === 'EXPIRED') {
        setLoading(false);
        return;
      }
      try {
        const [ordersData, syncLogsData, sessionsData] = await Promise.all([
          apiRequest('api/orders'),
          apiRequest('api/products/sync-logs'),
          apiRequest('api/whatsapp/sessions'),
        ]);

        setOrders(ordersData);
        setSyncLogs(syncLogsData);
        setSessionsCount(sessionsData.length);
      } catch (err) {
        console.error('Failed to load dashboard data:', err);
      } finally {
        setLoading(false);
      }
    }

    fetchDashboardData();
  }, [user?.id, user?.subscriptionStatus]);

  // Filter Orders By Selected Time Range
  const filterOrdersByTimeRange = (ordersList: Order[], range: '24h' | '7d' | '30d' | 'all') => {
    const now = new Date();
    return ordersList.filter((o) => {
      const orderDate = new Date(o.createdAt);
      const diffMs = now.getTime() - orderDate.getTime();
      if (range === '24h') {
        return diffMs <= 24 * 60 * 60 * 1000;
      } else if (range === '7d') {
        return diffMs <= 7 * 24 * 60 * 60 * 1000;
      } else if (range === '30d') {
        return diffMs <= 30 * 24 * 60 * 60 * 1000;
      }
      return true; // 'all'
    });
  };

  const isOrderPaidAndProcessed = (o: Order) => {
    return o.paymentStatus === 'PAID' && (o.status === 'PROCESSING' || o.status === 'COMPLETED' || o.status === 'DELIVERED');
  };

  const filteredOrders = filterOrdersByTimeRange(orders, timeRange);

  // Calculate Metrics - paid & processed orders only
  const totalSales = filteredOrders
    .filter(isOrderPaidAndProcessed)
    .reduce((sum, o) => sum + o.totalAmount, 0);

  // Real revenue comparison vs yesterday
  const now = new Date();
  const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0);
  const yesterdayStart = new Date(todayStart.getTime() - 24 * 60 * 60 * 1000);

  const todayPaidRevenue = orders
    .filter((o) => isOrderPaidAndProcessed(o) && new Date(o.createdAt) >= todayStart)
    .reduce((sum, o) => sum + o.totalAmount, 0);

  const yesterdayPaidRevenue = orders
    .filter((o) => {
      const d = new Date(o.createdAt);
      return isOrderPaidAndProcessed(o) && d >= yesterdayStart && d < todayStart;
    })
    .reduce((sum, o) => sum + o.totalAmount, 0);

  let revenueTrendText = '0% vs yesterday';
  if (yesterdayPaidRevenue > 0) {
    const diff = ((todayPaidRevenue - yesterdayPaidRevenue) / yesterdayPaidRevenue) * 100;
    revenueTrendText = `${diff >= 0 ? '+' : ''}${diff.toFixed(1)}% vs yesterday`;
  } else if (todayPaidRevenue > 0) {
    revenueTrendText = '+100% vs yesterday';
  }

  const completedOrdersCount = filteredOrders.filter((o) => o.status === 'PROCESSING' || o.status === 'COMPLETED' || o.status === 'DELIVERED').length;

  const syncStatus = syncLogs.length > 0 
    ? (syncLogs[0].status === 'COMPLETED' ? 'Synced' : 'Failed') 
    : 'Not Synced';

  let syncContainerClass = "p-3 bg-slate-50 border border-slate-200/60 rounded-xl flex items-center justify-center shadow-sm text-slate-600 hover:scale-[1.08] hover:shadow transition-all duration-300";
  let syncIconClass = "h-5 w-5 text-slate-600";
  if (syncStatus === 'Synced') {
    syncContainerClass = "p-3 bg-emerald-50 border border-emerald-100/60 rounded-xl flex items-center justify-center shadow-sm text-emerald-600 hover:scale-[1.08] hover:shadow transition-all duration-300";
    syncIconClass = "h-5 w-5 text-emerald-600";
  } else if (syncStatus === 'Failed') {
    syncContainerClass = "p-3 bg-rose-50 border border-rose-100/60 rounded-xl flex items-center justify-center shadow-sm text-rose-600 hover:scale-[1.08] hover:shadow transition-all duration-300";
    syncIconClass = "h-5 w-5 text-rose-600";
  }

  // Calculate dynamic hourly volume data from real orders
  const getHourlyVolumeData = () => {
    const bins = [
      { label: '00:00', count: 0 },
      { label: '02:00', count: 0 },
      { label: '04:00', count: 0 },
      { label: '06:00', count: 0 },
      { label: '08:00', count: 0 },
      { label: '10:00', count: 0 },
      { label: '12:00', count: 0 },
      { label: '14:00', count: 0 },
      { label: '16:00', count: 0 },
      { label: '18:00', count: 0 },
      { label: '20:00', count: 0 },
      { label: '22:00', count: 0 },
    ];

    filteredOrders.forEach(order => {
      try {
        const date = new Date(order.createdAt);
        const hour = date.getHours();
        const binIndex = Math.floor(hour / 2);
        if (binIndex >= 0 && binIndex < bins.length) {
          bins[binIndex].count += 1;
        }
      } catch (err) {
        // ignore
      }
    });

    const maxCount = Math.max(...bins.map(b => b.count), 0);

    return bins.map(b => {
      const heightPercent = maxCount > 0 
        ? `${Math.round((b.count / maxCount) * 80) + 15}%` 
        : '15%';
      return {
        label: b.label,
        count: b.count,
        height: heightPercent
      };
    });
  };

  const hourlyVolumeData = getHourlyVolumeData();
  const maxVolumeIndex = hourlyVolumeData.reduce(
    (maxIdx, bin, idx, arr) => (bin.count > arr[maxIdx].count ? idx : maxIdx),
    0
  );

  const getReportData = (type: 'today' | 'hourly' | 'weekly' | 'monthly') => {
    const now = new Date();
    let totalRevenue = 0;
    let totalOrdersCount = 0;
    let itemsSold = 0;
    let columns: string[] = [];
    let rows: any[] = [];

    if (type === 'today') {
      const todayOrders = orders.filter((o) => {
        const orderDate = new Date(o.createdAt);
        return (
          orderDate.getFullYear() === now.getFullYear() &&
          orderDate.getMonth() === now.getMonth() &&
          orderDate.getDate() === now.getDate()
        );
      });

      totalOrdersCount = todayOrders.length;
      totalRevenue = todayOrders
        .filter(isOrderPaidAndProcessed)
        .reduce((sum, o) => sum + o.totalAmount, 0);

      todayOrders.forEach((o) => {
        if (o.items && isOrderPaidAndProcessed(o)) {
          o.items.forEach((item) => {
            itemsSold += item.quantity;
          });
        }
      });

      columns = ['Order ID', 'Customer', 'Amount', 'Status', 'Payment', 'Created At'];
      rows = todayOrders.map((o) => ({
        'Order ID': o.orderNumber,
        'Customer': o.customerName,
        'Amount': `$${o.totalAmount.toFixed(2)}`,
        'Status': o.status,
        'Payment': o.paymentStatus,
        'Created At': new Date(o.createdAt).toLocaleTimeString(),
      }));
    } else if (type === 'hourly') {
      const todayOrders = orders.filter((o) => {
        const orderDate = new Date(o.createdAt);
        return (
          orderDate.getFullYear() === now.getFullYear() &&
          orderDate.getMonth() === now.getMonth() &&
          orderDate.getDate() === now.getDate()
        );
      });

      totalOrdersCount = todayOrders.length;
      totalRevenue = todayOrders
        .filter(isOrderPaidAndProcessed)
        .reduce((sum, o) => sum + o.totalAmount, 0);

      todayOrders.forEach((o) => {
        if (o.items && isOrderPaidAndProcessed(o)) {
          o.items.forEach((item) => {
            itemsSold += item.quantity;
          });
        }
      });

      const hourBins = Array.from({ length: 12 }, (_, i) => {
        const startHour = i * 2;
        const endHour = startHour + 2;
        const label = `${String(startHour).padStart(2, '0')}:00 - ${String(endHour).padStart(2, '0')}:00`;
        return { label, revenue: 0, count: 0, startHour, endHour };
      });

      todayOrders.forEach((o) => {
        const date = new Date(o.createdAt);
        const hour = date.getHours();
        const binIndex = Math.floor(hour / 2);
        if (binIndex >= 0 && binIndex < hourBins.length) {
          hourBins[binIndex].count += 1;
          if (isOrderPaidAndProcessed(o)) {
            hourBins[binIndex].revenue += o.totalAmount;
          }
        }
      });

      columns = ['Time Interval', 'Revenue', 'Orders Count', 'Avg Order Value'];
      rows = hourBins.map((bin) => ({
        'Time Interval': bin.label,
        'Revenue': `$${bin.revenue.toFixed(2)}`,
        'Orders Count': bin.count,
        'Avg Order Value': bin.count > 0 ? `$${(bin.revenue / bin.count).toFixed(2)}` : '$0.00',
      }));
    } else if (type === 'weekly') {
      const last7Days = Array.from({ length: 7 }, (_, i) => {
        const d = new Date();
        d.setDate(now.getDate() - (6 - i));
        d.setHours(0, 0, 0, 0);
        return d;
      });

      const matchDate = (date1: Date, date2Str: string) => {
        const d2 = new Date(date2Str);
        return (
          date1.getFullYear() === d2.getFullYear() &&
          date1.getMonth() === d2.getMonth() &&
          date1.getDate() === d2.getDate()
        );
      };

      const weeklyOrders = orders.filter((o) => {
        const orderDate = new Date(o.createdAt);
        const diffMs = now.getTime() - orderDate.getTime();
        return diffMs <= 7 * 24 * 60 * 60 * 1000;
      });

      totalOrdersCount = weeklyOrders.length;
      totalRevenue = weeklyOrders
        .filter(isOrderPaidAndProcessed)
        .reduce((sum, o) => sum + o.totalAmount, 0);

      weeklyOrders.forEach((o) => {
        if (o.items && isOrderPaidAndProcessed(o)) {
          o.items.forEach((item) => {
            itemsSold += item.quantity;
          });
        }
      });

      columns = ['Date', 'Revenue', 'Orders Count', 'Avg Order Value'];
      rows = last7Days.map((d) => {
        const dayOrders = weeklyOrders.filter((o) => matchDate(d, o.createdAt));
        const revenue = dayOrders
          .filter(isOrderPaidAndProcessed)
          .reduce((sum, o) => sum + o.totalAmount, 0);
        const count = dayOrders.length;

        return {
          'Date': d.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' }),
          'Revenue': `$${revenue.toFixed(2)}`,
          'Orders Count': count,
          'Avg Order Value': count > 0 ? `$${(revenue / count).toFixed(2)}` : '$0.00',
        };
      });
    } else {
      const last30Days = Array.from({ length: 30 }, (_, i) => {
        const d = new Date();
        d.setDate(now.getDate() - (29 - i));
        d.setHours(0, 0, 0, 0);
        return d;
      });

      const matchDate = (date1: Date, date2Str: string) => {
        const d2 = new Date(date2Str);
        return (
          date1.getFullYear() === d2.getFullYear() &&
          date1.getMonth() === d2.getMonth() &&
          date1.getDate() === d2.getDate()
        );
      };

      const monthlyOrders = orders.filter((o) => {
        const orderDate = new Date(o.createdAt);
        const diffMs = now.getTime() - orderDate.getTime();
        return diffMs <= 30 * 24 * 60 * 60 * 1000;
      });

      totalOrdersCount = monthlyOrders.length;
      totalRevenue = monthlyOrders
        .filter(isOrderPaidAndProcessed)
        .reduce((sum, o) => sum + o.totalAmount, 0);

      monthlyOrders.forEach((o) => {
        if (o.items && isOrderPaidAndProcessed(o)) {
          o.items.forEach((item) => {
            itemsSold += item.quantity;
          });
        }
      });

      columns = ['Date', 'Revenue', 'Orders Count', 'Avg Order Value'];
      rows = last30Days.map((d) => {
        const dayOrders = monthlyOrders.filter((o) => matchDate(d, o.createdAt));
        const revenue = dayOrders
          .filter(isOrderPaidAndProcessed)
          .reduce((sum, o) => sum + o.totalAmount, 0);
        const count = dayOrders.length;

        return {
          'Date': d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }),
          'Revenue': `$${revenue.toFixed(2)}`,
          'Orders Count': count,
          'Avg Order Value': count > 0 ? `$${(revenue / count).toFixed(2)}` : '$0.00',
        };
      });
    }

    const avgOrderValue = totalOrdersCount > 0 ? totalRevenue / totalOrdersCount : 0;

    return {
      totalRevenue,
      totalOrdersCount,
      itemsSold,
      avgOrderValue,
      columns,
      rows,
    };
  };

  const downloadCSVReport = (type: 'today' | 'hourly' | 'weekly' | 'monthly') => {
    const report = getReportData(type);
    const headers = report.columns.join(',');
    const dataRows = report.rows.map((row) => 
      report.columns.map((col) => {
        let val = row[col] ?? '';
        let strVal = String(val);
        // Tab-prefix order numbers or phone numbers to prevent Excel scientific notation (e.g. 2.63789E+11)
        if (col.toLowerCase().includes('id') || col.toLowerCase().includes('phone') || (strVal.length >= 10 && /^\d+$/.test(strVal))) {
          strVal = `\t${strVal}`;
        }
        const escaped = strVal.replace(/"/g, '""');
        return `"${escaped}"`;
      }).join(',')
    );

    const csvContent = [headers, ...dataRows].join('\n');
    const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);

    const link = document.createElement('a');
    link.setAttribute('href', url);
    const filename = `sales_report_${type}_${new Date().toISOString().slice(0, 10)}.csv`;
    link.setAttribute('download', filename);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return (
    <div className="space-y-8">
      {/* Welcome header */}
      <header className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <h2 className="font-headline-lg text-3xl font-bold text-white Outfit">Store Dashboard</h2>
          <p className="text-sm text-gray-400 mt-1">Real-time metrics for your WhatsApp store operations.</p>
        </div>
        <div className="flex items-center gap-3">
          <button
            onClick={() => setIsReportModalOpen(true)}
            className="px-4 py-2 bg-emerald-500 hover:bg-emerald-600 text-white font-semibold rounded-lg flex items-center gap-2 transition-all text-xs cursor-pointer shadow-lg shadow-emerald-500/10 focus:outline-none border-0"
          >
            <Download className="h-3.5 w-3.5" />
            Generate Report
          </button>

          <div className="relative">
            <button
              onClick={() => setDropdownOpen(!dropdownOpen)}
              className="px-4 py-2 bg-[rgba(255,255,255,0.03)] border border-[rgba(255,255,255,0.07)] backdrop-blur-md text-[var(--text-color)] rounded-lg flex items-center gap-2 hover:bg-white/5 transition-all text-xs cursor-pointer focus:outline-none"
            >
              <Calendar className="h-3.5 w-3.5 text-gray-400" />
              {timeRangeLabels[timeRange]}
            </button>
            
            {dropdownOpen && (
              <>
                <div 
                  className="fixed inset-0 z-30" 
                  onClick={() => setDropdownOpen(false)}
                />
                <div className="absolute right-0 mt-2 w-48 rounded-xl bg-slate-900/95 dark:bg-[#12141c]/95 border border-white/10 dark:border-white/5 backdrop-blur-xl shadow-2xl z-40 py-1.5 overflow-hidden">
                  {(Object.keys(timeRangeLabels) as Array<keyof typeof timeRangeLabels>).map((key) => (
                    <button
                      key={key}
                      onClick={() => {
                        setTimeRange(key);
                        setDropdownOpen(false);
                      }}
                      className={`w-full text-left px-4 py-2 text-xs transition-colors border-0 cursor-pointer ${
                        timeRange === key
                          ? 'bg-primary text-[#0f0069] font-bold'
                          : 'text-gray-300 hover:bg-white/5 hover:text-white'
                      }`}
                    >
                      {timeRangeLabels[key]}
                    </button>
                  ))}
                </div>
              </>
            )}
          </div>
        </div>
      </header>

      {loading ? (
        <div className="flex h-64 items-center justify-center">
          <div className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-emerald-500 border-t-transparent"></div>
        </div>
      ) : (
        <>
          {/* Metrics Grid */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            {/* Revenue Card */}
            <div className="glass-panel p-6 rounded-xl space-y-4">
              <div className="flex items-center justify-between text-gray-400">
                <span className="font-mono text-[10px] font-bold tracking-wider">TOTAL REVENUE</span>
                <DollarSign className="h-5 w-5 text-gray-400" />
              </div>
              <div className="text-3xl font-bold text-primary glow-text-primary Outfit">
                ${totalSales.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
              </div>
              <div className="text-xs text-primary font-medium">
                {revenueTrendText}
              </div>
            </div>

            {/* Orders Card */}
            <div className="glass-panel p-6 rounded-xl space-y-4">
              <div className="flex items-center justify-between text-gray-400">
                <span className="font-mono text-[10px] font-bold tracking-wider">COMPLETED ORDERS</span>
                <ShoppingBag className="h-5 w-5 text-gray-400" />
              </div>
              <div className="text-3xl font-bold text-secondary glow-text-secondary Outfit">
                {completedOrdersCount}
              </div>
              <div className="text-xs text-secondary font-medium">
                {orders.length > 0 ? Math.round((completedOrdersCount / orders.length) * 100) : 100}% fulfillment rate
              </div>
            </div>

            {/* WhatsApp Sessions */}
            <div className="glass-panel p-6 rounded-xl space-y-4">
              <div className="flex items-center justify-between text-gray-400">
                <span className="font-mono text-[10px] font-bold tracking-wider">ACTIVE SESSIONS</span>
                <MessageCircle className="h-5 w-5 text-gray-400" />
              </div>
              <div className="text-3xl font-bold text-[var(--text-title)] Outfit">
                {sessionsCount}
              </div>
              <div className="text-xs text-[var(--text-muted)] font-medium">
                Real-time peak activity
              </div>
            </div>

            {/* Sync Status */}
            <div className="glass-panel p-6 rounded-xl space-y-4">
              <div className="flex items-center justify-between text-gray-400">
                <span className="font-mono text-[10px] font-bold tracking-wider">SYNC STATUS</span>
                <RefreshCw className="h-5 w-5 text-gray-400" />
              </div>
              <div className="flex items-center">
                <div className={`px-3 py-1 rounded-lg flex items-center gap-1.5 ${
                  syncStatus === 'Synced'
                    ? 'bg-[rgba(16,185,129,0.1)] border border-[rgba(16,185,129,0.2)] text-primary'
                    : 'bg-[rgba(239,68,68,0.1)] border border-[rgba(239,68,68,0.2)] text-red-400'
                }`}>
                  {syncStatus === 'Synced' ? (
                    <CheckCircle className="h-3.5 w-3.5 text-primary" />
                  ) : (
                    <AlertCircle className="h-3.5 w-3.5 text-red-400" />
                  )}
                  <span className="text-xs font-bold font-sans">
                    {syncStatus === 'Synced' ? 'Healthy' : 'Not Connected'}
                  </span>
                </div>
              </div>
              <div className="text-[10px] text-gray-500 font-medium flex items-center gap-1">
                <Clock className="h-3 w-3 text-gray-550" />
                Last sync: {syncLogs.length > 0 ? formatTimeAgo(syncLogs[0].startedAt) : 'never'}
              </div>
            </div>
          </div>

          {/* Dashboard Charts Section */}
          <OverviewCharts orders={filteredOrders} timeRange={timeRange} />

          {/* Dashboard Main Area */}
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start mt-8">
            
            {/* Left Column: Recent Orders */}
            <div className="lg:col-span-8 glass-panel rounded-xl overflow-hidden flex flex-col">
              <div className="p-4 border-b border-[rgba(255,255,255,0.07)] flex items-center justify-between">
                <h3 className="font-bold text-base text-white font-sans tracking-tight">Recent Orders</h3>
                <Link href="/dashboard/orders" className="text-primary font-mono text-[10px] font-bold tracking-wider hover:underline uppercase">
                  View All
                </Link>
              </div>
              
              {filteredOrders.length === 0 ? (
                <div className="text-center py-12 text-gray-500 text-sm">
                  No orders placed yet. Place an order via WhatsApp.
                </div>
              ) : (
                <div className="overflow-x-auto custom-scrollbar">
                  <table className="w-full text-left border-collapse text-xs">
                    <thead>
                      <tr className="bg-[rgba(255,255,255,0.02)] border-b border-[rgba(255,255,255,0.07)] text-gray-400 font-mono">
                        <th className="px-4 py-3 font-bold text-[10px] tracking-wider uppercase">ORDER ID</th>
                        <th className="px-4 py-3 font-bold text-[10px] tracking-wider uppercase">CUSTOMER</th>
                        <th className="px-4 py-3 font-bold text-[10px] tracking-wider uppercase">AMOUNT</th>
                        <th className="px-4 py-3 font-bold text-[10px] tracking-wider uppercase">STATUS</th>
                        <th className="px-4 py-3 font-bold text-[10px] tracking-wider uppercase">TIME</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-[rgba(255,255,255,0.05)]">
                      {filteredOrders.slice(0, 5).map((order) => (
                        <tr key={order.id} className="hover:bg-[rgba(255,255,255,0.02)] transition-colors group">
                          <td className="px-4 py-3.5 font-mono text-secondary font-semibold">{order.orderNumber}</td>
                          <td className="px-4 py-3.5 flex items-center gap-2">
                            <div className="w-6 h-6 rounded-full bg-white/5 border border-white/10 flex items-center justify-center text-[9px] font-bold text-gray-300 uppercase">
                              {order.customerName.slice(0, 2)}
                            </div>
                            <span className="font-medium text-gray-200">{order.customerName}</span>
                          </td>
                          <td className="px-4 py-3.5 font-bold text-white">${order.totalAmount.toFixed(2)}</td>
                          <td className="px-4 py-3.5">
                            <span className={`px-2 py-0.5 rounded-md text-[10px] font-bold border ${
                              order.paymentStatus === 'PAID'
                                ? 'bg-[rgba(16,185,129,0.1)] text-primary border-[rgba(16,185,129,0.2)]'
                                : order.paymentStatus === 'FAILED'
                                ? 'bg-[rgba(239,68,68,0.1)] text-red-400 border-[rgba(239,68,68,0.2)]'
                                : 'bg-[rgba(245,158,11,0.1)] text-[#f59e0b] border-[rgba(245,158,11,0.2)]'
                            }`}>
                              {order.paymentStatus}
                            </span>
                          </td>
                          <td className="px-4 py-3.5 text-gray-400">{formatTimeAgo(order.createdAt)}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>

            {/* Right Column: Sync Timeline */}
            <div className="lg:col-span-4 space-y-6">

              {/* Performance Chart Miniature */}
              <div className="glass-panel rounded-xl p-6 bg-gradient-to-br from-[rgba(78,222,163,0.04)] to-transparent space-y-4">
                <div className="flex items-center justify-between">
                  <h4 className="font-mono text-[10px] font-bold tracking-wider text-gray-400 uppercase">HOURLY VOLUME</h4>
                  <TrendingUp className="h-4 w-4 text-primary" />
                </div>
                
                <div className="h-24 w-full flex items-end gap-1 px-1">
                  {hourlyVolumeData.map((d, i) => (
                    <div
                      key={i}
                      className="h-full flex-1 flex items-end group/bar relative cursor-pointer"
                    >
                      {/* Full-Height Column Hover Tooltip */}
                      <div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-1.5 hidden group-hover/bar:block bg-slate-900 text-[8px] text-white px-2 py-1 rounded border border-slate-800 dark:bg-[#12141c] dark:border-white/10 whitespace-nowrap z-30 shadow-lg">
                        {d.label}: {d.count} order{d.count === 1 ? '' : 's'}
                      </div>
                      
                      {/* The visual bar */}
                      <div
                        className={`w-full rounded-t-sm transition-all ${
                          i === maxVolumeIndex && d.count > 0
                            ? 'bg-primary shadow-[0_0_10px_rgba(78,222,163,0.4)]' 
                            : 'bg-primary/20 group-hover/bar:bg-primary'
                        }`}
                        style={{ height: d.height }}
                      />
                    </div>
                  ))}
                </div>
                
                <div className="flex justify-between text-[8px] text-gray-550 font-mono">
                  <span>{hourlyVolumeData[2]?.label || '04:00'}</span>
                  <span>{hourlyVolumeData[5]?.label || '10:00'}</span>
                  <span>{hourlyVolumeData[8]?.label || '16:00'}</span>
                  <span>{hourlyVolumeData[11]?.label || '22:00'}</span>
                </div>
              </div>

              {/* Sync Status Timeline */}
              <div className="glass-panel rounded-xl p-6 space-y-4">
                <h3 className="font-bold text-base text-white">Sync Status Timeline</h3>
                
                {syncLogs.length === 0 ? (
                  <div className="text-center py-8 text-gray-500 text-sm">
                    No sync logs recorded yet. Run a manual sync in the Products section.
                  </div>
                ) : (
                  <div className="space-y-4">
                    {syncLogs.slice(0, 4).map((log) => (
                      <div key={log.id} className="flex gap-4 items-start text-xs border-b border-white/5 pb-3 last:border-b-0 last:pb-0">
                        <div className="mt-0.5">
                          {log.status === 'COMPLETED' ? (
                            <CheckCircle className="h-4 w-4 text-primary" />
                          ) : log.status === 'FAILED' ? (
                            <AlertCircle className="h-4 w-4 text-red-400" />
                          ) : (
                            <RefreshCw className="h-4 w-4 text-amber-400 animate-spin" />
                          )}
                        </div>
                        <div className="flex-1">
                          <p className="font-semibold text-gray-200 capitalize">{log.syncType} Sync</p>
                          <p className="text-[10px] text-gray-400 mt-0.5">
                            Processed: {log.recordsProcessed} | Failed: {log.recordsFailed}
                          </p>
                          <span className="text-[9px] text-gray-500 block mt-1 font-mono">
                            {new Date(log.startedAt).toLocaleString()}
                          </span>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>

            </div>
          </div>

          {/* Store Settings Section */}
          <div className="glass-panel rounded-2xl p-6 mt-8 space-y-4">
            <div>
              <h3 className="font-bold text-base text-white font-sans">Store Profile Settings</h3>
              <p className="text-xs text-gray-400 mt-1">
                Edit your business name, store owner's WhatsApp number, and payout wallet credentials.
              </p>
            </div>
            
            <form onSubmit={handleSaveSettings} className="grid grid-cols-1 md:grid-cols-4 gap-6 items-end">
              <div className="space-y-2">
                <label className="text-[10px] font-bold uppercase tracking-wider text-gray-400">Business / Store Name</label>
                <input
                  type="text"
                  value={businessName}
                  onChange={(e) => setBusinessName(e.target.value)}
                  required
                  placeholder="Enter business name"
                  className="w-full glass-input px-4 py-2.5 text-xs outline-none focus:border-primary"
                />
              </div>

              <div className="space-y-2">
                <label className="text-[10px] font-bold uppercase tracking-wider text-gray-400">Seller WhatsApp Number</label>
                <input
                  type="text"
                  value={sellerPhone}
                  onChange={(e) => setSellerPhone(e.target.value)}
                  placeholder="e.g. +2637......"
                  className="w-full glass-input px-4 py-2.5 text-xs outline-none focus:border-primary"
                />
              </div>

              <div className="space-y-2">
                <label className="text-[10px] font-bold uppercase tracking-wider text-gray-400">Payout Wallet Address</label>
                <input
                  type="text"
                  value={walletAddress}
                  onChange={(e) => setWalletAddress(e.target.value)}
                  placeholder="e.g. Paynow / Ecocash"
                  className="w-full glass-input px-4 py-2.5 text-xs outline-none focus:border-primary"
                />
              </div>

              <div>
                <button
                  type="submit"
                  disabled={saving}
                  className="w-full bg-primary hover:brightness-110 text-[#0f0069] font-bold py-2.5 rounded-xl text-xs transition-all cursor-pointer shadow shadow-primary/10 disabled:opacity-50"
                >
                  {saving ? 'Saving Profile...' : 'Update Store Settings'}
                </button>
              </div>
            </form>
          </div>

          {/* SALES REPORT GENERATOR MODAL */}
          {isReportModalOpen && (() => {
            const report = getReportData(reportType);
            return (
              <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
                <div className="glass-panel w-full max-w-4xl rounded-2xl overflow-hidden shadow-2xl animate-fade-in flex flex-col max-h-[90vh]">
                  {/* Header */}
                  <div className="flex items-center justify-between px-4 sm:px-6 py-4 border-b border-white/5 bg-white/2">
                    <div className="flex items-center gap-2">
                      <div className="p-2 bg-emerald-500/10 rounded-lg text-emerald-400">
                        <FileText className="h-5 w-5" />
                      </div>
                      <div>
                        <h3 className="font-bold text-lg text-white Outfit">Sales Report Generator</h3>
                        <p className="text-xs text-gray-400">Analyze and download sales metrics for your business</p>
                      </div>
                    </div>
                    <button
                      onClick={() => setIsReportModalOpen(false)}
                      className="p-1.5 hover:bg-white/5 rounded-lg text-gray-400 hover:text-white transition-all cursor-pointer border-0 bg-transparent"
                    >
                      <X className="h-5 w-5" />
                    </button>
                  </div>

                  {/* Body */}
                  <div className="p-4 sm:p-6 overflow-y-auto space-y-6 flex-1 bg-transparent">
                    {/* Tabs */}
                    <div className="flex border-b border-white/5 gap-6 overflow-x-auto whitespace-nowrap scrollbar-none pb-0.5">
                      {([
                        { key: 'today', label: 'Today\'s Sales' },
                        { key: 'hourly', label: 'Hourly Breakdown' },
                        { key: 'weekly', label: 'Weekly Summary' },
                        { key: 'monthly', label: 'Monthly Summary' },
                      ] as const).map((tab) => (
                        <button
                          key={tab.key}
                          onClick={() => setReportType(tab.key)}
                          className={`pb-3 font-semibold text-xs transition-all relative cursor-pointer border-0 bg-transparent shrink-0 ${
                            reportType === tab.key ? 'text-primary font-bold' : 'text-gray-400 hover:text-white'
                          }`}
                        >
                          {tab.label}
                          {reportType === tab.key && (
                            <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary rounded-full" />
                          )}
                        </button>
                      ))}
                    </div>

                    {/* Summary Metrics Cards */}
                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                      <div className="bg-white/3 border border-white/10 rounded-xl p-4 space-y-1">
                        <span className="text-[9px] font-bold text-gray-400 uppercase tracking-wider">Total Revenue</span>
                        <h4 className="text-lg font-black text-white font-sans tracking-tight">
                          ${report.totalRevenue.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                        </h4>
                      </div>
                      <div className="bg-white/3 border border-white/10 rounded-xl p-4 space-y-1">
                        <span className="text-[9px] font-bold text-gray-400 uppercase tracking-wider">Orders Count</span>
                        <h4 className="text-lg font-black text-white font-sans tracking-tight">
                          {report.totalOrdersCount}
                        </h4>
                      </div>
                      <div className="bg-white/3 border border-white/10 rounded-xl p-4 space-y-1">
                        <span className="text-[9px] font-bold text-gray-400 uppercase tracking-wider">Avg Order Value</span>
                        <h4 className="text-lg font-black text-white font-sans tracking-tight">
                          ${report.avgOrderValue.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                        </h4>
                      </div>
                      <div className="bg-white/3 border border-white/10 rounded-xl p-4 space-y-1">
                        <span className="text-[9px] font-bold text-gray-400 uppercase tracking-wider">Total Items Sold</span>
                        <h4 className="text-lg font-black text-white font-sans tracking-tight">
                          {report.itemsSold}
                        </h4>
                      </div>
                    </div>

                    {/* Table Data Preview */}
                    <div className="space-y-2">
                      <h4 className="text-xs font-bold text-white uppercase tracking-wider">Report Preview</h4>
                      <div className="border border-white/10 rounded-xl overflow-hidden bg-[var(--bg-color)]">
                        <div className="overflow-x-auto max-h-[300px] scrollbar-thin">
                          {report.rows.length === 0 ? (
                            <div className="text-center py-12 text-gray-400 text-xs">
                              No sales data recorded for this time range.
                            </div>
                          ) : (
                            <table className="w-full min-w-[600px] text-left border-collapse text-xs">
                              <thead>
                                <tr className="border-b border-white/10 bg-white/5 text-gray-300 font-semibold font-mono">
                                  {report.columns.map((col) => (
                                    <th key={col} className="px-4 py-3">{col}</th>
                                  ))}
                                </tr>
                              </thead>
                              <tbody className="divide-y divide-white/5 text-gray-300">
                                {report.rows.map((row, idx) => (
                                  <tr key={idx} className="hover:bg-white/2 transition-colors">
                                    {report.columns.map((col) => (
                                      <td key={col} className={`px-4 py-3 ${col === 'Order ID' || col === 'Time Interval' || col === 'Date' ? 'font-mono font-semibold text-primary' : 'text-gray-400'}`}>
                                        {row[col]}
                                      </td>
                                    ))}
                                  </tr>
                                ))}
                              </tbody>
                            </table>
                          )}
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* Footer Actions */}
                  <div className="flex items-center justify-end gap-3 px-4 sm:px-6 py-4 border-t border-white/5 bg-white/2">
                    <button
                      onClick={() => setIsReportModalOpen(false)}
                      className="px-4 py-2 border border-white/10 hover:bg-white/5 text-gray-300 hover:text-white rounded-lg text-xs font-semibold transition-all cursor-pointer bg-transparent"
                    >
                      Close
                    </button>
                    <button
                      onClick={() => downloadCSVReport(reportType)}
                      className="px-4 py-2 bg-emerald-500 hover:bg-emerald-600 text-white rounded-lg text-xs font-semibold flex items-center gap-2 transition-all cursor-pointer border-0 shadow-lg shadow-emerald-500/10"
                    >
                      <Download className="h-3.5 w-3.5" />
                      Download CSV
                    </button>
                  </div>
                </div>
              </div>
            );
          })()}
        </>
      )}
    </div>
  );
}
