"use client";

import { FC, useState } from "react";
import { Box, Grid } from "@mui/material";
import { useRouter } from "next/navigation";
import { Dialog, Button, colors, typography } from "ui";

interface DetailProps {
  title: string;
  entity: string;
  id: string;
  children: any;
  deleteAction?: Function;
}

export const Detail: FC<DetailProps> = ({
  title,
  entity,
  id,
  children,
  deleteAction,
}) => {
  const router = useRouter();
  const { almostBlack } = colors;
  const { bodyLarge } = typography;
  const [showDeleteConfirmation, setShowDeleteConfirmation] = useState(false);

  const continueDeleteAction = async () => {
    await deleteAction?.(id);
    setShowDeleteConfirmation(false);
    router.push(`/${entity}`);
  };

  return (
    <>
      <Dialog
        open
        title={title}
        onClose={() => router.push(`/${entity}`)}
        buttons={
          <Grid container justifyContent="space-between">
            <Grid item container xs="auto" spacing={2}>
              {deleteAction && (
                <Grid item>
                  <Button
                    text="Delete"
                    kind="destructive"
                    onClick={() => setShowDeleteConfirmation(true)}
                  />
                </Grid>
              )}
              <Grid item>
                <Button
                  text="Edit"
                  kind="secondary"
                  href={`/${entity}/${id}/edit`}
                />
              </Grid>
            </Grid>
            <Grid item>
              <Button text="Done" kind="primary" href={`/${entity}`} />
            </Grid>
          </Grid>
        }
      >
        {children}
      </Dialog>
      <Dialog
        open={showDeleteConfirmation}
        size="xs"
        title="Really delete?"
        buttons={
          <Grid container justifyContent="space-between">
            <Grid item>
              <Button
                text="Cancel"
                kind="secondary"
                onClick={() => setShowDeleteConfirmation(false)}
              />
            </Grid>
            <Grid item>
              <Button
                text="Delete"
                kind="destructive"
                onClick={continueDeleteAction}
              />
            </Grid>
          </Grid>
        }
      >
        <Box sx={{ ...bodyLarge, color: almostBlack }}>
          Are you sure you want to delete this record?
        </Box>
      </Dialog>
    </>
  );
};
