/**
 * Reports Page
 * View various business reports with tabbed interface
 */

'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { reportsAPI } from '@/lib/api/reports';
import { Card, CardHeader, CardTitle, CardContent, Button, LoadingSpinner, Input, Table, TableHeader, TableBody, TableRow, TableHead, TableCell, Badge, Tabs, Tab } from '@/components/ui';
import { formatCurrency, formatDate } from '@/lib/utils/format';
import { 
  TrendingUp, 
  Receipt, 
  AlertTriangle,
  ArrowRight,
  BarChart3,
  CreditCard,
  Smartphone,
  DollarSign,
  TrendingDown,
  Users,
  ShoppingBag
} from 'lucide-react';

export default function ReportsPage() {
  const [activeTab, setActiveTab] = useState('financial');
  const [startDate, setStartDate] = useState(() => {
    const date = new Date();
    date.setDate(date.getDate() - 30);
    return date.toISOString().split('T')[0];
  });
  const [endDate, setEndDate] = useState(() => {
    return new Date().toISOString().split('T')[0];
  });
  const [paymentMethod, setPaymentMethod] = useState('ALL');

  // Get today's date range
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const todayStart = today.toISOString();
  const todayEnd = new Date(today);
  todayEnd.setHours(23, 59, 59, 999);
  const todayEndISO = todayEnd.toISOString();

  // Fetch profit & loss report
  const { data: profitLossReport, isLoading: isLoadingPL } = useQuery({
    queryKey: ['profit-loss-report', startDate, endDate],
    queryFn: async () => {
      const startDateISO = startDate ? new Date(startDate).toISOString() : undefined;
      const endDateISO = endDate ? new Date(endDate + 'T23:59:59.999Z').toISOString() : undefined;
      const response = await reportsAPI.getProfitLossReport({
        start_date: startDateISO,
        end_date: endDateISO,
      });
      return response?.data?.data || response?.data || response;
    },
    enabled: activeTab === 'financial',
  });

  // Fetch sales report by date range
  const { data: salesReport, isLoading: isLoadingSales } = useQuery({
    queryKey: ['sales-report', startDate, endDate],
    queryFn: async () => {
      const startDateISO = startDate ? new Date(startDate).toISOString() : undefined;
      const endDateISO = endDate ? new Date(endDate + 'T23:59:59.999Z').toISOString() : undefined;
      const response = await reportsAPI.getSalesReportByDate({
        start_date: startDateISO,
        end_date: endDateISO,
      });
      return response?.data?.data || response?.data || response;
    },
    enabled: activeTab === 'sales',
  });

  // Fetch today's sales report
  const { data: todaySalesReport, isLoading: isLoadingTodaySales } = useQuery({
    queryKey: ['today-sales-report', todayStart, todayEndISO],
    queryFn: async () => {
      const response = await reportsAPI.getSalesReportByDate({
        start_date: todayStart,
        end_date: todayEndISO,
      });
      return response?.data?.data || response?.data || response;
    },
    enabled: activeTab === 'sales',
  });

  // Fetch payment methods report
  const { data: paymentMethodsReport, isLoading: isLoadingPaymentMethods } = useQuery({
    queryKey: ['payment-methods-report', startDate, endDate, paymentMethod],
    queryFn: async () => {
      const startDateISO = startDate ? new Date(startDate).toISOString() : undefined;
      const endDateISO = endDate ? new Date(endDate + 'T23:59:59.999Z').toISOString() : undefined;
      const response = await reportsAPI.getPaymentMethodsReport({
        start_date: startDateISO,
        end_date: endDateISO,
        provider: paymentMethod,
      });
      return response?.data?.data || response?.data || response;
    },
    enabled: activeTab === 'payments',
  });

  // Fetch fast moving products
  const { data: fastMovingProducts, isLoading: isLoadingFastMoving } = useQuery({
    queryKey: ['fast-moving-products', startDate, endDate],
    queryFn: async () => {
      const startDateISO = startDate ? new Date(startDate).toISOString() : undefined;
      const endDateISO = endDate ? new Date(endDate + 'T23:59:59.999Z').toISOString() : undefined;
      const response = await reportsAPI.getFastMovingProducts({
        start_date: startDateISO,
        end_date: endDateISO,
        limit: 20,
      });
      return response?.data?.data || response?.data || response;
    },
    enabled: activeTab === 'inventory',
  });

  // Fetch low stock items
  const { data: lowStockItems, isLoading: isLoadingLowStock } = useQuery({
    queryKey: ['low-stock-items'],
    queryFn: async () => {
      const response = await reportsAPI.getLowStockItems({});
      return response?.data?.data || response?.data || response;
    },
    enabled: activeTab === 'inventory',
  });

  // Fetch slow moving products
  const { data: slowMovingProducts, isLoading: isLoadingSlowMoving } = useQuery({
    queryKey: ['slow-moving-products', startDate, endDate],
    queryFn: async () => {
      const startDateISO = startDate ? new Date(startDate).toISOString() : undefined;
      const endDateISO = endDate ? new Date(endDate + 'T23:59:59.999Z').toISOString() : undefined;
      const response = await reportsAPI.getSlowMovingProducts({
        start_date: startDateISO,
        end_date: endDateISO,
        limit: 20,
      });
      return response?.data?.data || response?.data || response;
    },
    enabled: activeTab === 'inventory',
  });

  // Fetch sales by product
  const { data: salesByProductReport, isLoading: isLoadingSalesByProduct } = useQuery({
    queryKey: ['sales-by-product', startDate, endDate],
    queryFn: async () => {
      const startDateISO = startDate ? new Date(startDate).toISOString() : undefined;
      const endDateISO = endDate ? new Date(endDate + 'T23:59:59.999Z').toISOString() : undefined;
      const response = await reportsAPI.getSalesReportByProduct({
        start_date: startDateISO,
        end_date: endDateISO,
      });
      return response?.data?.data || response?.data || response;
    },
    enabled: activeTab === 'sales',
  });

  // Fetch sales by cashier
  const { data: salesByCashierReport, isLoading: isLoadingSalesByCashier } = useQuery({
    queryKey: ['sales-by-cashier', startDate, endDate],
    queryFn: async () => {
      const startDateISO = startDate ? new Date(startDate).toISOString() : undefined;
      const endDateISO = endDate ? new Date(endDate + 'T23:59:59.999Z').toISOString() : undefined;
      const response = await reportsAPI.getSalesReportByCashier({
        start_date: startDateISO,
        end_date: endDateISO,
      });
      return response?.data?.data || response?.data || response;
    },
    enabled: activeTab === 'sales',
  });

  const handleDateRangeChange = (days) => {
    const date = new Date();
    if (days === 0) {
      setStartDate(date.toISOString().split('T')[0]);
      setEndDate(date.toISOString().split('T')[0]);
    } else {
      date.setDate(date.getDate() - days);
      setStartDate(date.toISOString().split('T')[0]);
      setEndDate(new Date().toISOString().split('T')[0]);
    }
  };

  return (
    <div className="p-6 bg-gray-50 dark:bg-gray-950 space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-3xl font-bold text-gray-900 dark:text-white">Reports</h1>
        <p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
          View business reports and analytics
        </p>
      </div>

      {/* Date Range Filter */}
      <Card>
        <CardHeader>
          <CardTitle>Date Range</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Start Date
              </label>
              <Input
                type="date"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                End Date
              </label>
              <Input
                type="date"
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
              />
            </div>
            <div className="flex gap-2">
              <Button onClick={() => handleDateRangeChange(0)} variant="outline" size="sm">
                Today
              </Button>
              <Button onClick={() => handleDateRangeChange(7)} variant="outline" size="sm">
                Last 7 Days
              </Button>
              <Button onClick={() => handleDateRangeChange(30)} variant="outline" size="sm">
                Last 30 Days
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Tabs */}
      <Card>
        <CardContent className="pt-6">
          <Tabs value={activeTab} onChange={setActiveTab} className="w-full">
            {/* Financial Reports Tab */}
            <Tab id="financial" label="Financial">
              <div className="space-y-6">
                {isLoadingPL ? (
                  <div className="flex justify-center py-12">
                    <LoadingSpinner size="lg" />
                  </div>
                ) : profitLossReport ? (
                  <>
                    {/* Summary Cards */}
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                      <div className="bg-green-50 dark:bg-green-900/20 p-4 rounded-lg">
                        <div className="text-sm text-gray-600 dark:text-gray-400">Total Revenue</div>
                        <div className="text-2xl font-bold text-gray-900 dark:text-white mt-1">
                          {formatCurrency(profitLossReport.revenue?.total_revenue || 0)}
                        </div>
                      </div>
                      <div className="bg-red-50 dark:bg-red-900/20 p-4 rounded-lg">
                        <div className="text-sm text-gray-600 dark:text-gray-400">Total Costs (COGS)</div>
                        <div className="text-2xl font-bold text-gray-900 dark:text-white mt-1">
                          {formatCurrency(profitLossReport.costs?.cost_of_goods_sold || 0)}
                        </div>
                      </div>
                      <div className={`p-4 rounded-lg ${(profitLossReport.profit?.gross_profit || 0) >= 0 ? 'bg-blue-50 dark:bg-blue-900/20' : 'bg-orange-50 dark:bg-orange-900/20'}`}>
                        <div className="text-sm text-gray-600 dark:text-gray-400">Gross Profit</div>
                        <div className="text-2xl font-bold text-gray-900 dark:text-white mt-1">
                          {formatCurrency(profitLossReport.profit?.gross_profit || 0)}
                        </div>
                        <div className="text-xs text-gray-500 mt-1">
                          Margin: {profitLossReport.profit?.gross_profit_margin || 0}%
                        </div>
                      </div>
                    </div>

                    {/* Revenue Breakdown */}
                    <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                      <div className="bg-blue-50 dark:bg-blue-900/20 p-4 rounded-lg">
                        <div className="text-sm text-gray-600 dark:text-gray-400">Net Revenue</div>
                        <div className="text-xl font-bold text-gray-900 dark:text-white mt-1">
                          {formatCurrency(profitLossReport.revenue?.net_revenue || 0)}
                        </div>
                      </div>
                      <div className="bg-purple-50 dark:bg-purple-900/20 p-4 rounded-lg">
                        <div className="text-sm text-gray-600 dark:text-gray-400">Total Discounts</div>
                        <div className="text-xl font-bold text-gray-900 dark:text-white mt-1">
                          {formatCurrency(profitLossReport.revenue?.total_discount || 0)}
                        </div>
                      </div>
                      <div className="bg-red-50 dark:bg-red-900/20 p-4 rounded-lg">
                        <div className="text-sm text-gray-600 dark:text-gray-400">Total Refunds</div>
                        <div className="text-xl font-bold text-gray-900 dark:text-white mt-1">
                          {formatCurrency(profitLossReport.returns?.total_refunds || 0)}
                        </div>
                      </div>
                      <div className="bg-yellow-50 dark:bg-yellow-900/20 p-4 rounded-lg">
                        <div className="text-sm text-gray-600 dark:text-gray-400">Total Returns</div>
                        <div className="text-xl font-bold text-gray-900 dark:text-white mt-1">
                          {profitLossReport.returns?.total_returns || 0}
                        </div>
                      </div>
                    </div>

                    {/* Period Info */}
                    <div className="text-sm text-gray-500 dark:text-gray-400">
                      Period: {profitLossReport.period?.start_date ? formatDate(profitLossReport.period.start_date) : 'All time'} - {profitLossReport.period?.end_date ? formatDate(profitLossReport.period.end_date) : 'Today'}
                    </div>
                  </>
                ) : (
                  <div className="text-center py-12 text-gray-500 dark:text-gray-400">
                    <BarChart3 className="w-12 h-12 mx-auto mb-4 opacity-50" />
                    <p>No financial data found for the selected date range</p>
                  </div>
                )}
              </div>
            </Tab>

            {/* Sales Reports Tab */}
            <Tab id="sales" label="Sales">
              <div className="space-y-6">
                {/* Today's Sales Summary */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <Receipt className="w-5 h-5" />
                      Today's Sales Summary
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    {isLoadingTodaySales ? (
                      <div className="flex justify-center py-8">
                        <LoadingSpinner />
                      </div>
                    ) : todaySalesReport?.summary ? (
                      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                        <div className="bg-blue-50 dark:bg-blue-900/20 p-4 rounded-lg">
                          <div className="text-sm text-gray-600 dark:text-gray-400">Total Sales</div>
                          <div className="text-2xl font-bold text-gray-900 dark:text-white mt-1">
                            {todaySalesReport.summary.total_sales || 0}
                          </div>
                        </div>
                        <div className="bg-green-50 dark:bg-green-900/20 p-4 rounded-lg">
                          <div className="text-sm text-gray-600 dark:text-gray-400">Total Revenue</div>
                          <div className="text-2xl font-bold text-gray-900 dark:text-white mt-1">
                            {formatCurrency(todaySalesReport.summary.total_revenue || 0)}
                          </div>
                        </div>
                        <div className="bg-purple-50 dark:bg-purple-900/20 p-4 rounded-lg">
                          <div className="text-sm text-gray-600 dark:text-gray-400">Total Discount</div>
                          <div className="text-2xl font-bold text-gray-900 dark:text-white mt-1">
                            {formatCurrency(todaySalesReport.summary.total_discount || 0)}
                          </div>
                        </div>
                        <div className="bg-yellow-50 dark:bg-yellow-900/20 p-4 rounded-lg">
                          <div className="text-sm text-gray-600 dark:text-gray-400">Average Sale</div>
                          <div className="text-2xl font-bold text-gray-900 dark:text-white mt-1">
                            {formatCurrency((todaySalesReport.summary.total_revenue || 0) / (todaySalesReport.summary.total_sales || 1))}
                          </div>
                        </div>
                      </div>
                    ) : (
                      <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                        <p>No sales data found for today</p>
                      </div>
                    )}
                  </CardContent>
                </Card>

                {/* Sales by Date Range */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <TrendingUp className="w-5 h-5" />
                      Sales Report ({startDate} to {endDate})
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    {isLoadingSales ? (
                      <div className="flex justify-center py-12">
                        <LoadingSpinner size="lg" />
                      </div>
                    ) : salesReport?.summary ? (
                      <div className="space-y-6">
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                          <div className="bg-blue-50 dark:bg-blue-900/20 p-4 rounded-lg">
                            <div className="text-sm text-gray-600 dark:text-gray-400">Total Sales</div>
                            <div className="text-2xl font-bold text-gray-900 dark:text-white mt-1">
                              {salesReport.summary.total_sales || 0}
                            </div>
                          </div>
                          <div className="bg-green-50 dark:bg-green-900/20 p-4 rounded-lg">
                            <div className="text-sm text-gray-600 dark:text-gray-400">Total Revenue</div>
                            <div className="text-2xl font-bold text-gray-900 dark:text-white mt-1">
                              {formatCurrency(salesReport.summary.total_revenue || 0)}
                            </div>
                          </div>
                          <div className="bg-purple-50 dark:bg-purple-900/20 p-4 rounded-lg">
                            <div className="text-sm text-gray-600 dark:text-gray-400">Total Discount</div>
                            <div className="text-2xl font-bold text-gray-900 dark:text-white mt-1">
                              {formatCurrency(salesReport.summary.total_discount || 0)}
                            </div>
                          </div>
                        </div>

                        {/* Sales List */}
                        {salesReport.sales && salesReport.sales.length > 0 && (
                          <div>
                            <h3 className="font-semibold text-gray-900 dark:text-white mb-4">Recent Sales</h3>
                            <Table>
                              <TableHeader>
                                <TableRow>
                                  <TableHead>Invoice</TableHead>
                                  <TableHead>Date</TableHead>
                                  <TableHead align="right">Items</TableHead>
                                  <TableHead align="right">Total</TableHead>
                                  <TableHead align="right">Discount</TableHead>
                                  <TableHead>Status</TableHead>
                                </TableRow>
                              </TableHeader>
                              <TableBody>
                                {salesReport.sales.slice(0, 20).map((sale) => (
                                  <TableRow key={sale.id}>
                                    <TableCell className="font-mono">{sale.invoice_no}</TableCell>
                                    <TableCell>{formatDate(sale.created_at)}</TableCell>
                                    <TableCell align="right">{sale.items?.length || 0}</TableCell>
                                    <TableCell align="right">{formatCurrency(sale.total || 0)}</TableCell>
                                    <TableCell align="right">{formatCurrency(sale.discount_amount || 0)}</TableCell>
                                    <TableCell>
                                      <Badge variant={sale.status === 'PAID' ? 'success' : sale.status === 'DRAFT' ? 'warning' : 'danger'}>
                                        {sale.status}
                                      </Badge>
                                    </TableCell>
                                  </TableRow>
                                ))}
                              </TableBody>
                            </Table>
                          </div>
                        )}
                      </div>
                    ) : (
                      <div className="text-center py-12 text-gray-500 dark:text-gray-400">
                        <TrendingUp className="w-12 h-12 mx-auto mb-4 opacity-50" />
                        <p>No sales data found for the selected date range</p>
                      </div>
                    )}
                  </CardContent>
                </Card>

                {/* Sales by Product */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <ShoppingBag className="w-5 h-5" />
                      Sales by Product
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    {isLoadingSalesByProduct ? (
                      <div className="flex justify-center py-12">
                        <LoadingSpinner size="lg" />
                      </div>
                    ) : salesByProductReport?.products && salesByProductReport.products.length > 0 ? (
                      <div className="space-y-6">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                          <div className="bg-blue-50 dark:bg-blue-900/20 p-4 rounded-lg">
                            <div className="text-sm text-gray-600 dark:text-gray-400">Total Products</div>
                            <div className="text-2xl font-bold text-gray-900 dark:text-white mt-1">
                              {salesByProductReport.summary?.total_products || salesByProductReport.products.length}
                            </div>
                          </div>
                          <div className="bg-green-50 dark:bg-green-900/20 p-4 rounded-lg">
                            <div className="text-sm text-gray-600 dark:text-gray-400">Total Revenue</div>
                            <div className="text-2xl font-bold text-gray-900 dark:text-white mt-1">
                              {formatCurrency(salesByProductReport.summary?.total_revenue || 0)}
                            </div>
                          </div>
                        </div>

                        <Table>
                          <TableHeader>
                            <TableRow>
                              <TableHead>Product</TableHead>
                              <TableHead>SKU</TableHead>
                              <TableHead align="right">Quantity Sold</TableHead>
                              <TableHead align="right">Revenue</TableHead>
                              <TableHead align="right">Sales Count</TableHead>
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {salesByProductReport.products.map((product) => (
                              <TableRow key={product.product_id}>
                                <TableCell className="font-medium">
                                  {product.product?.name || 'Unknown'}
                                </TableCell>
                                <TableCell>{product.product?.sku || '—'}</TableCell>
                                <TableCell align="right">{product.total_quantity || 0}</TableCell>
                                <TableCell align="right">{formatCurrency(product.total_revenue || 0)}</TableCell>
                                <TableCell align="right">{product.sale_count || 0}</TableCell>
                              </TableRow>
                            ))}
                          </TableBody>
                        </Table>
                      </div>
                    ) : (
                      <div className="text-center py-12 text-gray-500 dark:text-gray-400">
                        <ShoppingBag className="w-12 h-12 mx-auto mb-4 opacity-50" />
                        <p>No product sales data found for the selected date range</p>
                      </div>
                    )}
                  </CardContent>
                </Card>

                {/* Sales by Cashier */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <Users className="w-5 h-5" />
                      Sales by Cashier
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    {isLoadingSalesByCashier ? (
                      <div className="flex justify-center py-12">
                        <LoadingSpinner size="lg" />
                      </div>
                    ) : salesByCashierReport?.cashiers && salesByCashierReport.cashiers.length > 0 ? (
                      <div className="space-y-6">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                          <div className="bg-blue-50 dark:bg-blue-900/20 p-4 rounded-lg">
                            <div className="text-sm text-gray-600 dark:text-gray-400">Total Cashiers</div>
                            <div className="text-2xl font-bold text-gray-900 dark:text-white mt-1">
                              {salesByCashierReport.summary?.total_cashiers || salesByCashierReport.cashiers.length}
                            </div>
                          </div>
                          <div className="bg-green-50 dark:bg-green-900/20 p-4 rounded-lg">
                            <div className="text-sm text-gray-600 dark:text-gray-400">Total Revenue</div>
                            <div className="text-2xl font-bold text-gray-900 dark:text-white mt-1">
                              {formatCurrency(salesByCashierReport.summary?.total_revenue || 0)}
                            </div>
                          </div>
                        </div>

                        <Table>
                          <TableHeader>
                            <TableRow>
                              <TableHead>Cashier</TableHead>
                              <TableHead align="right">Sales Count</TableHead>
                              <TableHead align="right">Revenue</TableHead>
                              <TableHead align="right">Discount</TableHead>
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {salesByCashierReport.cashiers.map((cashier) => (
                              <TableRow key={cashier.user_id}>
                                <TableCell className="font-medium">
                                  {cashier.user?.full_name || cashier.user?.username || `User #${cashier.user_id}` || 'Unknown'}
                                </TableCell>
                                <TableCell align="right">{cashier.sale_count || 0}</TableCell>
                                <TableCell align="right">{formatCurrency(cashier.total_revenue || 0)}</TableCell>
                                <TableCell align="right">{formatCurrency(cashier.total_discount || 0)}</TableCell>
                              </TableRow>
                            ))}
                          </TableBody>
                        </Table>
                      </div>
                    ) : (
                      <div className="text-center py-12 text-gray-500 dark:text-gray-400">
                        <Users className="w-12 h-12 mx-auto mb-4 opacity-50" />
                        <p>No cashier sales data found for the selected date range</p>
                      </div>
                    )}
                  </CardContent>
                </Card>
              </div>
            </Tab>

            {/* Payment Methods Tab */}
            <Tab id="payments" label="Payment Methods">
              <div className="space-y-6">
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <CreditCard className="w-5 h-5" />
                      Payment Methods Report
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    {/* Payment Method Filter */}
                    <div className="mb-4">
                      <div className="flex gap-2">
                        {['ALL', 'CASH', 'CARD', 'MPESA'].map((method) => (
                          <Button
                            key={method}
                            variant={paymentMethod === method ? 'primary' : 'outline'}
                            onClick={() => setPaymentMethod(method)}
                            size="sm"
                          >
                            {method === 'ALL' ? 'All Methods' : method}
                          </Button>
                        ))}
                      </div>
                    </div>

                    {isLoadingPaymentMethods ? (
                      <div className="flex justify-center py-12">
                        <LoadingSpinner size="lg" />
                      </div>
                    ) : paymentMethodsReport ? (
                      <div className="space-y-6">
                        {/* Summary */}
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                          <div className="bg-blue-50 dark:bg-blue-900/20 p-4 rounded-lg">
                            <div className="text-sm text-gray-600 dark:text-gray-400">Total Revenue</div>
                            <div className="text-2xl font-bold text-gray-900 dark:text-white mt-1">
                              {formatCurrency(paymentMethodsReport.summary?.total_revenue || 0)}
                            </div>
                          </div>
                          <div className="bg-green-50 dark:bg-green-900/20 p-4 rounded-lg">
                            <div className="text-sm text-gray-600 dark:text-gray-400">Total Transactions</div>
                            <div className="text-2xl font-bold text-gray-900 dark:text-white mt-1">
                              {paymentMethodsReport.summary?.total_transactions || 0}
                            </div>
                          </div>
                        </div>

                        {/* Payment Methods Breakdown */}
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                          {paymentMethodsReport.payment_methods?.map((method) => {
                            const isCash = method.provider === 'CASH';
                            const isCard = method.provider === 'CARD';
                            const isMpesa = method.provider === 'MPESA';
                            
                            return (
                              <div
                                key={method.provider}
                                className={`p-4 rounded-lg ${
                                  isCash
                                    ? 'bg-green-50 dark:bg-green-900/20'
                                    : isCard
                                    ? 'bg-blue-50 dark:bg-blue-900/20'
                                    : 'bg-purple-50 dark:bg-purple-900/20'
                                }`}
                              >
                                <div className="flex items-center gap-2 mb-2">
                                  {isCash ? (
                                    <DollarSign className="w-5 h-5 text-green-600" />
                                  ) : isCard ? (
                                    <CreditCard className="w-5 h-5 text-blue-600" />
                                  ) : (
                                    <Smartphone className="w-5 h-5 text-purple-600" />
                                  )}
                                  <div className="text-sm font-medium text-gray-700 dark:text-gray-300">
                                    {method.provider === 'MPESA' ? 'Mpesa' : method.provider}
                                  </div>
                                </div>
                                <div className="text-2xl font-bold text-gray-900 dark:text-white mb-1">
                                  {formatCurrency(method.total_amount || 0)}
                                </div>
                                <div className="text-xs text-gray-500 dark:text-gray-400">
                                  {method.transaction_count || 0} transaction{method.transaction_count !== 1 ? 's' : ''}
                                </div>
                                <div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                                  {method.payment_count || 0} payment{method.payment_count !== 1 ? 's' : ''}
                                </div>
                              </div>
                            );
                          })}
                        </div>

                        {/* Details Table */}
                        {paymentMethodsReport.payment_methods && paymentMethodsReport.payment_methods.length > 0 && (
                          <div>
                            <h3 className="font-semibold text-gray-900 dark:text-white mb-4">Payment Details</h3>
                            <Table>
                              <TableHeader>
                                <TableRow>
                                  <TableHead>Payment Method</TableHead>
                                  <TableHead align="right">Transactions</TableHead>
                                  <TableHead align="right">Payments</TableHead>
                                  <TableHead align="right">Total Amount</TableHead>
                                  <TableHead align="right">Percentage</TableHead>
                                </TableRow>
                              </TableHeader>
                              <TableBody>
                                {paymentMethodsReport.payment_methods.map((method) => {
                                  const percentage =
                                    paymentMethodsReport.summary?.total_revenue > 0
                                      ? ((method.total_amount || 0) / paymentMethodsReport.summary.total_revenue) * 100
                                      : 0;
                                  
                                  return (
                                    <TableRow key={method.provider}>
                                      <TableCell className="font-medium">
                                        {method.provider === 'MPESA' ? 'Mpesa' : method.provider}
                                      </TableCell>
                                      <TableCell align="right">{method.transaction_count || 0}</TableCell>
                                      <TableCell align="right">{method.payment_count || 0}</TableCell>
                                      <TableCell align="right">{formatCurrency(method.total_amount || 0)}</TableCell>
                                      <TableCell align="right">{percentage.toFixed(1)}%</TableCell>
                                    </TableRow>
                                  );
                                })}
                              </TableBody>
                            </Table>
                          </div>
                        )}
                      </div>
                    ) : (
                      <div className="text-center py-12 text-gray-500 dark:text-gray-400">
                        <CreditCard className="w-12 h-12 mx-auto mb-4 opacity-50" />
                        <p>No payment data found for the selected date range</p>
                      </div>
                    )}
                  </CardContent>
                </Card>
              </div>
            </Tab>

            {/* Inventory Reports Tab */}
            <Tab id="inventory" label="Inventory">
              <div className="space-y-6">
                {/* Fast Moving Products */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <ArrowRight className="w-5 h-5" />
                      Fast Moving Products
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    {isLoadingFastMoving ? (
                      <div className="flex justify-center py-12">
                        <LoadingSpinner size="lg" />
                      </div>
                    ) : fastMovingProducts && fastMovingProducts.length > 0 ? (
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>Product</TableHead>
                            <TableHead>SKU</TableHead>
                            <TableHead align="right">Quantity Sold</TableHead>
                            <TableHead align="right">Revenue</TableHead>
                            <TableHead align="right">Sales Count</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {fastMovingProducts.map((product, index) => (
                            <TableRow key={product.product_id || index}>
                              <TableCell className="font-medium">
                                {product.product_name || product.product?.name || 'Unknown'}
                              </TableCell>
                              <TableCell>{product.product_sku || product.product?.sku || '—'}</TableCell>
                              <TableCell align="right">{product.total_quantity || product.quantity || 0}</TableCell>
                              <TableCell align="right">{formatCurrency(product.total_revenue || 0)}</TableCell>
                              <TableCell align="right">{product.sale_count || 0}</TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    ) : (
                      <div className="text-center py-12 text-gray-500 dark:text-gray-400">
                        <ArrowRight className="w-12 h-12 mx-auto mb-4 opacity-50" />
                        <p>No fast moving products found for the selected date range</p>
                      </div>
                    )}
                  </CardContent>
                </Card>

                {/* Slow Moving Products */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <TrendingDown className="w-5 h-5" />
                      Slow Moving Products
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    {isLoadingSlowMoving ? (
                      <div className="flex justify-center py-12">
                        <LoadingSpinner size="lg" />
                      </div>
                    ) : slowMovingProducts && slowMovingProducts.length > 0 ? (
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>Product</TableHead>
                            <TableHead>SKU</TableHead>
                            <TableHead align="right">Quantity Sold</TableHead>
                            <TableHead align="right">Revenue</TableHead>
                            <TableHead align="right">Sales Count</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {slowMovingProducts.map((product, index) => (
                            <TableRow key={product.product_id || index}>
                              <TableCell className="font-medium">
                                {product.product_name || product.product?.name || 'Unknown'}
                              </TableCell>
                              <TableCell>{product.product_sku || product.product?.sku || '—'}</TableCell>
                              <TableCell align="right">{product.total_quantity || product.quantity || 0}</TableCell>
                              <TableCell align="right">{formatCurrency(product.total_revenue || 0)}</TableCell>
                              <TableCell align="right">{product.sale_count || 0}</TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    ) : (
                      <div className="text-center py-12 text-gray-500 dark:text-gray-400">
                        <TrendingDown className="w-12 h-12 mx-auto mb-4 opacity-50" />
                        <p>No slow moving products found for the selected date range</p>
                      </div>
                    )}
                  </CardContent>
                </Card>

                {/* Low Stock Items */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <AlertTriangle className="w-5 h-5" />
                      Low Stock Items
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    {isLoadingLowStock ? (
                      <div className="flex justify-center py-12">
                        <LoadingSpinner size="lg" />
                      </div>
                    ) : lowStockItems && lowStockItems.length > 0 ? (
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>Product</TableHead>
                            <TableHead>SKU</TableHead>
                            <TableHead align="right">Current Stock</TableHead>
                            <TableHead align="right">Reorder Level</TableHead>
                            <TableHead>Status</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {lowStockItems.map((item) => (
                            <TableRow key={item.product_id || item.inventory_id}>
                              <TableCell className="font-medium">
                                {item.product_name || item.product?.name || 'Unknown'}
                              </TableCell>
                              <TableCell>{item.product_sku || item.product?.sku || '—'}</TableCell>
                              <TableCell align="right">{item.quantity || item.current_quantity || 0}</TableCell>
                              <TableCell align="right">{item.reorder_level || 0}</TableCell>
                              <TableCell>
                                <Badge variant={parseFloat(item.quantity || item.current_quantity || 0) <= 0 ? 'danger' : 'warning'}>
                                  {parseFloat(item.quantity || item.current_quantity || 0) <= 0 ? 'Out of Stock' : 'Low Stock'}
                                </Badge>
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    ) : (
                      <div className="text-center py-12 text-gray-500 dark:text-gray-400">
                        <AlertTriangle className="w-12 h-12 mx-auto mb-4 opacity-50" />
                        <p>No low stock items found</p>
                      </div>
                    )}
                  </CardContent>
                </Card>
              </div>
            </Tab>
          </Tabs>
        </CardContent>
      </Card>
    </div>
  );
}
