import { createFileRoute } from "@tanstack/react-router";
import { useQuery, useQueryClient, useMutation } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { listOrders, updateOrderStatus } from "@/lib/admin.functions";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { formatBDT } from "@/lib/format";
import { useState } from "react";
import { toast } from "sonner";
import { Copy, CheckCircle2, XCircle, Truck } from "lucide-react";

export const Route = createFileRoute("/admin/orders")({
  component: OrdersPage,
});

const statusColor: Record<string, string> = {
  pending: "bg-amber-500/15 text-amber-700",
  verified: "bg-blue-500/15 text-blue-700",
  delivered: "bg-green-500/15 text-green-700",
  rejected: "bg-red-500/15 text-red-700",
};

function OrdersPage() {
  const fn = useServerFn(listOrders);
  const updateFn = useServerFn(updateOrderStatus);
  const qc = useQueryClient();
  const [status, setStatus] = useState("all");
  const [search, setSearch] = useState("");

  const { data, isLoading } = useQuery({
    queryKey: ["admin", "orders", status, search],
    queryFn: () => fn({ data: { status, search } }),
  });

  const mut = useMutation({
    mutationFn: (vars: { id: string; status: any }) => updateFn({ data: vars }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["admin"] });
      toast.success("Order updated");
    },
    onError: (e: any) => toast.error(e.message ?? "Failed"),
  });

  return (
    <div className="space-y-4">
      <Card className="p-4 flex flex-col md:flex-row gap-3">
        <Input placeholder="Search by email..." value={search} onChange={(e) => setSearch(e.target.value)} className="md:max-w-xs" />
        <Select value={status} onValueChange={setStatus}>
          <SelectTrigger className="md:w-48"><SelectValue /></SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All statuses</SelectItem>
            <SelectItem value="pending">Pending</SelectItem>
            <SelectItem value="verified">Verified</SelectItem>
            <SelectItem value="delivered">Delivered</SelectItem>
            <SelectItem value="rejected">Rejected</SelectItem>
          </SelectContent>
        </Select>
      </Card>

      <Card className="p-0 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-muted/50">
              <tr className="text-left">
                <th className="p-3">#</th>
                <th className="p-3">Customer</th>
                <th className="p-3">Package</th>
                <th className="p-3">Payment</th>
                <th className="p-3">Amount</th>
                <th className="p-3">Status</th>
                <th className="p-3">Date</th>
                <th className="p-3 text-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              {isLoading && <tr><td colSpan={8} className="p-6 text-center text-muted-foreground">Loading...</td></tr>}
              {!isLoading && (data?.length ?? 0) === 0 && (
                <tr><td colSpan={8} className="p-6 text-center text-muted-foreground">No orders</td></tr>
              )}
              {data?.map((o: any) => (
                <tr key={o.id} className="border-t hover:bg-muted/30">
                  <td className="p-3 font-mono text-xs">#{String(o.order_number).padStart(4, "0")}</td>
                  <td className="p-3">
                    <div className="flex items-center gap-2">
                      <span>{o.customer_email}</span>
                      <button onClick={() => { navigator.clipboard.writeText(o.customer_email); toast.success("Copied"); }}>
                        <Copy className="w-3 h-3 text-muted-foreground" />
                      </button>
                    </div>
                    {o.whatsapp && <div className="text-xs text-muted-foreground">{o.whatsapp}</div>}
                  </td>
                  <td className="p-3">{o.package_name} × {o.quantity}<div className="text-xs text-muted-foreground">{o.total_credits} credits</div></td>
                  <td className="p-3 uppercase text-xs">{o.payment_method}{o.transaction_id && <div className="font-mono text-[10px] text-muted-foreground">{o.transaction_id}</div>}</td>
                  <td className="p-3 font-medium">{formatBDT(o.total_bdt)}</td>
                  <td className="p-3"><span className={`px-2 py-0.5 rounded text-xs font-medium ${statusColor[o.status] ?? ""}`}>{o.status}</span></td>
                  <td className="p-3 text-xs text-muted-foreground">{new Date(o.created_at).toLocaleString()}</td>
                  <td className="p-3">
                    <div className="flex gap-1 justify-end">
                      {o.status === "pending" && (
                        <Button size="sm" variant="outline" onClick={() => mut.mutate({ id: o.id, status: "verified" })}>
                          <CheckCircle2 className="w-3 h-3" /> Verify
                        </Button>
                      )}
                      {(o.status === "pending" || o.status === "verified") && (
                        <Button size="sm" onClick={() => mut.mutate({ id: o.id, status: "delivered" })}>
                          <Truck className="w-3 h-3" /> Deliver
                        </Button>
                      )}
                      {o.status !== "rejected" && o.status !== "delivered" && (
                        <Button size="sm" variant="ghost" onClick={() => mut.mutate({ id: o.id, status: "rejected" })}>
                          <XCircle className="w-3 h-3 text-red-600" />
                        </Button>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}