"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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Eye,
  Loader,
  CheckCircle,
  XCircle,
  ChevronLeft,
  ChevronRight,
  ArrowUpDown,
  Truck,
} from "lucide-react";
import Link from "next/link";
import { fetchWithAuthClient } from "@/lib/client-utils";
import { toast } from "sonner";
import { Checkbox } from "@/components/ui/checkbox";

interface Order {
  _id: string;
  orderId: number;
  status: string;
  totalPrice: number;
  escrowExpiresAt: string;
  telegramUsername: string;
  createdAt: string;
}

export default function OrderTable() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [filteredOrders, setFilteredOrders] = useState<Order[]>([]);
  const [selectedOrders, setSelectedOrders] = useState<Set<string>>(new Set());
  const [loading, setLoading] = useState<boolean>(true);
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [totalPages, setTotalPages] = useState<number>(1);
  const [sortColumn, setSortColumn] = useState<string>("createdAt");
  const [sortDirection, setSortDirection] = useState<"asc" | "desc">("desc");
  const ITEMS_PER_PAGE = 10;

  // Fetch Orders
  useEffect(() => {
    const fetchOrders = async () => {
      try {
        setLoading(true);
        const response = await fetchWithAuthClient("/orders");

        if (response.orders) {
          setOrders(response.orders);
          setFilteredOrders(response.orders);
          setTotalPages(Math.ceil(response.orders.length / ITEMS_PER_PAGE));
        } else {
          throw new Error("Invalid API response format");
        }
      } catch (error) {
        toast.error("Failed to fetch orders.");
        console.error("Error fetching orders:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchOrders();
  }, []);

  // Filter Orders by Status
  useEffect(() => {
    const filtered = orders.filter(
      (order) => statusFilter === "all" || order.status === statusFilter
    );
    setFilteredOrders(filtered);
    setTotalPages(Math.ceil(filtered.length / ITEMS_PER_PAGE));
    setCurrentPage(1); // Reset to the first page on filter change
  }, [statusFilter, orders]);

  // Sort Orders
  const sortedOrders = filteredOrders.sort((a, b) => {
    const aValue = a[sortColumn as keyof Order];
    const bValue = b[sortColumn as keyof Order];

    if (typeof aValue === "number" || typeof aValue === "string") {
      if (aValue < bValue) return sortDirection === "asc" ? -1 : 1;
      if (aValue > bValue) return sortDirection === "asc" ? 1 : -1;
    }

    return 0;
  });

  // Paginated Orders
  const paginatedOrders = sortedOrders.slice(
    (currentPage - 1) * ITEMS_PER_PAGE,
    currentPage * ITEMS_PER_PAGE
  );

  // Handle Sorting
  const handleSort = (column: string) => {
    if (column === sortColumn) {
      setSortDirection(sortDirection === "asc" ? "desc" : "asc");
    } else {
      setSortColumn(column);
      setSortDirection("asc");
    }
  };

  const toggleOrderSelection = (orderId: string) => {
    setSelectedOrders((prev) => {
      const updated = new Set(prev);
      if (updated.has(orderId)) {
        updated.delete(orderId);
      } else {
        updated.add(orderId);
      }
      return updated;
    });
  };

  // Handle Bulk Actions
  const markAsShipped = async () => {
    try {
      if (selectedOrders.size === 0) {
        toast.warning("No orders selected.");
        return;
      }

      const orderIds = Array.from(selectedOrders);
      const response = await fetchWithAuthClient(
        "/orders/mark-shipped",
        "POST",
        { orderIds }
      );

      if (response.success) {
        setOrders((prevOrders) =>
          prevOrders.map((order) =>
            selectedOrders.has(order._id)
              ? { ...order, status: "shipped" }
              : order
          )
        );
        setSelectedOrders(new Set());
        toast.success("Orders marked as shipped successfully.");
      } else {
        throw new Error("Failed to update orders");
      }
    } catch (error) {
      toast.error("Failed to update orders.");
      console.error("Error marking orders as shipped:", error);
    }
  };

  return (
    <div className="rounded-lg border dark:border-zinc-700 shadow-sm overflow-hidden">
      {/* Filter and Bulk Action */}
      <div className="p-4 flex justify-between items-center border-b dark:border-zinc-700">
        <Select value={statusFilter} onValueChange={setStatusFilter}>
          <SelectTrigger className="w-40">
            <SelectValue placeholder="Filter Status" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All</SelectItem>
            <SelectItem value="paid">Paid</SelectItem>
            <SelectItem value="unpaid">Unpaid</SelectItem>
            <SelectItem value="shipped">Shipped</SelectItem>
            <SelectItem value="completed">Completed</SelectItem>
          </SelectContent>
        </Select>
        <Button onClick={markAsShipped} disabled={selectedOrders.size === 0}>
          <Truck className="mr-2 h-5 w-5" />
          Mark as Shipped
        </Button>
      </div>

      {/* Orders Table */}
      <Table>
        <TableHeader className="bg-gray-50 dark:bg-zinc-800/50">
          <TableRow>
            <TableHead className="w-[50px] text-center">
              <Checkbox
                checked={
                  selectedOrders.size === paginatedOrders.length &&
                  paginatedOrders.length > 0
                }
                onCheckedChange={(checked) =>
                  setSelectedOrders(
                    checked
                      ? new Set(paginatedOrders.map((o) => o._id))
                      : new Set()
                  )
                }
              />
            </TableHead>
            <TableHead
              className="text-center cursor-pointer"
              onClick={() => handleSort("orderId")}
            >
              Order ID <ArrowUpDown className="ml-2 h-4 w-4 inline" />
            </TableHead>
            <TableHead
              className="text-center cursor-pointer"
              onClick={() => handleSort("totalPrice")}
            >
              Total (£) <ArrowUpDown className="ml-2 h-4 w-4 inline" />
            </TableHead>
            <TableHead
              className="text-center cursor-pointer"
              onClick={() => handleSort("status")}
            >
              Status <ArrowUpDown className="ml-2 h-4 w-4 inline" />
            </TableHead>
            <TableHead
              className="text-center cursor-pointer"
              onClick={() => handleSort("createdAt")}
            >
              Date <ArrowUpDown className="ml-2 h-4 w-4 inline" />
            </TableHead>
            <TableHead className="text-center">Buyer</TableHead>
            <TableHead className="text-right">Action</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {loading ? (
            <TableRow>
              <TableCell colSpan={7} className="text-center py-4">
                <Loader className="h-5 w-5 animate-spin" />
              </TableCell>
            </TableRow>
          ) : paginatedOrders.length ? (
            paginatedOrders.map((order) => (
              <TableRow key={order._id}>
                <TableCell className="text-center">
                  <Checkbox
                    checked={selectedOrders.has(order._id)}
                    onCheckedChange={() => toggleOrderSelection(order._id)}
                  />
                </TableCell>
                <TableCell className="text-center">#{order.orderId}</TableCell>
                <TableCell className="text-center">
                  £{order.totalPrice.toFixed(2)}
                </TableCell>
                <TableCell className="text-center">
                  {order.status === "paid" && (
                    <span className="flex items-center justify-center text-green-500">
                      <CheckCircle className="h-4 w-4 mr-1" /> Paid
                    </span>
                  )}
                  {order.status === "unpaid" && (
                    <span className="flex items-center justify-center text-red-500">
                      <XCircle className="h-4 w-4 mr-1" /> Unpaid
                    </span>
                  )}
                  {order.status === "confirming" && (
                    <span className="flex items-center justify-center text-yellow-500">
                      <Loader className="h-4 w-4 mr-1 animate-spin" />{" "}
                      Confirming
                    </span>
                  )}
                  {order.status === "shipped" && (
                    <span className="flex items-center justify-center text-blue-500">
                      <Truck className="h-4 w-4 mr-1" /> Shipped
                    </span>
                  )}
                  {order.status === "completed" && (
                    <span className="flex items-center justify-center text-gray-500">
                      <CheckCircle className="h-4 w-4 mr-1" /> Completed
                    </span>
                  )}
                  {order.status === "disputed" && (
                    <span className="flex items-center justify-center text-orange-500">
                      <XCircle className="h-4 w-4 mr-1" /> Disputed
                    </span>
                  )}
                  {order.status === "cancelled" && (
                    <span className="flex items-center justify-center text-gray-400">
                      <XCircle className="h-4 w-4 mr-1" /> Cancelled
                    </span>
                  )}
                </TableCell>
                <TableCell className="text-center">
                  {new Date(order.createdAt).toLocaleDateString()}
                </TableCell>
                <TableCell className="text-center">
                  @{order.telegramUsername}
                </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={7} className="text-center py-4">
                No orders found.
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>

      {/* Pagination */}
      <div className="p-4 flex justify-between items-center border-t dark:border-zinc-700">
        <Button
          variant="outline"
          size="sm"
          disabled={currentPage === 1}
          onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}
        >
          <ChevronLeft className="h-4 w-4" /> Previous
        </Button>
        <span className="text-sm">
          Page {currentPage} of {totalPages}
        </span>
        <Button
          variant="outline"
          size="sm"
          disabled={currentPage === totalPages}
          onClick={() => setCurrentPage((prev) => prev + 1)}
        >
          Next <ChevronRight className="h-4 w-4" />
        </Button>
      </div>
    </div>
  );
}
