import { Request, Response } from 'express';
import { PrismaClient, OrderStatus, PaymentStatus } from '@prisma/client';

const prisma = new PrismaClient();

// GET /api/admin/orders
// Handles List View with Search & Tabs
export const getOrders = async (req: Request, res: Response) => {
  try {
    const { search, status, tab } = req.query;

    const whereClause: any = {};

    // 1. Filter by Tab
    if (tab === 'pending') {
      whereClause.status = 'PENDING';
    } else if (tab === 'shipped') {
      whereClause.status = 'SHIPPED';
    } else if (tab === 'returns') {
      whereClause.status = { in: ['CANCELLED', 'RETURNED'] };
    }

    // 2. Search (Order # or Customer Name)
    if (search) {
      whereClause.OR = [
        { orderNumber: { contains: String(search), mode: 'insensitive' } },
        { user: { fullName: { contains: String(search), mode: 'insensitive' } } },
      ];
    }

    // 3. Query DB
    const orders = await prisma.order.findMany({
      where: whereClause,
      include: {
        user: { select: { fullName: true } },
        payment: { select: { status: true } },
        
      },
      orderBy: { createdAt: 'desc' },
      take: 50, // Limit for performance
    });

    // 4. Format for UI
    const formattedOrders = orders.map((order) => ({
      id: order.id,
      orderNumber: order.orderNumber,
      customer: order.user?.fullName || 'Guest',
      date: order.createdAt.toLocaleDateString('en-IN', { month: 'short', day: 'numeric', year: 'numeric' }),
      total: Number(order.total),
      status: order.status,
      paymentStatus: order.payment?.status || 'PENDING',
    }));

    res.json(formattedOrders);
  } catch (error) {
    console.error('Get Orders Error:', error);
    res.status(500).json({ error: 'Failed to fetch orders' });
  }
};

// GET /api/admin/orders/:id
// Handles the Details Page
export const getOrderDetails = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;

    const order = await prisma.order.findUnique({
      where: { id },
      include: {
        user: true,
        items: true,
        shippingAddress: true,
        payment: true,
      },
    });

    if (!order) {
      return res.status(404).json({ error: "Order not found" });
    }

    // Customer total orders count
    const customerOrderCount = order.userId
      ? await prisma.order.count({ where: { userId: order.userId } })
      : 1;

    // Response
    const responseData = {
      id: order.orderNumber, // Display ID
      dbId: order.id,        // UUID
      date: order.createdAt.toLocaleString("en-IN", {
        dateStyle: "medium",
        timeStyle: "short",
      }),
      status: order.status,
      paymentStatus: order.payment?.status || "PENDING",
      paymentMethod: order.payment?.provider || "N/A",

      customer: {
        name: order.user?.fullName || "Guest",
        email:
          order.user?.email ||
          order.shippingAddress?.email ||
          "N/A",
        phone:
          order.user?.phone ||
          order.shippingAddress?.phone ||
          "N/A",
        ordersCount: customerOrderCount,
      },

      shippingAddress: order.shippingAddress,
      billingAddress: order.shippingAddress,

      // 🔥 ITEMS WITH IMAGE ADDED
      items: order.items.map((item) => ({
        name: item.productName,
        image: item.productImage, // ✅ IMAGE INCLUDED
        sku: item.sku || "N/A",
        size: item.size || null,
        color: item.color || null,
        price: Number(item.price),
        qty: item.quantity,
        total: Number(item.price) * item.quantity,
      })),

      subtotal: Number(order.subtotal),
      tax: Number(order.tax),
      shipping: Number(order.shippingCost),
      total: Number(order.total),
    };

    res.json(responseData);
  } catch (error) {
    console.error("Get Order Detail Error:", error);
    res.status(500).json({ error: "Failed to fetch order details" });
  }
};


// PUT /api/admin/orders/:id/status
export const updateOrderStatus = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { status } = req.body; 

    // Validate Status Enum (Optional strict check)
    // if (!Object.values(OrderStatus).includes(status)) ...

    const updatedOrder = await prisma.order.update({
      where: { id },
      data: { status },
    });

    res.json({ message: 'Order status updated', status: updatedOrder.status });
  } catch (error) {
    console.error('Update Status Error:', error);
    res.status(500).json({ error: 'Failed to update status' });
  }
};

// PUT /api/admin/orders/:id/payment
export const updatePaymentStatus = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { status } = req.body;

    // 1. Update Payment Record
    const updateResult = await prisma.payment.update({
      where: { orderId: id },
      data: { status },
    });

    // 2. Sync Order.isPaid Boolean
    const isPaid = status === 'PAID';
    await prisma.order.update({
      where: { id },
      data: { isPaid }
    });

    res.json({ message: 'Payment status updated', result: updateResult });
  } catch (error) {
    console.error('Update Payment Error:', error);
    res.status(500).json({ error: 'Failed to update payment status' });
  }
};