"use client";

import { useEffect, Suspense } from "react";
import { useRouter } from "next/navigation";
import Dashboard from "@/components/dashboard/dashboard";
import { Package } from "lucide-react";
import dynamic from "next/dynamic";
import { Skeleton } from "@/components/ui/skeleton";
import { Card, CardContent, CardHeader } from "@/components/ui/card";

// Lazy load the OrderTable component
const OrderTable = dynamic(() => import("@/components/tables/order-table"), {
  loading: () => <OrderTableSkeleton />
});

// Loading skeleton for the order table
function OrderTableSkeleton() {
  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <Skeleton className="h-6 w-32" />
          <div className="flex gap-2">
            <Skeleton className="h-9 w-24" />
            <Skeleton className="h-9 w-32" />
          </div>
        </div>
      </CardHeader>
      <CardContent>
        {/* Table header skeleton */}
        <div className="border rounded-lg">
          <div className="border-b p-4">
            <div className="flex items-center gap-4">
              {['Order ID', 'Customer', 'Status', 'Total', 'Date', 'Actions'].map((header, i) => (
                <Skeleton key={i} className="h-4 w-20 flex-1" />
              ))}
            </div>
          </div>
          
          {/* Table rows skeleton */}
          {[...Array(8)].map((_, i) => (
            <div key={i} className="border-b last:border-b-0 p-4">
              <div className="flex items-center gap-4">
                <Skeleton className="h-4 w-24 flex-1" />
                <Skeleton className="h-4 w-32 flex-1" />
                <Skeleton className="h-6 w-20 flex-1" />
                <Skeleton className="h-4 w-16 flex-1" />
                <Skeleton className="h-4 w-20 flex-1" />
                <div className="flex gap-2 flex-1">
                  <Skeleton className="h-8 w-16" />
                  <Skeleton className="h-8 w-16" />
                </div>
              </div>
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  );
}

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

  useEffect(() => {
    const authToken = document.cookie
      .split("; ")
      .find((row) => row.startsWith("Authorization="))
      ?.split("=")[1];

    if (!authToken) {
      router.push("/login");
    }
  }, [router]);

  return (
    <Dashboard>
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <h1 className="text-2xl font-semibold text-gray-900 dark:text-white flex items-center">
            <Package className="mr-2 h-6 w-6" />
            Orders
          </h1>
        </div>

        <Suspense fallback={<OrderTableSkeleton />}>
          <OrderTable />
        </Suspense>
      </div>
    </Dashboard>
  );
}