import { useEffect, useState } from 'react';

import { Box, Button, Link, TextField, Typography } from '@mui/material';
import OpenInNewIcon from '@mui/icons-material/OpenInNew';
import { makeStyles } from 'tss-react/mui';

import { blue } from '../../../themes/common';
import Dialog from '../../common/Dialog';

interface Props {
  addedVersion?: string;
  latestVersion?: string;
  moduleName: string;
  onClose: () => void;
  onConfirm: (gitMessage: string) => void;
  open: boolean;
}

const useStyles = makeStyles()(theme => ({
  row: {
    marginTop: 24,
    '&:first-of-type': { marginTop: 0 }
  },
  value: { display: 'block', marginTop: 4 },
  link: {
    paddingLeft: 12,
    // Beat the global `html.dark body * { color }` so the link keeps its blue.
    ...(theme.palette.mode === 'dark' && { '&&, && *': { color: blue[300] } })
  }
}));

export const UpdateModuleDialog = ({ addedVersion, latestVersion, moduleName, onClose, onConfirm, open }: Props) => {
  const { classes } = useStyles();
  const [commitMessage, setCommitMessage] = useState('');

  useEffect(() => {
    if (open) setCommitMessage(`Updated ${moduleName} from ${addedVersion} to ${latestVersion}`);
  }, [open, moduleName, addedVersion, latestVersion]);

  return (
    <Dialog
      open={open}
      onClose={onClose}
      title="Update Module"
      size="sm"
      fullWidth
      actionButtons={
        <>
          <Button onClick={onClose} variant="outlined" color="inherit">
            Cancel
          </Button>
          <Button onClick={() => onConfirm(commitMessage)} variant="contained" color="secondary">
            Update
          </Button>
        </>
      }
    >
      <Box className={classes.row}>
        <Typography variant="h6">Current version</Typography>
        <Typography variant="subtitle1" className={classes.value}>
          {addedVersion}
        </Typography>
      </Box>
      <Box className={classes.row}>
        <Typography variant="h6">Latest version available</Typography>
        <Box className={classes.value}>
          <Typography component="span" variant="subtitle1">
            {latestVersion}
          </Typography>
          <Link
            className={classes.link}
            variant="subtitle1"
            underline="always"
            href={`https://build.cfengine.com/modules/${moduleName}/`}
            target="_blank"
            rel="noopener"
          >
            View project website <OpenInNewIcon fontSize="inherit" />
          </Link>
        </Box>
      </Box>
      <Box className={classes.row}>
        <Typography variant="h6" component="label" htmlFor="commitMessage">
          Comment (commit message)
        </Typography>
        <TextField
          id="commitMessage"
          className={classes.value}
          variant="outlined"
          size="small"
          fullWidth
          value={commitMessage}
          onChange={e => setCommitMessage(e.target.value)}
        />
      </Box>
    </Dialog>
  );
};
