/**
 * Copyright (c) 2023-present Plane Software, Inc. and contributors
 * SPDX-License-Identifier: AGPL-3.0-only
 * See the LICENSE file for details.
 */

import type { MouseEvent } from "react";
import { observer } from "mobx-react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { useTranslation } from "@plane/i18n";
import { PriorityIcon } from "@plane/propel/icons";
import { Tooltip } from "@plane/propel/tooltip";
import { Avatar, Row } from "@plane/ui";
import { cn, renderFormattedDate } from "@plane/utils";
import { usePlatformOS } from "@/hooks/use-platform-os";
import { useProjectExternalContours } from "@/hooks/store/use-project-external-contours";
import { ExternalContourStatePill } from "./state-pill";

type Props = {
  workspaceSlug: string;
  projectId: string;
  requestId: string;
  setIsMobileSidebar: (value: boolean) => void;
};

export const ExternalContoursListItem = observer(function ExternalContoursListItem(props: Props) {
  const { workspaceSlug, projectId, requestId, setIsMobileSidebar } = props;
  const searchParams = useSearchParams();
  const selectedInboxIssueId = searchParams.get("inboxIssueId");
  const { t } = useTranslation();
  const { currentTab, getRequestById } = useProjectExternalContours();
  const { isMobile } = usePlatformOS();
  const request = getRequestById(requestId);
  const issue = request?.issue;

  const handleIssueRedirection = (event: MouseEvent, currentIssueId: string | undefined) => {
    if (selectedInboxIssueId === currentIssueId) event.preventDefault();
    setIsMobileSidebar(false);
  };

  if (!request || !issue) return <></>;

  const assigneeDetails = issue.assignee_details?.slice(0, 2) ?? [];
  const visibleLabels = issue.label_details?.slice(0, 3) ?? [];
  const lastUpdatedAt = issue.updated_at || request.updated_at;

  return (
    <Link
      id={`external-contour-list-item-${request.id}`}
      key={`${projectId}_${request.id}`}
      href={`/${workspaceSlug}/projects/${projectId}/external-contours?currentTab=${currentTab}&inboxIssueId=${request.id}`}
      onClick={(e) => handleIssueRedirection(e, request.id)}
    >
      <Row
        className={cn(
          "relative flex cursor-pointer flex-col gap-2 border border-t-transparent border-r-transparent border-b-subtle-1 border-l-transparent py-4 transition-all hover:bg-accent-primary/5",
          { "border border-accent-strong": selectedInboxIssueId === request.id }
        )}
      >
        <div className="space-y-1">
          <div className="relative flex items-center justify-between gap-2">
            <div className="flex items-center gap-2 text-11 font-medium text-tertiary">
              <span>
                {issue.project_detail?.identifier || "REQ"}-{issue.sequence_id}
              </span>
              {issue.project_detail?.name && <span className="truncate text-placeholder">{issue.project_detail.name}</span>}
              {request.has_unread_updates && (
                <Tooltip tooltipHeading={t("external_contours_page.list.unread_updates")} isMobile={isMobile}>
                  <span className="size-2 rounded-full bg-accent-primary" />
                </Tooltip>
              )}
            </div>
            <ExternalContourStatePill request={request} />
          </div>
          <h3 className="w-full truncate text-13">{issue.name}</h3>
        </div>

        <div className="flex items-center justify-between gap-2">
          <div className="flex flex-wrap items-center gap-2">
            <Tooltip
              tooltipHeading={t("external_contours_page.list.last_updated")}
              tooltipContent={`${renderFormattedDate(lastUpdatedAt ?? "")}`}
              isMobile={isMobile}
            >
              <div className="text-11 text-secondary">{renderFormattedDate(lastUpdatedAt ?? "")}</div>
            </Tooltip>

            {issue.priority && issue.priority !== "none" && (
              <Tooltip tooltipHeading={t("priority")} tooltipContent={`${issue.priority ?? t("none")}`}>
                <PriorityIcon priority={issue.priority} withContainer className="h-3 w-3" />
              </Tooltip>
            )}

            {visibleLabels.map((label) => (
              <div key={label.id} className="relative flex !h-[17.5px] items-center gap-1 rounded-sm border border-strong px-1 text-11">
                <span className="h-2 w-2 rounded-full" style={{ backgroundColor: label.color }} />
                <span className="max-w-28 truncate normal-case">{label.name}</span>
              </div>
            ))}
          </div>
          <div className="flex items-center gap-1">
            {assigneeDetails.length > 0 ? (
              <>
                {assigneeDetails.map((assignee) => (
                  <Avatar
                    key={assignee.id}
                    src={assignee.avatar_url || ""}
                    name={assignee.display_name || "NODE.DC"}
                    size="md"
                    showTooltip
                  />
                ))}
              </>
            ) : (
              <Tooltip tooltipHeading={t("assignee")} tooltipContent={t("external_contours_page.list.unassigned")} isMobile={isMobile}>
                <div className="text-11 text-placeholder">{t("external_contours_page.list.unassigned")}</div>
              </Tooltip>
            )}
          </div>
        </div>
      </Row>
    </Link>
  );
});
