package dev.service;

import dev.dao.MenuItemDao;
import dev.dao.OrderDao;
import dev.dao.OrderDetailDao;
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 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) {
        List<MenuItem> items = menuItemDao.findAll();
        if (items.isEmpty()) {
            System.out.println("No menu items are currently available.");
            return;
        }

        System.out.println("\n[Placing Order]");
        System.out.println("Available Items:");
        for (MenuItem item : items) {
            System.out.printf("%d. %s - $%.2f\n", item.getId(), item.getName(), item.getPrice());
        }

        List<OrderDetail> cart = new ArrayList<>();
        double total = 0.0;

        while (true) {
            System.out.print("\nEnter the ID of the item to add (or 0 to finish): ");
            int itemId = scanner.nextInt();
            if (itemId == 0) {
                break;
            }

            MenuItem selectedItem = menuItemDao.findById(itemId);
            if (selectedItem == null) {
                System.out.println("Invalid item ID.");
                continue;
            }

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

            OrderDetail detail = new OrderDetail();
            detail.setMenuItemId(selectedItem.getId());
            detail.setQuantity(quantity);
            detail.setPrice(selectedItem.getPrice());

            cart.add(detail);
            total += selectedItem.getPrice() * quantity;
            System.out.printf("Added %dx %s to your cart.\n", quantity, selectedItem.getName());
        }

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

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

        int orderId = orderDao.save(order);
        if (orderId != -1) {
            for (OrderDetail detail : cart) {
                detail.setOrderId(orderId);
                orderDetailDao.save(detail);
            }
            printReceipt(orderId);
            System.out.println("Order saved successfully!");
        } else {
            System.out.println("An error occurred while saving the order.");
        }
    }

    public void printReceipt(int orderId) {
        List<OrderDetail> details = orderDetailDao.findByOrderId(orderId);
        if (details.isEmpty()) {
            System.out.println("No records found for the requested receipt.");
            return;
        }

        System.out.println("\n[Order Summary / Receipt]");
        System.out.println("---------------------------------------");
        System.out.printf("%-15s %-7s %-9s %-7s\n", "Item", "Qty", "Unit", "Total");
        System.out.println("---------------------------------------");
        double grandTotal = 0.0;
        for (OrderDetail detail : details) {
            MenuItem item = menuItemDao.findById(detail.getMenuItemId());
            String name = item != null ? item.getName() : "Unknown";
            double total = detail.getPrice() * detail.getQuantity();
            grandTotal += total;
            System.out.printf("%-15s %-7d $%-8.2f $%-7.2f\n", name, detail.getQuantity(), detail.getPrice(), total);
        }
        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 past orders found.");
            return;
        }

        System.out.println("\n--- ORDER HISTORY ---");
        for (Order order : orders) {
            System.out.printf("Order ID: %d | Date: %s | Total Spent: $%.2f\n",
                    order.getId(), order.getCreatedAt().toString(), order.getTotalPrice());
        }
        System.out.println("---------------------");
    }
}