package dev.service;
import dev.dao.MenuItemDao;
import dev.dao.OrderDao;
import dev.dao.OrderDetailDao;
import dev.model.Order;
import dev.model.MenuItem;
import dev.model.OrderDetail;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class OrderService {
    private final MenuItemDao menuItemDao = new MenuItemDao();
    private final OrderDao orderDao = new OrderDao();
    private final OrderDetailDao orderDetailDao = new OrderDetailDao();
    private final Scanner scanner = new Scanner(System.in);
    public void placeOrder(int userId) {

        // TODO:
        // Create order
        List<OrderDetail> cart = new ArrayList<>();
        double grandTotal = 0.0;

        try {
            Field itemPriceField = MenuItem.class.getDeclaredField("price");
            Field itemNameField = MenuItem.class.getDeclaredField("name");
            itemPriceField.setAccessible(true);
            itemNameField.setAccessible(true);

            while (true){
                System.out.print("Enter the ID of the item to add (or 0 to finish): ");
                int itemId = scanner.nextInt();
                if (itemId == 0) break;
                MenuItem item = menuItemDao.findById(itemId);
                if (item == null){
                    System.out.println("Item not found!");
                    continue;
                }

                System.out.print("Enter quantity: ");
                int quantity = scanner.nextInt();
                if (quantity <= 0){
                    System.out.println("Quantity must be greater than zero!");
                    continue;
                }
                double price = (double) itemPriceField.get(item);

                OrderDetail detail = new OrderDetail();
                Field ordDetItemField = OrderDetail.class.getDeclaredField("menuItemId");
                Field ordDetQtyField = OrderDetail.class.getDeclaredField("quantity");
                Field ordDetPrcField = OrderDetail.class.getDeclaredField("price");
                ordDetItemField.setAccessible(true);
                ordDetQtyField.setAccessible(true);
                ordDetPrcField.setAccessible(true);
                ordDetItemField.set(detail, itemId);
                ordDetQtyField.set(detail, quantity);
                ordDetPrcField.set(detail, price);
                cart.add(detail);
                grandTotal += (price * quantity);
                System.out.println("Added " + quantity + "x " + itemNameField.get(item) + " to your cart.");
            }

            if (cart.isEmpty()){
                System.out.println("Cart is empty. Order cancelled.");
                return;
            }

            Order order = new Order();
            Field ordUserField = Order.class.getDeclaredField("userId");
            Field ordTotalField = Order.class.getDeclaredField("totalPrice");
            ordUserField.setAccessible(true);
            ordTotalField.setAccessible(true);
            ordUserField.set(order, userId);
            ordTotalField.set(order, grandTotal);

            int orderId = orderDao.save(order);
            if (orderId != -1){
                Field ordDetIdField = OrderDetail.class.getDeclaredField("orderId");
                ordDetIdField.setAccessible(true);
                for (OrderDetail detail : cart){
                    ordDetIdField.set(detail, orderId);
                    orderDetailDao.save(detail);
                }
                System.out.println("Order saved successfully!");
                printReceipt(orderId);
            }
            else{
                System.out.println("Failed to save order.");
            }

        }
        catch (Exception ex){
            ex.printStackTrace();
        }

    }

    public void printReceipt(int orderId) {

        // TODO:
        // Print order receipt
        System.out.println("\n[Order Receipt]");
        System.out.println("---------------------------------------");
        System.out.printf("%-12s %-7s %-9s %s\n", "Item", "Qty", "Unit", "Total");
        System.out.println("---------------------------------------");

        List<OrderDetail> details = orderDetailDao.findByOrderId(orderId);
        double finalTotal = 0.0;

        try {
            Field itemField = OrderDetail.class.getDeclaredField("menuItemId");
            Field qtyField = OrderDetail.class.getDeclaredField("quantity");
            Field prcField = OrderDetail.class.getDeclaredField("price");
            itemField.setAccessible(true);
            qtyField.setAccessible(true);
            prcField.setAccessible(true);
            Field itemNameField = MenuItem.class.getDeclaredField("name");
            itemNameField.setAccessible(true);
            for (OrderDetail detail : details){
                int itemId = (int) itemField.get(detail);
                int qty = (int) qtyField.get(detail);
                double unitPrice = (double) prcField.get(detail);
                double total = unitPrice * qty;
                finalTotal += total;
                MenuItem item = menuItemDao.findById(itemId);
                String itemName = (item != null) ? (String) itemNameField.get(item) : "Unknown";
                System.out.printf("%-12s %-7d $%-8.2f $%.2f\n", itemName, qty, unitPrice, total);
            }
            System.out.println("---------------------------------------");
            System.out.printf("Final Total: $%.2f\n", finalTotal);
        }
        catch (Exception ex){
            ex.printStackTrace();
        }

    }

    public void showOrderHistory(int userId) {

        // TODO:
        // Display user's order history
        List<Order> orders = orderDao.findByUserId(userId);
        System.out.println("\n--- ORDER HISTORY ---");
        if (orders.isEmpty()){
            System.out.println("No past orders found.");
            return;
        }

        try {
            Field idField = Order.class.getDeclaredField("id");
            Field dateField = Order.class.getDeclaredField("createdAt");
            Field totalField = Order.class.getDeclaredField("totalPrice");
            idField.setAccessible(true);
            dateField.setAccessible(true);
            totalField.setAccessible(true);
            for (Order order : orders){
                System.out.printf("Order ID: %d | Date: %s | Total Spent: $%.2f\n", idField.get(order), dateField.get(order), totalField.get(order));
            }
        }
        catch (Exception ex){
            ex.printStackTrace();
        }

    }

}