package dev.service;

import dev.dao.MenuItemDao;
import dev.dao.OrderDao;
import dev.dao.OrderDetailDao;
import dev.model.Order;
import dev.model.OrderDetail;
import dev.model.MenuItem;
import dev.ui.ConsoleStyle;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Scanner;

public class OrderService
{

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

    public void placeOrder(int userId)
    {
        System.out.println("\n--- Create New Order ---");

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

        int orderId = orderDao.save(order);

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

        double total = 0;
        List<OrderDetail> details = new java.util.ArrayList<>();

        while (true)
        {
            System.out.print("Enter Menu Item ID (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("Quantity for " + item.getName() + ": ");
            int quantity = scanner.nextInt();

            OrderDetail detail = new OrderDetail();
            detail.setOrderId(orderId);
            detail.setMenuItemId(itemId);
            detail.setQuantity(quantity);
            detail.setPrice(item.getPrice());

            orderDetailDao.save(detail);
            details.add(detail);

            total += (item.getPrice() * quantity);
            System.out.println("Added: " + item.getName() + " x" + quantity);
        }

        order.setId(orderId);
        order.setTotalPrice(total);
        orderDao.updateTotalPrice(orderId, total);

        System.out.println("Order #" + orderId + " placed successfully. Total: $" + total);

        printReceipt(order, details);
    }

    private void printReceipt(Order order, List<OrderDetail> details)
    {
        ConsoleStyle.printHeader("🧾 RECEIPT ");

        System.out.println("Order ID: " + order.getId());
        System.out.println("Date    : " + order.getCreatedAt().toString().replace("T", " "));
        ConsoleStyle.printLine();

        System.out.printf("%-20s %-8s %-12s %-12s%n", "Item Name", "Qty", "Unit Price", "Total");
        ConsoleStyle.printLine();

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

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

            System.out.printf(
                    "%-20s %-8d $%-11.2f $%-11.2f%n",
                    itemName,
                    detail.getQuantity(),
                    detail.getPrice(),
                    lineTotal
            );
        }

        ConsoleStyle.printLine();
        System.out.printf("%-42s $%.2f%n", "Grand Total:", order.getTotalPrice());
        ConsoleStyle.printLine();
    }

    public void showOrderHistory(int userId)
    {
        System.out.println("\n--- 📜 Order History (Detailed) ---");
        List<Order> history = orderDao.findByUserId(userId);

        if (history.isEmpty())
        {
            System.out.println("You have no previous orders.");
            return;
        }

        for (Order o : history) {
            System.out.println("==========================================");
            System.out.printf("ORDER ID: %-5d | Date: %s\n", o.getId(), o.getCreatedAt().toString().replace("T", " "));
            System.out.println("Items:");

            List<OrderDetail> details = orderDetailDao.findByOrderId(o.getId());

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

                System.out.printf("   - %-20s x%-3d ($%.2f)\n", itemName, detail.getQuantity(), detail.getPrice());
            }

            System.out.printf("TOTAL: $%.2f\n", o.getTotalPrice());
        }
        System.out.println("==========================================");
    }

}