import React, { useCallback, useMemo } from "react";

import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp";
import { FormControlLabel } from "@mui/material";
import MuiCardHeader, { CardHeaderProps as MuiCardHeaderProps } from "@mui/material/CardHeader";
import IconButton from "@mui/material/IconButton";
import Stack from "@mui/material/Stack";
import Switch from "@mui/material/Switch";
import Typography from "@mui/material/Typography";

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

export interface CardHeaderProps extends MuiCardHeaderProps {
  title: string;
}

export const CardHeader: React.FC<CardHeaderProps> = ({ title, children, ...props }) => {
  const {
    alwaysEditable,
    isCompact,
    isEditing,
    isEditable,
    isDisabled,
    setIsEditing,
    isCollapsible,
    isOpen,
    setIsOpen,
  } = useCardContext();
  const { t } = useI18n();

  // TODO Implement dialog for cancel when changed values
  // const openDialog = useDialog();
  const handleEdit = useCallback(() => {
    setIsEditing((isEditing) => !isEditing);
  }, [setIsEditing]);

  const handleCollapse = useCallback(() => {
    setIsOpen((isOpen) => !isOpen);
  }, [setIsOpen]);

  const showToggle = useMemo(
    () => Boolean(isEditable && !alwaysEditable),
    [isEditable, isCollapsible],
  );

  return (
    <MuiCardHeader
      {...props}
      action={
        <Stack direction="row">
          {showToggle && (
            <FormControlLabel
              control={<Switch checked={isEditing} disabled={isDisabled} onChange={handleEdit} />}
              label={
                <Typography color="grey.600" variant="body2">
                  {t("Edit")}
                </Typography>
              }
            />
          )}

          {isCollapsible && (
            <IconButton size="small" onClick={handleCollapse}>
              {isOpen ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
            </IconButton>
          )}
        </Stack>
      }
      component="header"
      sx={{
        px: isCompact ? 2 : 3,
        pt: 2,
        pb: isCompact ? 1 : 2,
        ...props.sx,
      }}
      title={
        <Stack
          alignItems={isCompact ? "flex-start" : "center"}
          direction={isCompact ? "column" : "row"}
          gap={1}
        >
          <Typography fontWeight="500" variant="body1">
            {title}
          </Typography>

          {children}
        </Stack>
      }
    />
  );
};

export default CardHeader;
