"use client";

import { useState, useEffect } from "react";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Eye } from "lucide-react";
import Link from "next/link";
import { fetchWithAuthClient } from "@/lib/client-utils"; // ✅ Import client-safe API helper
import { toast } from "sonner";

// ✅ Define the Order Type
interface Order {
  _id: string;
  date: string;
  totalPrice: number;
  status: string;
}

export default function OrderTable() {
  const [orders, setOrders] = useState<Order[] | null>(null);
  const [loading, setLoading] = useState<boolean>(true);

  useEffect(() => {
    const fetchOrders = async () => {
      try {
        const data: Order[] = await fetchWithAuthClient("/orders");
        setOrders(data);
      } catch (error) {
        toast.error("Failed to fetch orders.");
        console.error("Error fetching orders:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchOrders();
  }, []);

  return (
    <div className="rounded-lg border dark:border-zinc-700 shadow-sm overflow-hidden">
      <Table>
        <TableHeader className="bg-gray-50 dark:bg-zinc-800/50">
          <TableRow>
            <TableHead className="w-[150px]">Order ID</TableHead>
            <TableHead className="text-center">Date</TableHead>
            <TableHead className="text-center">Total</TableHead>
            <TableHead className="text-center">Status</TableHead>
            <TableHead className="text-right">Action</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {loading ? (
            Array.from({ length: 3 }).map((_, index) => (
              <TableRow key={index}>
                <TableCell>Loading...</TableCell>
                <TableCell className="text-center">Loading...</TableCell>
                <TableCell className="text-center">Loading...</TableCell>
                <TableCell className="text-center">Loading...</TableCell>
                <TableCell className="text-right">Loading...</TableCell>
              </TableRow>
            ))
          ) : orders && orders.length > 0 ? (
            orders.map((order) => (
              <TableRow key={order._id} className="transition-colors hover:bg-gray-50 dark:hover:bg-zinc-800/70">
                <TableCell className="font-medium">{order._id.slice(-6)}</TableCell>
                <TableCell className="text-center">{new Date(order.date).toLocaleDateString()}</TableCell>
                <TableCell className="text-center">£{order.totalPrice.toFixed(2)}</TableCell>
                <TableCell className="text-center">{order.status}</TableCell>
                <TableCell className="text-right">
                  <Link href={`/dashboard/orders/${order._id}`}>
                    <Button size="sm" variant="ghost">
                      <Eye className="h-4 w-4" />
                    </Button>
                  </Link>
                </TableCell>
              </TableRow>
            ))
          ) : (
            <TableRow>
              <TableCell colSpan={5} className="h-24 text-center">
                No orders found.
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>
    </div>
  );
}