"use client";

import { useState, useEffect, useCallback } 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,
  Loader2,
  CheckCircle2,
  XCircle,
  ChevronLeft,
  ChevronRight,
  ArrowUpDown,
  Truck,
} from "lucide-react";
import Link from "next/link";
import { fetchClient } from "@/lib/client-utils";
import { toast } from "sonner";
import { Checkbox } from "@/components/ui/checkbox";

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

type SortableColumns = "orderId" | "totalPrice" | "status" | "createdAt";

export default function OrderTable() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [statusFilter, setStatusFilter] = useState("all");
  const [currentPage, setCurrentPage] = useState(1);
  const [sortConfig, setSortConfig] = useState<{
    column: SortableColumns;
    direction: "asc" | "desc";
  }>({ column: "createdAt", direction: "desc" });
  const [selectedOrders, setSelectedOrders] = useState<Set<string>>(new Set());
  const ITEMS_PER_PAGE = 10;

  // Fetch orders with error handling
  const fetchOrders = useCallback(async () => {
    try {
      setLoading(true);
      const data = await fetchClient<{ orders: Order[] }>("/orders");
      setOrders(data.orders || []);
    } catch (error) {
      toast.error("Failed to fetch orders");
      console.error("Fetch error:", error);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchOrders();
  }, [fetchOrders]);

  // Derived data calculations
  const filteredOrders = orders.filter(
    (order) => statusFilter === "all" || order.status === statusFilter
  );

  const sortedOrders = [...filteredOrders].sort((a, b) => {
    const aValue = a[sortConfig.column];
    const bValue = b[sortConfig.column];

    if (typeof aValue === "string" && typeof bValue === "string") {
      return sortConfig.direction === "asc"
        ? aValue.localeCompare(bValue)
        : bValue.localeCompare(aValue);
    }

    if (typeof aValue === "number" && typeof bValue === "number") {
      return sortConfig.direction === "asc" ? aValue - bValue : bValue - aValue;
    }

    return 0;
  });

  const totalPages = Math.ceil(sortedOrders.length / ITEMS_PER_PAGE);
  const paginatedOrders = sortedOrders.slice(
    (currentPage - 1) * ITEMS_PER_PAGE,
    currentPage * ITEMS_PER_PAGE
  );

  // Handlers
  const handleSort = (column: SortableColumns) => {
    setSortConfig(prev => ({
      column,
      direction: prev.column === column && prev.direction === "asc" ? "desc" : "asc"
    }));
  };

  const toggleSelection = (orderId: string) => {
    setSelectedOrders(prev => {
      const newSet = new Set(prev);
      newSet.has(orderId) ? newSet.delete(orderId) : newSet.add(orderId);
      return newSet;
    });
  };

  const toggleAll = () => {
    if (selectedOrders.size === paginatedOrders.length) {
      setSelectedOrders(new Set());
    } else {
      setSelectedOrders(new Set(paginatedOrders.map(o => o._id)));
    }
  };

  const markAsShipped = async () => {
    if (selectedOrders.size === 0) {
      toast.warning("Please select orders to mark as shipped");
      return;
    }

    try {
      await fetchClient("/orders/mark-shipped", {
        method: "POST",
        body: JSON.stringify({ orderIds: Array.from(selectedOrders) })
      });

      setOrders(prev =>
        prev.map(order =>
          selectedOrders.has(order._id)
            ? { ...order, status: "shipped" }
            : order
        )
      );
      setSelectedOrders(new Set());
      toast.success("Selected orders marked as shipped");
    } catch (error) {
      toast.error("Failed to update orders");
      console.error("Shipping error:", error);
    }
  };

  // Status display configuration
  const statusConfig = {
    paid: { icon: CheckCircle2, color: "text-green-500" },
    unpaid: { icon: XCircle, color: "text-red-500" },
    confirming: { icon: Loader2, color: "text-yellow-500 -" },
    shipped: { icon: Truck, color: "text-blue-500" },
    completed: { icon: CheckCircle2, color: "text-gray-500" },
    disputed: { icon: XCircle, color: "text-orange-500" },
    cancelled: { icon: XCircle, color: "text-gray-400" }
  };

  return (
    <div className="rounded-lg border shadow-sm overflow-hidden">
      {/* Toolbar */}
      <div className="p-4 flex justify-between items-center border-b">
        <Select value={statusFilter} onValueChange={setStatusFilter}>
          <SelectTrigger className="w-40">
            <SelectValue placeholder="Filter Status" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Statuses</SelectItem>
            {Object.keys(statusConfig).map(status => (
              <SelectItem key={status} value={status}>
                {status.charAt(0).toUpperCase() + status.slice(1)}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        <Button onClick={markAsShipped} disabled={selectedOrders.size === 0}>
          <Truck className="mr-2 h-5 w-5" />
          Mark Shipped ({selectedOrders.size})
        </Button>
      </div>

      {/* Table */}
      <Table>
        <TableHeader className="bg-muted">
          <TableRow>
            <TableHead className="w-12">
              <Checkbox
                checked={selectedOrders.size > 0 && selectedOrders.size === paginatedOrders.length}
                onCheckedChange={toggleAll}
              />
            </TableHead>
            <TableHead className="cursor-pointer" onClick={() => handleSort("orderId")}>
              Order ID <ArrowUpDown className="ml-2 inline h-4 w-4" />
            </TableHead>
            <TableHead className="cursor-pointer" onClick={() => handleSort("totalPrice")}>
              Total <ArrowUpDown className="ml-2 inline h-4 w-4" />
            </TableHead>
            <TableHead className="cursor-pointer" onClick={() => handleSort("status")}>
              Status <ArrowUpDown className="ml-2 inline h-4 w-4" />
            </TableHead>
            <TableHead className="cursor-pointer" onClick={() => handleSort("createdAt")}>
              Date <ArrowUpDown className="ml-2 inline h-4 w-4" />
            </TableHead>
            <TableHead>Buyer</TableHead>
            <TableHead className="text-right">Actions</TableHead>
          </TableRow>
        </TableHeader>

        <TableBody>
          {loading ? (
            <TableRow>
              <TableCell colSpan={7} className="text-center h-24">
                <Loader2 className="h-8 w-8 animate-spin mx-auto" />
              </TableCell>
            </TableRow>
          ) : paginatedOrders.length === 0 ? (
            <TableRow>
              <TableCell colSpan={7} className="text-center h-24">
                No orders found
              </TableCell>
            </TableRow>
          ) : (
            paginatedOrders.map(order => {
              const StatusIcon = statusConfig[order.status as keyof typeof statusConfig]?.icon || XCircle;
              const statusColor = statusConfig[order.status as keyof typeof statusConfig]?.color || "text-red-500";

              return (
                <TableRow key={order._id}>
                  <TableCell>
                    <Checkbox
                      checked={selectedOrders.has(order._id)}
                      onCheckedChange={() => toggleSelection(order._id)}
                    />
                  </TableCell>
                  <TableCell>#{order.orderId}</TableCell>
                  <TableCell>£{order.totalPrice.toFixed(2)}</TableCell>
                  <TableCell>
                    <div className={`flex items-center ${statusColor}`}>
                      <StatusIcon className="h-4 w-4 mr-2" />
                      {order.status.charAt(0).toUpperCase() + order.status.slice(1)}
                    </div>
                  </TableCell>
                  <TableCell>
                    {new Date(order.createdAt).toLocaleDateString("en-GB")}
                  </TableCell>
                  <TableCell>
                    {order.telegramUsername ? `@${order.telegramUsername}` : "-"}
                  </TableCell>
                  <TableCell className="text-right">
                    <Button variant="ghost" size="sm" asChild>
                      <Link href={`/dashboard/orders/${order._id}`}>
                        <Eye className="h-4 w-4" />
                      </Link>
                    </Button>
                  </TableCell>
                </TableRow>
              );
            })
          )}
        </TableBody>
      </Table>

      {/* Pagination */}
      <div className="p-4 flex justify-between items-center border-t">
        <div className="flex-1 text-sm text-muted-foreground">
          {selectedOrders.size} of {sortedOrders.length} row(s) selected
        </div>

        <div className="flex items-center gap-4">
          <Button
            variant="outline"
            size="sm"
            disabled={currentPage === 1}
            onClick={() => setCurrentPage(p => Math.max(p - 1, 1))}
          >
            <ChevronLeft className="h-4 w-4 mr-2" /> Previous
          </Button>
          <span className="text-sm font-medium">
            Page {currentPage} of {totalPages}
          </span>
          <Button
            variant="outline"
            size="sm"
            disabled={currentPage >= totalPages}
            onClick={() => setCurrentPage(p => p + 1)}
          >
            Next <ChevronRight className="h-4 w-4 ml-2" />
          </Button>
        </div>
      </div>
    </div>
  );
}