"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Box, Button, IconButton, Paper, Typography } from "@mui/material";

import MoreVertIcon from "@mui/icons-material/MoreVert";
import { type ITransactionsOverviewData } from "@/app/services/types";
import { dashboardService } from "@/app/services/dashboardService";
import {
  transformOverviewResponse,
  calculatePercentages,
  enrichOverviewData,
} from "../TransactionsOverview/utils";
import { TransactionsOverViewTable } from "./components/TransactionsOverViewTable";
import PieCharts from "../Charts/PieCharts";
import "./TransactionsOverView.scss";

interface ITransactionsOverviewProps {
  initialOverviewData?: ITransactionsOverviewData | null;
}

export const TransactionsOverview = ({
  initialOverviewData = null,
}: ITransactionsOverviewProps) => {
  const router = useRouter();
  const [overviewData, setOverviewData] =
    useState<ITransactionsOverviewData | null>(
      initialOverviewData ||
        dashboardService.getCurrentDashboardData()?.overviewData ||
        null
    );

  /**
   * Subscribe to dashboard data changes
   */
  useEffect(() => {
    const subscription = dashboardService
      .getDashboardData$()
      .subscribe(data => {
        if (data?.overviewData) {
          setOverviewData(data.overviewData);
        }
      });

    // Cleanup subscription on unmount
    return () => subscription.unsubscribe();
  }, []);

  /**
   * Transform overview data from flat object to array format
   */
  const transformedData = overviewData
    ? transformOverviewResponse({
        cancelled: overviewData.cancelled,
        failed: overviewData.failed,
        successful: overviewData.successful,
        waiting: overviewData.waiting,
      })
    : [];

  /**
   * Calculate percentages and enrich with colors
   */
  const enrichedData =
    transformedData.length > 0
      ? enrichOverviewData(calculatePercentages(transformedData))
      : [];

  /**
   * Transform overview data for PieCharts (expects { name, value }[])
   */
  const pieChartData = enrichedData.map(item => ({
    name: item.state,
    value: item.count,
  }));

  /**
   * Transform overview data for table (expects { state, count, percentage, color }[])
   */
  const tableData = enrichedData;

  return (
    <Paper className="transaction-overview" elevation={3}>
      <Box className="transaction-overview__header">
        <Typography variant="h5" fontWeight="bold">
          Transactions Overview
        </Typography>
        <Box>
          <Button
            variant="contained"
            color="primary"
            onClick={() => router.push("dashboard/transactions/all")}
          >
            All Transactions
          </Button>
          <IconButton size="small">
            <MoreVertIcon fontSize="small" />
          </IconButton>
        </Box>
      </Box>

      {overviewData && (
        <Box className="transaction-overview__chart-table">
          <PieCharts data={pieChartData} />
          <TransactionsOverViewTable data={tableData} />
        </Box>
      )}
    </Paper>
  );
};
