import { Box, Button, Card, Chip, Stack, Table, Typography } from "@mui/joy";
import { Layers3, PenSquare, Plus } from "lucide-react";
import { useNavigate } from "react-router";

import { formatNumber } from "./number-format";
import type { ProjectSummary } from "./types";

export type ProjectsListCardProps = {
  projects: ProjectSummary[];
  onCreateProject: () => void;
};

export function ProjectsListCard({
  projects,
  onCreateProject,
}: ProjectsListCardProps) {
  const hasProjects = projects.length > 0;
  const navigate = useNavigate();

  const handleOpenProject = (projectId: string) => {
    navigate(`/projects/${projectId}`);
  };

  const handleEditProject = (projectId: string) => {
    navigate(`/projects/${projectId}`);
  };

  return (
    <Card variant="outlined" sx={{ height: "100%", p: 0 }}>
      <Stack
        direction="row"
        alignItems="center"
        justifyContent="space-between"
        sx={{
          px: 2.5,
          py: 2,
          borderBottom: "1px solid",
          borderColor: "divider",
        }}
      >
        <Stack direction="row" alignItems="center" gap={1.25}>
          <Layers3 size={18} />
          <Box>
            <Typography level="title-sm" fontWeight={600}>
              Projects
            </Typography>
            <Typography level="body-xs" textColor="neutral.500">
              Overview of your deployed workloads
            </Typography>
          </Box>
        </Stack>
        <Stack direction="row" gap={1} alignItems="center">
          <Chip size="sm" variant="soft">
            {projects.length} total
          </Chip>
          <Button
            size="sm"
            startDecorator={<Plus size={16} />}
            onClick={onCreateProject}
          >
            New project
          </Button>
        </Stack>
      </Stack>

      {hasProjects ? (
        <Table
          size="sm"
          stickyHeader
          sx={{
            "--TableCell-headBackground": "transparent",
            "--TableCell-paddingX": "16px",
            "--TableCell-paddingY": "12px",
          }}
        >
          <thead>
            <tr>
              <th style={{ width: "35%" }}>Name</th>
              <th>Functions</th>
              <th>Invocations</th>
              <th>Errors</th>
              <th>CPU usage</th>
              <th style={{ width: "12%" }}></th>
            </tr>
          </thead>
          <tbody>
            {projects.map((project) => {
              const functionsCount = project.functions?.length ?? 0;
              const invocations = project.functionsInvocationCount ?? 0;
              const errors = project.functionsErrorCount ?? 0;
              const quota = project.cpuTimeQuotaMsPerMinute ?? 0;
              const used = project.cpuTimeUsedMs ?? 0;
              const cpuPercent = quota
                ? Math.min(100, (used / quota) * 100)
                : 0;

              return (
                <tr
                  key={project._id}
                  onClick={() => handleOpenProject(project._id)}
                  onKeyDown={(event) => {
                    if (event.key === "Enter" || event.key === " ") {
                      event.preventDefault();
                      handleOpenProject(project._id);
                    }
                  }}
                  tabIndex={0}
                  style={{ cursor: "pointer" }}
                  role="button"
                >
                  <td>
                    <Stack>
                      <Typography level="body-sm" fontWeight={600}>
                        {project.name}
                      </Typography>
                      <Chip size="sm" variant="soft" color="neutral">
                        {project.slug}
                      </Chip>
                    </Stack>
                  </td>
                  <td>
                    <Typography level="body-sm" fontWeight={500}>
                      {formatNumber(functionsCount)}
                    </Typography>
                  </td>
                  <td>
                    <Typography level="body-sm" fontWeight={500}>
                      {formatNumber(invocations)}
                    </Typography>
                  </td>
                  <td>
                    <Typography
                      level="body-sm"
                      fontWeight={500}
                      color={errors ? "danger" : undefined}
                    >
                      {formatNumber(errors)}
                    </Typography>
                  </td>
                  <td>
                    <Typography level="body-sm" fontWeight={500}>
                      {cpuPercent.toFixed(1)}%
                    </Typography>
                  </td>
                  <td>
                    <Stack direction="row" gap={1} justifyContent="flex-end">
                      <Button
                        size="sm"
                        variant="outlined"
                        startDecorator={<PenSquare size={14} />}
                        onClick={(event) => {
                          event.stopPropagation();
                          handleEditProject(project._id);
                        }}
                      >
                        Edit
                      </Button>
                    </Stack>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </Table>
      ) : (
        <Stack
          alignItems="center"
          justifyContent="center"
          sx={{ py: 6, px: 2 }}
          gap={0.75}
        >
          <Typography level="title-sm">No projects yet</Typography>
          <Typography
            level="body-sm"
            textColor="neutral.500"
            textAlign="center"
          >
            Spin up your first project to start deploying functions.
          </Typography>
          <Button
            size="sm"
            startDecorator={<Plus size={16} />}
            onClick={onCreateProject}
          >
            Create project
          </Button>
        </Stack>
      )}
    </Card>
  );
}
