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.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class OrderService {

    private final Scanner scanner = new Scanner(System.in);
    private MenuItemDao menuItemDao = new MenuItemDao();
    private OrderDao orderDao = new OrderDao();
    private OrderDetailDao orderDetailDao = new OrderDetailDao();
    private MenuService menuService = new MenuService();

    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");

    public void placeOrder(int userId) {
        Scanner scanner = new Scanner(System.in);
        List<OrderDetail> cart = new ArrayList<>();
        double grandTotal = 0.0;

        System.out.println("\n[Placing Order]");

        menuService.showMenu();

        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("Invalid Item ID. Please choose from the list.");
                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(itemId);
            detail.setQuantity(quantity);
            detail.setPrice(item.getPrice());
            cart.add(detail);

            grandTotal += (item.getPrice() * quantity);
            System.out.println("Added " + quantity + "x " + item.getName() + " to your cart.\n");
        }

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

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

        int orderId = orderDao.save(order);

        if (orderId != -1) {
            for (OrderDetail detail : cart) {
                detail.setOrderId(orderId);
                orderDetailDao.save(detail);
            }

            printReceipt(orderId);
        } else {
            System.out.println("System Error: Could not process order transaction.");
        }
    }

    public void printReceipt(int orderId) {
        List<OrderDetail> details = orderDetailDao.findByOrderId(orderId);

        System.out.println("\n[Order Summary / Receipt]");
        System.out.println("---------------------------------------");
        System.out.printf("%-18s %-5s %-9s %s\n", "Item", "Qty", "Unit", "Total");
        System.out.println("---------------------------------------");

        double finalTotal = 0.0;
        for (OrderDetail detail : details) {
            MenuItem item = menuItemDao.findById(detail.getMenuItemId());
            String itemName = (item != null) ? item.getName() : "Unknown Item";

            double lineTotal = detail.getQuantity() * detail.getPrice();
            finalTotal += lineTotal;

            System.out.printf("%-18s %-5d $%-8.2f $%.2f\n",
                    itemName,
                    detail.getQuantity(),
                    detail.getPrice(),
                    lineTotal);
        }

        System.out.println("---------------------------------------");
        System.out.printf("Final Total: $%.2f\n", finalTotal);
        System.out.println("Order saved successfully!");
    }

    public void showOrderHistory(int userId) {
        List<Order> orders = orderDao.findByUserId(userId);

        System.out.println("\n=======================================");
        System.out.println("             ORDER HISTORY             ");
        System.out.println("=======================================");

        if (orders.isEmpty()) {
            System.out.println("You have not placed any orders yet.");
            System.out.println("=======================================");
            System.out.println("Enter 0 to return to main menu: ");
            int choice = scanner.nextInt();
            while (choice != 0) {
                System.out.println("Invalid choice.");
                choice = scanner.nextInt();
            }
            return;

        }

        for (Order order : orders) {
            String formattedDate = order.getCreatedAt().format(formatter);
            System.out.println("Order ID: " + order.getId() +
                    " | Date: " + formattedDate +
                    " | Total: $" + order.getTotalPrice());
        }
        System.out.println("=======================================");
        System.out.println("Enter 0 to return to main menu: ");
        int choice = scanner.nextInt();
        while (choice != 0) {
            System.out.println("Invalid choice.");
            choice = scanner.nextInt();
        }
    }

}