import { redirect } from "next/navigation";
import Link from "next/link";
import { ArrowLeft } from "lucide-react";
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";

export async function generateMetadata({ params }: { params: Promise<{ id: string }> }) {
  const resolvedParams = await params;
  return { title: `Order ${resolvedParams.id.slice(-8)} | WhatsApp CRM` };
}

export default async function OrderDetailsPage({ params }: { params: Promise<{ id: string }> }) {
  const resolvedParams = await params;
  const session = await requireAccount();

  const order = await prisma.order.findFirst({
    where: { 
      id: resolvedParams.id,
      accountId: session.accountId 
    },
    include: {
      contact: true,
    }
  });

  if (!order) {
    redirect("/orders");
  }

  // Parse items safely
  let items = [];
  try {
    items = typeof order.items === 'string' ? JSON.parse(order.items) : order.items;
    if (!Array.isArray(items)) items = [];
  } catch (e) {
    items = [];
  }

  const retailerIds = items.map((item: any) => item.retailerId).filter(Boolean);
  const products = await prisma.product.findMany({
    where: {
      accountId: session.accountId,
      OR: [
        { id: { in: retailerIds } },
        { sku: { in: retailerIds } },
      ],
    },
    select: { id: true, sku: true, name: true }
  });

  const getProductName = (retailerId: string) => {
    if (retailerId === "SHIPPING") return "Shipping Charge";
    const p = products.find(x => x.id === retailerId || x.sku === retailerId);
    return p ? p.name : "Unknown Product";
  };

  return (
    <div className="flex h-full flex-col">
      <div className="flex h-14 items-center gap-4 border-b border-border bg-card px-6">
        <Link href="/orders" className="text-muted-foreground hover:text-foreground transition-colors">
          <ArrowLeft className="h-5 w-5" />
        </Link>
        <h1 className="text-lg font-semibold text-foreground">Order {order.id.slice(-8)}</h1>
        <Badge variant={order.status === 'COMPLETED' ? 'default' : order.status === 'CANCELLED' ? 'destructive' : 'secondary'} className="ml-2">
          {order.status}
        </Badge>
      </div>

      <div className="flex-1 overflow-auto p-6 bg-background">
        <div className="mx-auto max-w-4xl space-y-6">
          <div className="grid gap-6 md:grid-cols-2">
            {/* Customer Details */}
            <Card>
              <CardHeader>
                <CardTitle>Customer Details</CardTitle>
              </CardHeader>
              <CardBody className="space-y-4">
                <div>
                  <div className="text-sm font-medium text-muted-foreground">Name</div>
                  <div className="text-base text-foreground font-medium">{order.contact.name}</div>
                </div>
                <div>
                  <div className="text-sm font-medium text-muted-foreground">WhatsApp Number</div>
                  <div className="text-base text-foreground">{order.contact.phone}</div>
                </div>
                <div>
                  <div className="text-sm font-medium text-muted-foreground">Date Placed</div>
                  <div className="text-base text-foreground">
                    {order.createdAt.toLocaleDateString()} {order.createdAt.toLocaleTimeString()}
                  </div>
                </div>
              </CardBody>
            </Card>

            {/* Order Summary */}
            <Card>
              <CardHeader>
                <CardTitle>Order Summary</CardTitle>
              </CardHeader>
              <CardBody className="space-y-4">
                <div className="flex justify-between items-center py-2 border-b border-border">
                  <div className="text-sm font-medium text-muted-foreground">Total Amount</div>
                  <div className="text-xl font-bold text-foreground">
                    {Number(order.totalAmount).toLocaleString(undefined, { style: 'currency', currency: order.currency })}
                  </div>
                </div>
                <div>
                  <div className="text-sm font-medium text-muted-foreground">Catalog ID</div>
                  <div className="text-sm text-foreground font-mono mt-1">{order.catalogId || "N/A"}</div>
                </div>
                <div>
                  <div className="text-sm font-medium text-muted-foreground">Message ID (WAMID)</div>
                  <div className="text-sm text-muted-foreground font-mono truncate mt-1">{order.wamid || "N/A"}</div>
                </div>
              </CardBody>
            </Card>
          </div>

          {/* Order Items */}
          <Card>
            <CardHeader>
              <CardTitle>Order Items</CardTitle>
            </CardHeader>
            <CardBody>
              {items.length === 0 ? (
                <div className="text-sm text-muted-foreground py-4">No item details available for this order.</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">Product</th>
                        <th className="px-4 py-3 font-medium">Product ID</th>
                        <th className="px-4 py-3 font-medium text-center">Quantity</th>
                        <th className="px-4 py-3 font-medium text-right">Unit Price</th>
                        <th className="px-4 py-3 font-medium text-right">Subtotal</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border bg-card">
                      {items.map((item: any, idx: number) => {
                        const price = parseFloat(item.itemPrice || "0");
                        const qty = parseInt(item.quantity || "1", 10);
                        const subtotal = price * qty;
                        
                        return (
                          <tr key={idx} className="hover:bg-muted/50 transition-colors">
                            <td className="px-4 py-3 font-medium text-foreground">
                              {getProductName(item.retailerId)}
                            </td>
                            <td className="px-4 py-3 font-mono text-xs text-muted-foreground">
                              {item.retailerId || "N/A"}
                            </td>
                            <td className="px-4 py-3 text-center">
                              {qty}
                            </td>
                            <td className="px-4 py-3 text-right text-muted-foreground">
                              {price.toLocaleString(undefined, { style: 'currency', currency: item.currency || order.currency })}
                            </td>
                            <td className="px-4 py-3 text-right font-medium">
                              {subtotal.toLocaleString(undefined, { style: 'currency', currency: item.currency || order.currency })}
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              )}
            </CardBody>
          </Card>
        </div>
      </div>
    </div>
  );
}
