package dev.service;

import dev.dao.OrderDao;
import dev.dao.OrderDetailDao;
import dev.dao.MenuItemDao;
import dev.model.MenuItem;
import dev.model.Order;
import dev.model.OrderDetail;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class OrderService {
    private OrderDao orderDao = new OrderDao();
    private OrderDetailDao orderDetailDao = new OrderDetailDao();
    private MenuItemDao menuItemDao = new MenuItemDao();
    private MenuService menuService = new MenuService();

    public void placeOrder(int userId) {

        Scanner scanner = new Scanner(System.in);
        List<OrderDetail> cart = new ArrayList<>();
        double total = 0.0;

        System.out.println("\n[Placing Order]");
        while (true) {
            menuService.showMenu();
            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("Invalid item ID. Try again.");
                continue;
            }

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

            double subtotal = item.getPrice() * qty;
            OrderDetail detail = new OrderDetail();
            detail.setMenuItemId(itemId);
            detail.setQuantity(qty);
            detail.setPrice(item.getPrice());
            cart.add(detail);

            total += subtotal;
            System.out.printf("Added %dx %s to your cart.\n", qty, item.getName());
        }

        if (cart.isEmpty()) {
            System.out.println("No items selected. Order cancelled.");
            return;
        }


        Order order = new Order();
        order.setUserId(userId);
        order.setCreatedAt(LocalDateTime.now());
        order.setTotalPrice(total);

        int orderId = orderDao.save(order);
        if (orderId == -1) {
            System.out.println("Failed to save order.");
            return;
        }


        for (OrderDetail detail : cart) {
            detail.setOrderId(orderId);
            orderDetailDao.save(detail);
        }

        System.out.println("Order saved successfully!");
        printReceipt(orderId);

    }

    public void printReceipt(int orderId) {
        Order order = orderDao.findById(orderId);
        if (order == null) {
            System.out.println("Order not found.");
            return;
        }

        List<OrderDetail> details = orderDetailDao.findByOrderId(orderId);
        if (details.isEmpty()) {
            System.out.println("No details found for this order.");
            return;
        }

        System.out.println("\n[Order Summary / Receipt]");
        System.out.println("Order ID: " + orderId);
        System.out.println("Date: " + order.getCreatedAt());
        System.out.println("---------------------------------------");
        System.out.printf("%-20s %-5s %-10s %-10s\n", "Item", "Qty", "Unit", "Total");
        System.out.println("---------------------------------------");

        double grandTotal = 0.0;
        for (OrderDetail detail : details) {
            MenuItem item = menuItemDao.findById(detail.getMenuItemId());
            String itemName = (item != null) ? item.getName() : "Unknown";
            double lineTotal = detail.getPrice() * detail.getQuantity();
            System.out.printf("%-20s %-5d $%-9.2f $%-9.2f\n",
                    itemName, detail.getQuantity(), detail.getPrice(), lineTotal);
            grandTotal += lineTotal;
        }
        System.out.println("---------------------------------------");
        System.out.printf("Final Total: $%.2f\n", grandTotal);

    }

    public void showOrderHistory(int userId) {
        List<Order> orders = orderDao.findByUserId(userId);
        if (orders.isEmpty()) {
            System.out.println("No orders found for this user.");
            return;
        }

        System.out.println("\n[Order History]");
        System.out.printf("%-8s %-20s %-12s\n", "Order ID", "Date", "Total");
        System.out.println("--------------------------------------");
        for (Order order : orders) {
            System.out.printf("%-8d %-20s $%-10.2f\n",
                    order.getId(), order.getCreatedAt().toString(), order.getTotalPrice());
        }
    }

}