"use client";

import { useState } from "react";

import Box from "@mui/material/Box";
import ButtonBase from "@mui/material/ButtonBase";
import Typography from "@mui/material/Typography";
import { alpha } from "@mui/material/styles";

import type { IssueViewDetailReportTab } from "./issue-view-detail-types";

function ReportTabButton({
  active,
  isDark,
  label,
  onClick,
}: {
  active: boolean;
  isDark: boolean;
  label: string;
  onClick: () => void;
}) {
  return (
    <ButtonBase
      onClick={onClick}
      sx={{
        px: "10px",
        py: "10px",
        mb: "-1px",
        borderBottom: active ? "2px solid #1a64a8" : "2px solid transparent",
        borderRadius: 0,
        flexShrink: 0,
      }}
    >
      <Typography
        sx={{
          color: active ? "#1a64a8" : isDark ? alpha("#ffffff", 0.55) : "#717680",
          fontSize: 12,
          fontWeight: 500,
          lineHeight: 1,
          whiteSpace: "nowrap",
        }}
      >
        {label}
      </Typography>
    </ButtonBase>
  );
}

type IssueViewDetailReportTabsProps = {
  isDark: boolean;
  tabs: IssueViewDetailReportTab[];
  defaultTabId?: string;
};

export function IssueViewDetailReportTabs({
  isDark,
  tabs,
  defaultTabId,
}: IssueViewDetailReportTabsProps) {
  const [activeTabId, setActiveTabId] = useState(
    defaultTabId ?? tabs[0]?.id ?? "",
  );

  if (tabs.length === 0) {
    return null;
  }

  const activeTab =
    tabs.find((tab) => tab.id === activeTabId) ?? tabs[0] ?? null;

  return (
    <Box sx={{ mt: 2.5 }}>
      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          flexWrap: "wrap",
          gap: 0,
          borderBottom: `1px solid ${isDark ? alpha("#ffffff", 0.08) : "#f5f5f5"}`,
        }}
      >
        {tabs.map((tab) => (
          <ReportTabButton
            key={tab.id}
            active={tab.id === activeTab?.id}
            isDark={isDark}
            label={tab.label}
            onClick={() => setActiveTabId(tab.id)}
          />
        ))}
      </Box>

      {activeTab?.content ? (
        <Box sx={{ pt: 2.5 }}>{activeTab.content}</Box>
      ) : null}
    </Box>
  );
}