"use client";
import React, { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import Axios from "@/lib/Axios";
import { OrderT } from "@/types/orders";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Plus, ArrowRight } from "lucide-react";
import { format } from "date-fns";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { useRouter } from "next/navigation";
import Link from "next/link";

interface CustomerOrdersDialogProps {
  customerId: number;
  customerName?: string;
  firstName?: string;
  lastName?: string;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function CustomerOrdersDialog({
  customerId,
  customerName,
  firstName,
  lastName,
  open,
  onOpenChange,
}: CustomerOrdersDialogProps) {
  const router = useRouter();

  const {
    data: ordersData,
    isLoading: ordersLoading,
    refetch: refetchOrders,
  } = useQuery({
    queryKey: ["customer-orders-dialog", customerId],
    queryFn: async () => {
      const res = await Axios.get<{ data: OrderT[]; total: number }>("/orders/", {
        params: {
          customerId: customerId,
          limit: 100, // Get all orders for this customer
        },
      });
      return res.data.data;
    },
    enabled: open && !!customerId, // Only fetch when dialog is open
  });

  const handleAddOrder = () => {
    // Navigate to customer view-details page which shows the order list section
    const firstNameParam = firstName || customerName?.split(" ")[0] || "";
    const lastNameParam = lastName || customerName?.split(" ").slice(1).join(" ") || "";
    router.push(
      `/customer/customer-manage/${customerId}?firstName=${firstNameParam}&lastName=${lastNameParam}`
    );
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>
            Orders for {customerName || `Customer #${customerId}`}
          </DialogTitle>
          <DialogDescription>
            View and manage all orders for this customer
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4">
          <div className="flex justify-end">
            <Button onClick={handleAddOrder} className="gap-2">
              <Plus className="w-4 h-4" />
              Add Order
            </Button>
          </div>
          {ordersLoading ? (
            <div className="text-center py-8">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
              <p className="mt-2 text-sm text-muted-foreground">Loading orders...</p>
            </div>
          ) : ordersData && ordersData.length > 0 ? (
            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Order Number</TableHead>
                    <TableHead>Date & Time</TableHead>
                    <TableHead>Created By</TableHead>
                    <TableHead>Products</TableHead>
                    <TableHead>Total Items</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {ordersData.map((order) => (
                    <TableRow key={order.id}>
                      <TableCell className="font-medium">
                        {order.orderNumber || `Order #${order.id}`}
                      </TableCell>
                      <TableCell>
                        <div className="space-y-1">
                          <div className="text-sm">
                            {format(
                              new Date(
                                typeof order.createdAt === "string"
                                  ? order.createdAt
                                  : order.createdAt
                              ),
                              "dd MMM, yyyy"
                            )}
                          </div>
                          <div className="text-xs text-muted-foreground">
                            {format(
                              new Date(
                                typeof order.createdAt === "string"
                                  ? order.createdAt
                                  : order.createdAt
                              ),
                              "h:mm aa"
                            )}
                          </div>
                        </div>
                      </TableCell>
                      <TableCell>
                        {order.createdBy?.name ||
                          `${order.createdBy?.firstName || ""} ${order.createdBy?.lastName || ""}`.trim() ||
                          "N/A"}
                      </TableCell>
                      <TableCell>
                        {order.orderItems && order.orderItems.length > 0 ? (
                          <div className="space-y-1">
                            {order.orderItems.map((item, idx) => (
                              <div key={item.id || idx} className="text-sm">
                                {item.product?.name || "N/A"} (x{item.count})
                              </div>
                            ))}
                          </div>
                        ) : (
                          <span className="text-sm text-muted-foreground">No products</span>
                        )}
                      </TableCell>
                      <TableCell>
                        {order.orderItems
                          ? order.orderItems.reduce((sum, item) => sum + item.count, 0)
                          : 0}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          ) : (
            <div className="text-center py-12">
              <p className="text-muted-foreground mb-4">No orders found for this customer</p>
              <Button onClick={handleAddOrder} variant="outline" className="gap-2">
                <Plus className="w-4 h-4" />
                Add First Order
              </Button>
            </div>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}

