import Link from "next/link";
import { redirect } from "next/navigation";
import { prisma } from "@/lib/db";
import { requireAccount } from "@/lib/auth";
import { Card, CardBody, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Trash2 } from "lucide-react";
import { deleteOrder } from "./actions";

export const metadata = {
  title: "Orders | WhatsApp CRM",
};

export default async function OrdersPage() {
  const session = await requireAccount();

  const orders = await prisma.order.findMany({
    where: { accountId: session.accountId },
    include: {
      contact: true,
    },
    orderBy: {
      createdAt: 'desc',
    }
  });

  return (
    <div className="flex h-full flex-col">
      <div className="flex h-14 items-center justify-between border-b border-border bg-card px-6">
        <h1 className="text-lg font-semibold text-foreground">Orders</h1>
      </div>

      <div className="flex-1 overflow-auto p-6 bg-background">
        <div className="mx-auto max-w-6xl space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Recent Orders</CardTitle>
              <p className="text-sm text-muted-foreground mt-1">Orders placed by your customers via WhatsApp</p>
            </CardHeader>
            <CardBody>
              {orders.length === 0 ? (
                <div className="flex flex-col items-center justify-center rounded-lg border border-dashed p-12 text-center">
                  <div className="text-lg font-medium text-foreground">No orders yet</div>
                  <p className="mt-1 text-sm text-muted-foreground">
                    When customers send orders from your WhatsApp catalog, they will appear here.
                  </p>
                </div>
              ) : (
                <div className="rounded-md border border-border overflow-hidden">
                  <table className="w-full text-sm text-left">
                    <thead className="bg-muted text-muted-foreground border-b border-border">
                      <tr>
                        <th className="px-4 py-3 font-medium">Order ID</th>
                        <th className="px-4 py-3 font-medium">Customer</th>
                        <th className="px-4 py-3 font-medium">Total</th>
                        <th className="px-4 py-3 font-medium">Status</th>
                        <th className="px-4 py-3 font-medium">Date</th>
                        <th className="px-4 py-3 font-medium text-right">Actions</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border bg-card">
                      {orders.map((order) => (
                        <tr key={order.id} className="hover:bg-muted/50 transition-colors">
                          <td className="px-4 py-3 font-mono text-xs text-indigo-600 hover:underline">
                            <Link href={`/orders/${order.id}`}>
                              {order.id.slice(-8)}
                            </Link>
                          </td>
                          <td className="px-4 py-3">
                            <div className="font-medium text-foreground">{order.contact.name}</div>
                            <div className="text-xs text-muted-foreground">{order.contact.phone}</div>
                          </td>
                          <td className="px-4 py-3 font-medium">
                            {Number(order.totalAmount).toLocaleString(undefined, { style: 'currency', currency: order.currency })}
                          </td>
                          <td className="px-4 py-3">
                            <Badge variant={order.status === 'COMPLETED' ? 'default' : order.status === 'CANCELLED' ? 'destructive' : 'secondary'}>
                              {order.status}
                            </Badge>
                          </td>
                          <td className="px-4 py-3 text-muted-foreground">
                            {order.createdAt.toLocaleDateString()} {order.createdAt.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                          </td>
                          <td className="px-4 py-3 text-right">
                            <form action={deleteOrder}>
                              <input type="hidden" name="orderId" value={order.id} />
                              <button type="submit" className="text-muted-foreground hover:text-destructive transition-colors" title="Delete Order">
                                <Trash2 className="h-4 w-4 ml-auto" />
                              </button>
                            </form>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </CardBody>
          </Card>
        </div>
      </div>
    </div>
  );
}
