import { gql, useQuery } from "@apollo/client";
import { Link } from "@curi/react-dom";
import { Box, List, ListItem, makeStyles, Theme } from "@material-ui/core";
import { FC } from "react";
import { Project } from "../generated/graphql";
import { ListItemText } from "@material-ui/core";
import { Button } from "@material-ui/core";
import { AddBox } from "@material-ui/icons";
import { ActiveLink } from "../commons/route/active-link";

const PROJECTS = gql`
  query Projects {
    projects {
      id
      name
      comment
      sshUrl
      webUrl
      webHookSecret
    }
  }
`;

const useStyles = makeStyles((theme: Theme) => ({
  item: {
    position: "relative",
    ".active &": {
      backgroundColor: theme.palette.background.default,
    },
    ".active &::before": {
      position: "absolute",
      top: 0,
      bottom: 0,
      left: 0,
      content: '""',
      display: "block",
      borderLeftColor: theme.palette.secondary.main,
      borderLeftWidth: 4,
      borderLeftStyle: "solid",
    },
  },
}));

export function ProjectPanel() {
  return (
    <section>
      <Box m={2}>
        <Link name="create-project">
          <Button
            variant="contained"
            color="primary"
            title="New Project"
            startIcon={<AddBox />}
          >
            New Project
          </Button>
        </Link>
      </Box>
      <ProjectList />
    </section>
  );
}

const ProjectList: FC<{}> = () => {
  const { data } = useQuery<{
    projects: Project[];
  }>(PROJECTS);
  const projects = data?.projects;

  const classes = useStyles();

  const items = projects?.map((item) => (
    <ActiveLink
      name="project-detail"
      params={{ projectId: item.id }}
      key={item.id}
    >
      <ListItem button className={classes.item}>
        <ListItemText primary={item.name} secondary={item.comment} />
      </ListItem>
    </ActiveLink>
  ));
  return <List>{items}</List>;
};
