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

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

// Helper function to get user name
const getUserName = (user: any) => {
  if (!user) return "N/A";
  if (user.name) return user.name;
  if (user.firstName || user.lastName) {
    return `${user.firstName || ""} ${user.lastName || ""}`.trim() || "N/A";
  }
  return "N/A";
};

// Helper function to get user initial
const getUserInitial = (user: any) => {
  const name = getUserName(user);
  return name !== "N/A" ? name.charAt(0).toUpperCase() : "N";
};

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
  });

  // Fetch products for the order rows
  const { data: productsData } = useQuery({
    queryKey: ["products-list"],
    queryFn: async () => {
      const res = await Axios.get<{ data: ProductT[]; total: number }>("/products/", {
        params: {
          isActive: true,
          limit: 1000,
        },
      });
      return res.data.data;
    },
    enabled: open,
  });

  const handleAddOrder = () => {
    const params = new URLSearchParams();
    params.set("customerId", String(customerId));
    if (firstName) params.set("firstName", firstName);
    if (lastName) params.set("lastName", lastName);
    router.push(`/customer/create-order?${params.toString()}`);
    onOpenChange(false);
  };

  // Function to render order rows (similar to EditableOrderRow)
  const renderOrderRows = (order: OrderT) => {
    const orderItemsData = order.orderItems || [];
    const hasProducts = orderItemsData.length > 0;

    if (!hasProducts || orderItemsData.length === 0) {
      return (
        <TableRow className="hover:bg-muted/30">
          <TableCell className="py-3">
            <div className="space-y-0.5">
              <div className="text-sm font-medium text-gray-800">
                {format(
                  new Date(
                    typeof order.createdAt === "string"
                      ? order.createdAt
                      : order.createdAt
                  ),
                  "dd-MMM-yy"
                )}
              </div>
              <div className="text-xs text-gray-500">
                {format(
                  new Date(
                    typeof order.createdAt === "string"
                      ? order.createdAt
                      : order.createdAt
                  ),
                  "h:mm aa"
                )}
              </div>
            </div>
          </TableCell>
          <TableCell className="py-3">
            <div className="flex items-center gap-2">
              <div className="w-7 h-7 rounded-full bg-primary/10 flex items-center justify-center flex-shrink-0">
                <span className="text-xs font-semibold text-primary">
                  {getUserInitial(order.createdBy)}
                </span>
              </div>
              <span className="text-sm truncate text-gray-700">{getUserName(order.createdBy)}</span>
            </div>
          </TableCell>
          <TableCell colSpan={7} className="py-3 text-center text-muted-foreground">
            No products
          </TableCell>
        </TableRow>
      );
    }

    const orderDate = new Date(
      typeof order.createdAt === "string" ? order.createdAt : order.createdAt
    );
    const formattedDate = format(orderDate, "dd-MMM-yy");
    const formattedTime = format(orderDate, "h:mm aa");
    const createdByName = getUserName(order.createdBy);

    let productsSubtotal = 0;
    let postageAmount = 0;
    let orderTotal = 0;
    let hasDiscount = false;
    let discountNote = "";

    orderItemsData.forEach((item, idx) => {
      const amountPerTub = Number(item.amountPerTub) || 0;
      // Exclude free products (amountPerTub = 0) from products subtotal
      // Free products should only be added via "Add a free product" button
      if (amountPerTub > 0) {
        const itemSubtotal = amountPerTub * item.count;
        productsSubtotal += itemSubtotal;
      }

      if (idx === 0 && item.postageServiceCharge) {
        postageAmount = Number(item.postageServiceCharge.amount) || 0;
      }

      // Get order note from first item (general order note is stored in first item's deductionNote)
      if (idx === 0 && item.deductionNote) {
        discountNote = item.deductionNote;
      }
    });

    orderTotal = productsSubtotal + postageAmount;
    // Get the actual order total by summing all items' totalAmount
    // This accounts for all products including any manual adjustments
    const actualOrderTotal = orderItemsData.reduce((sum, item) => {
      const itemTotal = item.totalAmount ? Number(item.totalAmount) : 0;
      return sum + itemTotal;
    }, 0);
    // Calculate discount amount if there's a difference
    // Discount = actual total - calculated total (products + postage, excluding free products)
    const discountAmount = actualOrderTotal !== orderTotal
      ? actualOrderTotal - orderTotal
      : 0;
    
    if (discountAmount !== 0 || discountNote) {
      hasDiscount = true;
    }

    const finalOrderTotal = actualOrderTotal > 0 ? actualOrderTotal : orderTotal;
    const totalRows = orderItemsData.length + (postageAmount > 0 ? 1 : 0) + (hasDiscount ? 1 : 0);
    const rows: React.ReactNode[] = [];

    orderItemsData.forEach((item, idx) => {
      const amountPerTub = Number(item.amountPerTub) || 0;
      const quantity = Number(item.count) || 0;
      const subtotal = amountPerTub * quantity;
      const isFirstProduct = idx === 0;

      rows.push(
        <TableRow key={`product-${item.id || idx}`} className="hover:bg-muted/30 border-b">
          {isFirstProduct && (
            <>
              <TableCell rowSpan={totalRows} className="py-3 align-top border-r">
                <div className="space-y-0.5">
                  <div className="text-sm font-medium text-gray-800">{formattedDate}</div>
                  <div className="text-xs text-gray-500">{formattedTime}</div>
                </div>
              </TableCell>
              <TableCell rowSpan={totalRows} className="py-3 align-top border-r">
                <div className="flex items-center gap-2">
                  <div className="w-7 h-7 rounded-full bg-primary/10 flex items-center justify-center flex-shrink-0">
                    <span className="text-xs font-semibold text-primary">
                      {getUserInitial(order.createdBy)}
                    </span>
                  </div>
                  <span className="text-sm truncate text-gray-700">{createdByName}</span>
                </div>
              </TableCell>
            </>
          )}
          <TableCell className="py-2 align-middle">
            <span className="text-sm text-gray-800">{item.product?.name || "N/A"}</span>
          </TableCell>
          <TableCell className="py-2 align-middle text-center">
            <span className="text-sm text-gray-700">{quantity}</span>
          </TableCell>
          <TableCell className="py-2 align-middle text-right">
            <span className="text-sm text-gray-700">{amountPerTub.toFixed(2)}</span>
          </TableCell>
          <TableCell className="py-2 align-middle text-right">
            <span className="text-sm font-medium text-gray-800">{subtotal.toFixed(2)}</span>
          </TableCell>
          {isFirstProduct && (
            <TableCell rowSpan={totalRows} className="py-3 align-top border-l border-r">
              <div className="text-sm font-bold text-primary">
                {finalOrderTotal.toFixed(2)}
              </div>
            </TableCell>
          )}
          {isFirstProduct && (
            <TableCell rowSpan={totalRows} className="py-3 align-top border-l border-r">
              <span className="text-xs text-gray-600 whitespace-normal break-words max-w-xs">
                {discountNote || "-"}
              </span>
            </TableCell>
          )}
          {isFirstProduct && (
            <TableCell rowSpan={totalRows} className="py-3 align-top border-l">
              <div className="flex justify-center">
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-8 w-8 hover:bg-primary/10"
                  onClick={() => {
                    const params = new URLSearchParams({
                      customerId: customerId.toString(),
                      orderId: order.id.toString(),
                      ...(firstName && { firstName }),
                      ...(lastName && { lastName }),
                    });
                    window.location.href = `/customer/create-order?${params.toString()}`;
                  }}
                >
                  <Pencil className="w-4 h-4 text-gray-600" />
                </Button>
              </div>
            </TableCell>
          )}
        </TableRow>
      );
    });

    if (postageAmount > 0) {
      rows.push(
        <TableRow key="shipping" className="hover:bg-muted/30 border-b">
          <TableCell className="py-2 align-middle">
            <span className="text-sm font-medium text-gray-800">Postage</span>
          </TableCell>
          <TableCell className="py-2 align-middle text-center">
            <span className="text-sm text-gray-400">-</span>
          </TableCell>
          <TableCell className="py-2 align-middle text-right">
            <span className="text-sm text-gray-400">-</span>
          </TableCell>
          <TableCell className="py-2 align-middle text-right">
            <span className="text-sm font-medium text-gray-800">{postageAmount.toFixed(2)}</span>
          </TableCell>
        </TableRow>
      );
    }

    if (hasDiscount) {
      rows.push(
        <TableRow key="discount" className="hover:bg-muted/30 border-b">
          <TableCell className="py-2 align-middle">
            <span className="text-sm font-medium text-gray-800">Discount/Round Off</span>
          </TableCell>
          <TableCell className="py-2 align-middle text-center">
            <span className="text-sm text-gray-400">-</span>
          </TableCell>
          <TableCell className="py-2 align-middle text-right">
            <span className="text-sm text-gray-400">-</span>
          </TableCell>
          <TableCell className="py-2 align-middle text-right">
            <span className={`text-sm font-medium ${discountAmount < 0 ? 'text-red-600' : 'text-gray-800'}`}>
              {discountAmount !== 0 ? discountAmount.toFixed(2) : "-"}
            </span>
          </TableCell>
        </TableRow>
      );
    }

    return rows;
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-6xl max-h-[85vh] 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 overflow-hidden">
              <div className="max-h-[60vh] overflow-y-auto">
                <Table>
                  <TableHeader className="sticky top-0 bg-white z-10 border-b">
                    <TableRow className="bg-blue-50 hover:bg-blue-50">
                      <TableHead className="font-semibold whitespace-nowrap text-gray-700 py-3">Date & Time</TableHead>
                      <TableHead className="font-semibold whitespace-nowrap text-gray-700 py-3">Created By</TableHead>
                      <TableHead className="font-semibold whitespace-nowrap text-gray-700 py-3">Product</TableHead>
                      <TableHead className="font-semibold whitespace-nowrap text-gray-700 py-3 text-center">Quantity</TableHead>
                      <TableHead className="font-semibold whitespace-nowrap text-gray-700 py-3 text-right">Price</TableHead>
                      <TableHead className="font-semibold whitespace-nowrap text-gray-700 py-3 text-right">Subtotal</TableHead>
                      <TableHead className="font-semibold whitespace-nowrap text-gray-700 py-3 text-right">Total</TableHead>
                      <TableHead className="font-semibold whitespace-nowrap text-gray-700 py-3">Reason for discount</TableHead>
                      <TableHead className="font-semibold whitespace-nowrap text-gray-700 py-3 text-center">Edit</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {ordersData.flatMap((order) => renderOrderRows(order))}
                  </TableBody>
                </Table>
              </div>
            </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>
  );
}

