import { Box, CircularProgress, IconButton } from "@mui/material";
import { CraftTableOptionsProps } from "../../types/table-options";
import { settingsOptionsProps } from "../../types/table";
import { useMemo } from "react";
import { TableTab, TableTabCount, TableTabsRoot } from "./tabs.styles";
import { SettingsOutlined } from "@mui/icons-material";

interface TabDataProps {
  tab_name: string | null;
  count?: string | number;
}

interface TableTabsProps {
  loading?: boolean;
  tabsData?: TabDataProps[];
  activeTab?: TabDataProps;
  tableStates: CraftTableOptionsProps;
  onClick: (state: string) => void;
  settingsOptions?: settingsOptionsProps;
}

export function TableTabs({
  loading = false,
  tabsData = [],
  activeTab = { tab_name: "All", count: 0 },
  onClick,
  tableStates,
  settingsOptions,
}: TableTabsProps) {
  if (loading) return <CircularProgress size={24} />;

  const handleTabClick = (tab: string) => {
    onClick(tab);
    tableStates.setPagination((prev) => ({
      ...prev,
      pageIndex: 0,
    }));
  };

  const normalizedTabs = useMemo(() => {
    return tabsData
      ?.filter((tab) => tab.tab_name !== null)
      ?.map((tab) => ({
        ...tab,
        tab_name: tab.tab_name,
      }));
  }, [tabsData]);

  const defaultTab = useMemo(() => {
    return (
      normalizedTabs.find((t) => t.tab_name === "All")?.tab_name ||
      normalizedTabs[0]?.tab_name ||
      ""
    );
  }, [normalizedTabs]);

  const selectedTab = activeTab?.tab_name || defaultTab;

  return (
    <Box display="flex" alignItems="center" justifyContent="flex-start">
      {/* Settings icon */}
      {settingsOptions?.showIcon && (
        <IconButton size="small" onClick={settingsOptions?.onClick}>
          <SettingsOutlined fontSize="small" />
        </IconButton>
      )}

      {/* Tabs */}
      <TableTabsRoot
        value={selectedTab}
        onChange={(_, newValue) => handleTabClick(newValue)}
        variant="scrollable"
        scrollButtons="auto"
      >
        {normalizedTabs.map((tab) => {
          const isSelected = activeTab?.tab_name === tab?.tab_name;

          return (
            <TableTab
              key={tab?.tab_name}
              value={tab}
              label={
                <Box display="flex" alignItems="center" gap={1}>
                  <Box sx={{ color: isSelected ? "#000" : "" }}>
                    {tab?.tab_name}
                  </Box>
                  <TableTabCount selected={isSelected}>
                    {tab?.count == 0
                      ? "0"
                      : String(tab?.count).padStart(2, "0")}
                  </TableTabCount>
                </Box>
              }
            />
          );
        })}
      </TableTabsRoot>
    </Box>
  );
}
