/**
 * Dashboard Home Page
 * Overview and statistics with real data
 */

'use client';

import { useQuery } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { Card, CardHeader, CardTitle, CardContent, Table, TableHeader, TableBody, TableRow, TableHead, TableCell, Badge, LoadingSpinner } from '@/components/ui';
import { salesAPI } from '@/lib/api/sales';
import { inventoryAPI } from '@/lib/api/inventory';
import { reportsAPI } from '@/lib/api/reports';
import { formatCurrency, formatDateTime } from '@/lib/utils/format';
import { DollarSign, Package, AlertTriangle, ShoppingCart, TrendingUp, ArrowRight } from 'lucide-react';

export default function DashboardPage() {
  const router = useRouter();

  // 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 today's sales report
  const { data: salesReport, isLoading: isLoadingSalesReport } = useQuery({
    queryKey: ['dashboard-sales-report', todayStart, todayEndISO],
    queryFn: async () => {
      const response = await reportsAPI.getSalesReportByDate({
        start_date: todayStart,
        end_date: todayEndISO,
      });
      return response?.data || response;
    },
  });

  // Fetch recent sales
  const { data: recentSalesData, isLoading: isLoadingRecentSales } = useQuery({
    queryKey: ['dashboard-recent-sales'],
    queryFn: async () => {
      const response = await salesAPI.list({ limit: 5, page: 1 });
      // API client returns response.data (which is { success, message, data })
      // Extract the actual data from response.data.data or use response.data if already the data
      return response?.data?.data || response?.data || response;
    },
  });

  // Fetch low stock items
  const { data: lowStockData, isLoading: isLoadingLowStock } = useQuery({
    queryKey: ['dashboard-low-stock'],
    queryFn: async () => {
      const response = await inventoryAPI.list({ low_stock: 'true', limit: 5, page: 1 });
      return response?.data || response;
    },
  });

  // Calculate stats from data
  // Use total_revenue from the sales report (sum of PAID sales)
  const todaySales = salesReport?.summary?.total_revenue || 0;
  const todaySalesCount = salesReport?.summary?.total_sales || 0;
  const todayRevenue = salesReport?.summary?.total_revenue || 0;
  const lowStockCount = lowStockData?.pagination?.total || lowStockData?.inventories?.length || 0;
  
  // Get recent sales list
  // API returns { sales: [...], pagination: {...} } or nested in { success, message, data: { sales, pagination } }
  const recentSales = recentSalesData?.sales || recentSalesData?.data?.sales || [];
  const lowStockItems = lowStockData?.inventories || [];

  const statCards = [
    {
      title: "Today's Sales",
      value: formatCurrency(todaySales),
      description: `${todaySalesCount} transactions`,
      color: 'bg-blue-500',
      icon: DollarSign,
      link: '/sales',
    },
    {
      title: "Today's Revenue",
      value: formatCurrency(todayRevenue),
      description: 'Total revenue today',
      color: 'bg-green-500',
      icon: TrendingUp,
      link: '/reports',
    },
    {
      title: 'Low Stock Items',
      value: lowStockCount,
      description: 'Items below reorder level',
      color: 'bg-yellow-500',
      icon: AlertTriangle,
      link: '/inventory?low_stock=true',
    },
    {
      title: 'Total Products',
      value: '—',
      description: 'Tracked in inventory',
      color: 'bg-purple-500',
      icon: Package,
      link: '/products',
    },
  ];

  const isLoading = isLoadingSalesReport || isLoadingRecentSales || isLoadingLowStock;

  return (
    <div className="min-h-full bg-gray-50 dark:bg-[#0F172A]">
      <div className="p-6 bg-gray-50 dark:bg-gray-950 space-y-6">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-4xl font-bold text-gray-900 dark:text-white mb-2">
            Dashboard
          </h1>
          <p className="text-lg text-gray-600 dark:text-gray-400">
            Welcome back! Here's what's happening with your business today.
          </p>
        </div>

        {/* Stats Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          {statCards.map((card, index) => {
            const Icon = card.icon;
            const colorMap = {
              'bg-blue-500': 'from-[#3B82F6] to-[#2563EB]',
              'bg-green-500': 'from-[#10B981] to-[#059669]',
              'bg-yellow-500': 'from-[#F59E0B] to-[#D97706]',
              'bg-purple-500': 'from-[#8B5CF6] to-[#7C3AED]',
            };
            const gradient = colorMap[card.color] || 'from-gray-500 to-gray-600';
            
            return (
              <Card 
                key={index} 
                hoverable
                className="overflow-hidden group cursor-pointer"
                onClick={() => card.link && router.push(card.link)}
              >
                <CardContent className="p-6 bg-gray-50 dark:bg-gray-950 relative">
                  {/* Gradient accent bar */}
                  <div className={`absolute top-0 left-0 right-0 h-1 bg-gradient-to-r ${gradient}`} />
                  
                  <div className="flex items-start justify-between mt-1">
                    <div className="flex-1">
                      <p className="text-sm font-medium text-gray-600 dark:text-gray-400 mb-2">
                        {card.title}
                      </p>
                      {isLoading ? (
                        <div className="mt-2 h-8 w-32 bg-gray-200 dark:bg-gray-700 animate-pulse rounded-lg" />
                      ) : (
                        <p className="text-3xl font-bold text-gray-900 dark:text-white mb-1">
                          {card.value}
                        </p>
                      )}
                      <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                        {card.description}
                      </p>
                    </div>
                    <div className={`
                      w-14 h-14 rounded-xl 
                      bg-gradient-to-br ${gradient}
                      flex items-center justify-center 
                      text-white shadow-lg
                      group-hover:scale-110 transition-transform duration-200
                    `}>
                      <Icon className="w-7 h-7" />
                    </div>
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>

        {/* Recent Activity Section */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Recent Sales */}
          <Card hoverable className="overflow-hidden">
            <CardHeader className="flex flex-row items-center justify-between bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-[#1E293B] dark:to-[#0F172A]">
              <CardTitle className="flex items-center gap-2 text-gray-900 dark:text-white">
                <div className="w-10 h-10 rounded-lg bg-gradient-to-br from-[#3B82F6] to-[#2563EB] flex items-center justify-center text-white shadow-md">
                  <ShoppingCart className="w-5 h-5" />
                </div>
                Recent Sales
              </CardTitle>
              <button
                onClick={() => router.push('/sales')}
                className="text-sm font-medium text-[#4F46E5] hover:text-[#4338CA] dark:text-[#818CF8] dark:hover:text-[#A78BFA] flex items-center gap-1 transition-colors group"
              >
                View All
                <ArrowRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
              </button>
            </CardHeader>
          <CardContent>
            {isLoadingRecentSales ? (
              <div className="flex justify-center py-12">
                <LoadingSpinner size="lg" />
              </div>
            ) : recentSales.length === 0 ? (
              <div className="text-center py-12 text-gray-500 dark:text-gray-400">
                <ShoppingCart className="w-12 h-12 mx-auto mb-4 opacity-50" />
                <p>No recent sales</p>
                <button
                  onClick={() => router.push('/pos')}
                  className="mt-4 text-blue-600 hover:text-blue-800 dark:text-blue-400"
                >
                  Start a Sale
                </button>
              </div>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Invoice</TableHead>
                    <TableHead>Customer</TableHead>
                    <TableHead>Date</TableHead>
                    <TableHead align="right">Amount</TableHead>
                    <TableHead>Status</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {recentSales.map((sale) => (
                    <TableRow 
                      key={sale.id}
                      onClick={() => router.push(`/sales/${sale.id}`)}
                      className="cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800"
                    >
                      <TableCell className="font-medium">
                        {sale.invoice_no || `SALE-${sale.id}`}
                      </TableCell>
                      <TableCell>
                        {sale.customer?.name || 'Walk-in'}
                      </TableCell>
                      <TableCell className="text-sm text-gray-600 dark:text-gray-400">
                        {formatDateTime(sale.created_at)}
                      </TableCell>
                      <TableCell align="right" className="font-medium">
                        {formatCurrency(sale.total || 0)}
                      </TableCell>
                      <TableCell>
                        <Badge
                          variant={
                            sale.status === 'PAID'
                              ? 'success'
                              : sale.status === 'CANCELLED'
                              ? 'danger'
                              : 'warning'
                          }
                        >
                          {sale.status}
                        </Badge>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            )}
          </CardContent>
        </Card>

          {/* Low Stock Items */}
          <Card hoverable className="overflow-hidden">
            <CardHeader className="flex flex-row items-center justify-between bg-gradient-to-r from-yellow-50 to-amber-50 dark:from-[#1E293B] dark:to-[#0F172A]">
              <CardTitle className="flex items-center gap-2 text-gray-900 dark:text-white">
                <div className="w-10 h-10 rounded-lg bg-gradient-to-br from-[#F59E0B] to-[#D97706] flex items-center justify-center text-white shadow-md">
                  <AlertTriangle className="w-5 h-5" />
                </div>
                Low Stock Alerts
              </CardTitle>
              <button
                onClick={() => router.push('/inventory?low_stock=true')}
                className="text-sm font-medium text-[#4F46E5] hover:text-[#4338CA] dark:text-[#818CF8] dark:hover:text-[#A78BFA] flex items-center gap-1 transition-colors group"
              >
                View All
                <ArrowRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
              </button>
            </CardHeader>
          <CardContent>
            {isLoadingLowStock ? (
              <div className="flex justify-center py-12">
                <LoadingSpinner size="lg" />
              </div>
            ) : lowStockItems.length === 0 ? (
              <div className="text-center py-12 text-gray-500 dark:text-gray-400">
                <Package className="w-12 h-12 mx-auto mb-4 opacity-50" />
                <p>No low stock items</p>
                <p className="text-sm mt-2">All items are well stocked</p>
              </div>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Product</TableHead>
                    <TableHead align="right">Current</TableHead>
                    <TableHead align="right">Reorder Level</TableHead>
                    <TableHead>Action</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {lowStockItems.map((item) => (
                    <TableRow 
                      key={item.id}
                      onClick={() => router.push(`/products/${item.product_id}`)}
                      className="cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800"
                    >
                      <TableCell>
                        <div className="font-medium">
                          {item.product?.name || 'Unknown Product'}
                        </div>
                        {item.variant && (
                          <div className="text-xs text-gray-500">
                            Variant
                          </div>
                        )}
                      </TableCell>
                      <TableCell align="right">
                        <span className={`font-medium ${item.quantity <= 0 ? 'text-red-600' : 'text-yellow-600'}`}>
                          {item.quantity}
                        </span>
                      </TableCell>
                      <TableCell align="right" className="text-gray-600">
                        {item.reorder_level || 'N/A'}
                      </TableCell>
                      <TableCell>
                        <Badge variant="warning">Low Stock</Badge>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            )}
          </CardContent>
        </Card>
      </div>

        {/* Quick Actions */}
        <Card hoverable className="overflow-hidden">
          <CardHeader className="bg-gradient-to-r from-gray-50 to-slate-50 dark:from-[#1E293B] dark:to-[#0F172A]">
            <CardTitle>Quick Actions</CardTitle>
          </CardHeader>
          <CardContent className="p-6 bg-gray-50 dark:bg-gray-950">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              <button
                onClick={() => router.push('/pos')}
                className="group p-6 border-2 border-gray-200 dark:border-gray-700 rounded-xl hover:border-[#4F46E5] dark:hover:border-[#818CF8] hover:bg-gradient-to-br hover:from-blue-50 hover:to-indigo-50 dark:hover:from-[#1E293B] dark:hover:to-[#0F172A] transition-all duration-200 text-left hover:shadow-lg"
              >
                <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-[#3B82F6] to-[#2563EB] flex items-center justify-center text-white mb-4 group-hover:scale-110 transition-transform shadow-md">
                  <ShoppingCart className="w-6 h-6" />
                </div>
                <div className="font-semibold text-gray-900 dark:text-white mb-1">Start New Sale</div>
                <div className="text-sm text-gray-600 dark:text-gray-400">Process a new transaction</div>
              </button>
              <button
                onClick={() => router.push('/products/new')}
                className="group p-6 border-2 border-gray-200 dark:border-gray-700 rounded-xl hover:border-[#10B981] dark:hover:border-[#34D399] hover:bg-gradient-to-br hover:from-green-50 hover:to-emerald-50 dark:hover:from-[#1E293B] dark:hover:to-[#0F172A] transition-all duration-200 text-left hover:shadow-lg"
              >
                <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-[#10B981] to-[#059669] flex items-center justify-center text-white mb-4 group-hover:scale-110 transition-transform shadow-md">
                  <Package className="w-6 h-6" />
                </div>
                <div className="font-semibold text-gray-900 dark:text-white mb-1">Add Product</div>
                <div className="text-sm text-gray-600 dark:text-gray-400">Create a new product</div>
              </button>
              <button
                onClick={() => router.push('/reports')}
                className="group p-6 border-2 border-gray-200 dark:border-gray-700 rounded-xl hover:border-[#8B5CF6] dark:hover:border-[#A78BFA] hover:bg-gradient-to-br hover:from-purple-50 hover:to-violet-50 dark:hover:from-[#1E293B] dark:hover:to-[#0F172A] transition-all duration-200 text-left hover:shadow-lg"
              >
                <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-[#8B5CF6] to-[#7C3AED] flex items-center justify-center text-white mb-4 group-hover:scale-110 transition-transform shadow-md">
                  <TrendingUp className="w-6 h-6" />
                </div>
                <div className="font-semibold text-gray-900 dark:text-white mb-1">View Reports</div>
                <div className="text-sm text-gray-600 dark:text-gray-400">Analyze sales and performance</div>
              </button>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
