"use client";

import { FC } from "react";
import {
  Box,
  Dialog as InternalDialog,
  DialogActions,
  DialogContent,
  DialogTitle,
} from "@mui/material";
import { typography, colors } from "../styles/theme";

type DialogDetailsProps = {
  title: string;
  children: React.ReactNode;
  buttons?: React.ReactNode;
};

const DialogDetails: FC<DialogDetailsProps> = ({
  title,
  children,
  buttons,
}) => {
  const { h4 } = typography;
  const { lightGray, mediumGray, darkMediumGray, white, almostBlack } = colors;

  return (
    <>
      <DialogTitle
        sx={{
          backgroundColor: mediumGray,
          borderBottom: `1px solid ${darkMediumGray}`,
          px: 3,
          py: 2,
        }}
      >
        <Box
          sx={{
            ...h4,
            color: almostBlack,
          }}
        >
          {title}
        </Box>
      </DialogTitle>
      <DialogContent
        sx={{
          backgroundColor: lightGray,
          p: 3,
          borderTop: `1px solid ${white}`,
          borderBottom: `1px solid ${darkMediumGray}`,
        }}
      >
        <Box sx={{ color: "white", py: 3 }}>{children}</Box>
      </DialogContent>
      {buttons && (
        <DialogActions sx={{ backgroundColor: mediumGray, p: 0 }}>
          <Box
            sx={{
              p: 2,
              borderTop: `1px solid ${white}`,
              width: "100%",
            }}
          >
            {buttons}
          </Box>
        </DialogActions>
      )}
    </>
  );
};

type DialogProps = {
  title: string;
  open: boolean;
  onClose?: Function;
  size?: "xs" | "sm" | "md" | "lg" | "xl";
  formAction?: any;
  buttons?: React.ReactNode;
  children?: any;
};

export const Dialog: FC<DialogProps> = ({
  title,
  open,
  size = "md",
  onClose,
  formAction,
  buttons,
  children,
}) => {
  return (
    <InternalDialog
      open={open}
      onClose={onClose as any}
      fullWidth
      maxWidth={size}
    >
      {formAction ? (
        <form action={formAction}>
          <DialogDetails title={title} buttons={buttons}>
            {children}
          </DialogDetails>
        </form>
      ) : (
        <DialogDetails title={title} buttons={buttons}>
          {children}
        </DialogDetails>
      )}
    </InternalDialog>
  );
};
