"use client";

import type { ReactNode } from "react";

import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import type { SxProps, Theme } from "@mui/material/styles";
import { alpha, useTheme } from "@mui/material/styles";

export type StatsCardItem = {
  id: string;
  label: ReactNode;
  value: ReactNode;
  backgroundColor: string;
  borderColor: string;
  icon?: ReactNode;
};

export type StatsCardsProps = {
  cards: StatsCardItem[];
  sx?: SxProps<Theme>;
};

const darkCardStyles = [
  { bg: "#132b50", border: "#1d5aa6" },
  { bg: "#123734", border: "#1f7a61" },
  { bg: "#34291d", border: "#9a650b" },
  { bg: "#3a1f32", border: "#93415a" },
];

type StatsCardProps = StatsCardItem & {
  index: number;
};

function StatsCard({
  label,
  value,
  backgroundColor,
  borderColor,
  icon,
  index,
}: StatsCardProps) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const darkStyle = darkCardStyles[index % darkCardStyles.length];

  return (
    <Box
      sx={{
        width: "100%",
        height: 108,
        p: "22px 20px",
        borderRadius: "12px",
        bgcolor: isDark ? darkStyle.bg : backgroundColor,
        border: `1px solid ${isDark ? darkStyle.border : borderColor}`,
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        gap: 2,
      }}
    >
      <Box sx={{ minWidth: 0, flex: 1 }}>
        <Typography
          sx={{
            color: isDark ? alpha("#ffffff", 0.78) : "#717680",
            fontSize: 12,
            fontWeight: 400,
            lineHeight: 1.2,
            whiteSpace: "nowrap",
          }}
        >
          {label}
        </Typography>

        <Typography
          sx={{
            mt: 1.3,
            color: isDark ? "#ffffff" : "#414651",
            fontSize: 30,
            fontWeight: 700,
            lineHeight: 1,
            letterSpacing: "-0.04em",
          }}
        >
          {value}
        </Typography>
      </Box>

      {icon ? (
        <Box
          sx={{
            width: 46,
            height: 46,
            borderRadius: "10px",
            bgcolor: isDark ? "#0f172a" : "#ffffff",
            border: `1px solid ${
              isDark ? alpha("#ffffff", 0.08) : borderColor
            }`,
            display: "grid",
            placeItems: "center",
            flexShrink: 0,
          }}
        >
          {icon}
        </Box>
      ) : null}
    </Box>
  );
}

export function StatsCards({ cards, sx }: StatsCardsProps) {
  return (
    <Box
      sx={{
        display: "grid",
        gridTemplateColumns: {
          xs: "1fr",
          sm: "repeat(2, minmax(0, 1fr))",
          lg: "repeat(4, minmax(0, 1fr))",
        },
        gap: 3,
        ...sx,
      }}
    >
      {cards.map((card, index) => (
        <StatsCard key={card.id} {...card} index={index} />
      ))}
    </Box>
  );
}
