"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 { 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 => {
        // console.log("[data]", data);
        if (data?.overviewData) {
          console.log("[OverViewData] - Subscribe", data);
          setOverviewData(data.overviewData);
        }
      });

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

  console.log("[OverviewData] - Component", overviewData);
  /**
   * Use transformed data from API (already includes percentages and colors)
   */
  const enrichedData = overviewData?.data || [];

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

  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={overviewData?.data || []} />
        </Box>
      )}
    </Paper>
  );
};
