package com.example.FinanceTracker.Controllers;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import com.example.FinanceTracker.Components.BootstrapColours;
// import com.example.FinanceTracker.Components.ColourComponent;
//import com.example.FinanceTracker.Components.PdfManager;
import com.example.FinanceTracker.DTOs.GroupedTransaction;
import com.example.FinanceTracker.DTOs.Home.OverviewCard;
import com.example.FinanceTracker.Models.Transaction;
//import com.example.FinanceTracker.Services.ReportService;
import com.example.FinanceTracker.Services.TransactionService;

@Controller
public class HomeController {

    // @Autowired
    // private PdfManager pdfManager;

    @Autowired
    private TransactionService transactionsService;

    // @Autowired
    // private ReportService reportService;

    private Locale saLocale = Locale.of("en", "ZA");
    private NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(saLocale);

    @GetMapping("/")
    public String Home(Model model) {

        // transactionsService.saveAll(pdfManager.extractTransactions());

        // Balance Text
        model.addAttribute("latestBalance",
                "Balance: " + currencyFormat.format(transactionsService.getLatestBalance()) + "*");

        // Overview Cards
        createOverviewCards(model);

        // Income Chart
        doughnutChart(
                model,
                new ArrayList<>(Arrays.asList("#00cc00", "#00ff00", "#33ff33")),
                transactionsService.getIncomeGroupedTransactions(),
                "incomeDoughnutdata", "incomeDoughnutLabels",
                "incomeDoughnutColours");
        model.addAttribute("incomeChartType", "bar");

        // Expenditure Chart
        doughnutChart(
                model,
                new ArrayList<>(Arrays.asList("#cc0000", "#ff0000", "#ff3333")),
                transactionsService.getExpenditureGroupedTransactions(),
                "expenseDoughnutdata", "expenseDoughnutLabels",
                "expenseDoughnutColours");
        model.addAttribute("expenseChartType", "bar");

        // Quarterly Chart
        createQuartlyChart(model);

        // Current Month's Transactions
        LocalDate currentDate = LocalDate.now();
        LocalDate firstDay = currentDate.with(TemporalAdjusters.firstDayOfMonth());
        LocalDate lastDay = currentDate.with(TemporalAdjusters.firstDayOfMonth());

        Page<Transaction> currentMonthsTransactions = transactionsService.getTransactionsBetween(0, 10,
                firstDay,
                lastDay);
        model.addAttribute("transactions", currentMonthsTransactions);

        // footer
        model.addAttribute("footerDetails", "Copyright © FinanceTracker " + LocalDate.now().getYear());

        return "index";
    }

    @GetMapping("/summary")
    public String getSummaryReport() {
        return "hello world";
    }

    private void createQuartlyChart(Model model) {
        ArrayList<String> quarterLabels = new ArrayList<>();
        ArrayList<BigDecimal> quarterMoneyIn = new ArrayList<>();
        ArrayList<BigDecimal> quarterMoneyOut = new ArrayList<>();

        transactionsService.getQuarterlyTotals(2025).forEach(qt -> {
            quarterLabels.add(qt.getQuarter());
            quarterMoneyIn.add(qt.getTotalMoneyIn());
            quarterMoneyOut.add(qt.getTotalMoneyOut().multiply(new BigDecimal(-1)));
        });

        model.addAttribute("labels", quarterLabels);
        model.addAttribute("moneyIn", quarterMoneyIn);
        model.addAttribute("moneyOut", quarterMoneyOut);
    }

    private void createOverviewCards(Model model) {
        OverviewCard avgMonthlyEarnings = new OverviewCard(
                "Average Monthly Earnings",
                currencyFormat.format(transactionsService.getAverageMonthlyMoneyIn(2025)),
                "text-" + BootstrapColours.SUCCESS, "border-left-" + BootstrapColours.SUCCESS, "",
                "money");

        OverviewCard totalAnnualEarnings = new OverviewCard(
                "Total Annual Earnings ",
                currencyFormat.format(transactionsService.getTotalMoneyInByYear(2025)),
                "text-" + BootstrapColours.SUCCESS, "border-left-" + BootstrapColours.SUCCESS, "",
                "money");

        // Net Cashflow Card
        double netCashflow = transactionsService.getNetCashflow();
        OverviewCard avgMonthlyExpenditure = new OverviewCard(
                "Net Cashflow",
                currencyFormat.format(netCashflow),
                "text-" + ((netCashflow < 0) ? BootstrapColours.DANGER : BootstrapColours.SUCCESS),
                "border-left-" + ((netCashflow < 0) ? BootstrapColours.DANGER
                        : BootstrapColours.SUCCESS),
                "", "money");

        OverviewCard totalAnnualFees = new OverviewCard(
                "Total Annual Fees",
                currencyFormat.format(transactionsService.getTotalFeesByYear(2025)),
                "text-" + BootstrapColours.DANGER, "border-left-" + BootstrapColours.DANGER, "",
                "money");

        model.addAttribute("avgMonthlyEarnings", avgMonthlyEarnings);
        model.addAttribute("avgMonthlyExpenditure", avgMonthlyExpenditure);
        model.addAttribute("totalAnnualEarnings", totalAnnualEarnings);
        model.addAttribute("totalAnnualFees", totalAnnualFees);
    }

    private void doughnutChart(Model model,
            ArrayList<String> colours, List<GroupedTransaction> allTransactions,
            String modelData, String modelLables, String modelColours) {

        String[] categories = new String[allTransactions.size()];
        BigDecimal[] values = new BigDecimal[allTransactions.size()];

        for (int i = 0; i < allTransactions.size(); i++) {
            categories[i] = allTransactions.get(i).getCategory();
            values[i] = allTransactions.get(i).getValue();
        }

        model.addAttribute(modelData, values);
        model.addAttribute(modelLables, categories);
        model.addAttribute(modelColours, colours);

    }

}
