import React from "react";

import CancelIcon from "@mui/icons-material/Cancel";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import {
  CardHeader,
  CardHeaderProps,
  FormControlLabel,
  Stack,
  Switch,
  Typography,
} from "@mui/material";

import { useI18n } from "../contexts/I18nContext";

import { Pill } from "./Card/shared";
import Chip from "./Chip";

export interface TableCardHeaderProps extends Omit<CardHeaderProps, "onChange"> {
  isEditable?: boolean;
  isDisabled?: boolean;
  onChange?: (v: boolean) => void;
  toggled?: boolean;
  pills?: Pill[];
}

export const TableCardHeader: React.FC<TableCardHeaderProps> = ({
  title,
  avatar,
  isEditable = false,
  isDisabled = false,
  onChange,
  toggled,
  pills,
  ...props
}) => {
  const { t } = useI18n();

  return (
    <CardHeader
      {...props}
      action={
        isEditable && (
          <FormControlLabel
            control={
              <Switch
                checked={Boolean(toggled)}
                disabled={isDisabled && toggled}
                onChange={(_, v) => onChange?.(v)}
              />
            }
            label={
              <Typography sx={{ color: "grey.600" }} variant="body2">
                {t("Edit")}
              </Typography>
            }
          />
        )
      }
      avatar={avatar}
      sx={{ opacity: isDisabled && toggled ? 0.5 : 1, ...props.sx }}
      title={
        <Stack direction="row" gap={1}>
          <Typography sx={{ fontWeight: 500, marginRight: 1 }} variant="body1">
            {title}
          </Typography>

          {pills?.map(({ label, color, icon }, i) => (
            <Chip
              key={i}
              color={color ?? "success"}
              icon={icon ?? (color === "success" ? <CheckCircleIcon /> : <CancelIcon />)}
              label={label}
              size="small"
            />
          ))}
        </Stack>
      }
    />
  );
};

export default TableCardHeader;
