import { gql, useQuery } from "@apollo/client";
import { Link, useRouter } from "@curi/react-dom";
import {
  List,
  ListItem,
  Typography,
  ListItemText,
  ListItemSecondaryAction,
  IconButton,
} from "@material-ui/core";
import { FC, MouseEventHandler, useMemo } from "react";
import { Pipeline, Project } from "../generated/graphql";
import { CallMerge, Edit } from "@material-ui/icons";

interface Props {
  projectId: string;
}

const PIPELINES = gql`
  query Pipelines($projectId: String!) {
    pipelines(projectId: $projectId) {
      id
      name
      branch
    }
    project(id: $projectId) {
      id
    }
  }
`;

export const PipelineList: FC<Props> = ({ projectId }) => {
  const { data } = useQuery<
    { pipelines: Pipeline[]; project: Project },
    { projectId: string }
  >(PIPELINES, {
    variables: { projectId },
  });
  const pipelines = useMemo(() => {
    return data?.pipelines?.map((pipeline) => ({
      ...pipeline,
      project: data?.project,
    }));
  }, [data]);
  return (
    <List>
      {pipelines?.map((pipeline) => (
        <Link
          name="pipeline-commits"
          params={{ pipelineId: pipeline.id, projectId: projectId }}
          key={pipeline.id}
        >
          <Item pipeline={pipeline} />
        </Link>
      ))}
    </List>
  );
};

const Item = ({ pipeline }: { pipeline: Pipeline }) => {
  const { navigate, url } = useRouter();
  const modify: MouseEventHandler = (ev) => {
    ev.preventDefault();
    navigate({
      url: url({
        name: "edit-pipeline",
        params: { pipelineId: pipeline.id, projectId: pipeline.project.id },
      }),
    });
  };
  return (
    <ListItem button>
      <ListItemText
        primary={pipeline.name}
        secondary={
          <Typography component="span" variant="body2" color="textSecondary">
            <CallMerge fontSize="small" />
            {pipeline.branch}
          </Typography>
        }
      />
      <ListItemSecondaryAction>
        <IconButton edge="end" aria-label="edit" onClick={modify}>
          <Edit />
        </IconButton>
      </ListItemSecondaryAction>
    </ListItem>
  );
};
