/**
 * 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 } 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 lastUpdatedAt = issue.updated_at || request.updated_at;
  const requester = issue.created_by_detail;
  const requesterName =
    request.requested_by_name || requester?.display_name || t("external_contours_page.mirror.system_actor");
  const contourName = request.target_project_name || issue.project_detail?.name || t("common.none");

  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)}
    >
      <div
        data-active={selectedInboxIssueId === request.id}
        className={cn(
          "nodedc-external-card relative flex min-h-[15rem] cursor-pointer flex-col gap-5 px-6 py-5 transition-all hover:bg-white/5",
          { "ring-0": selectedInboxIssueId === request.id }
        )}
      >
        <div className="space-y-0.5">
          <div className="flex items-center justify-between gap-3">
            <div className="flex min-w-0 flex-1 items-center gap-3">
              <Avatar
                src={requester?.avatar_url || ""}
                name={requesterName}
                size="md"
                showTooltip
              />
              <div className="min-w-0">
                <div className="truncate text-[15px] leading-5 font-semibold text-primary">{requesterName}</div>
              </div>
            </div>

            <div className="flex shrink-0 items-center gap-2">
              <div className="text-11 font-medium text-tertiary">
                {issue.project_detail?.identifier || "REQ"}-{issue.sequence_id}
              </div>
              <div className="flex items-center gap-2">
                {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>
                )}
                <ExternalContourStatePill request={request} />
              </div>
            </div>
          </div>

          <div className="truncate pl-10 text-[12px] font-medium leading-4 text-secondary">{contourName}</div>
        </div>

        <div className="flex flex-1 items-center justify-center px-5 py-2 text-center">
          <h3 className="line-clamp-3 w-full max-w-[18.5rem] text-center text-16 leading-7 font-semibold text-primary">
            {issue.name}
          </h3>
        </div>

        <div className="flex items-center justify-between gap-3">
          <div className="flex min-w-0 items-center gap-2">
            {assigneeDetails.length > 0 ? (
              assigneeDetails.map((assignee, index) => (
                <div key={assignee.id} className={cn(index > 0 && "-ml-2")}>
                  <Avatar
                    src={assignee.avatar_url || ""}
                    name={assignee.display_name || "NODE.DC"}
                    size="md"
                    showTooltip
                  />
                </div>
              ))
            ) : (
              <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 className="flex flex-wrap items-center justify-end gap-2">
            <Tooltip
              tooltipHeading={t("external_contours_page.list.last_updated")}
              tooltipContent={`${renderFormattedDate(lastUpdatedAt ?? "")}`}
              isMobile={isMobile}
            >
              <div className="rounded-full bg-white/6 px-3 py-1.5 text-12 text-secondary">
                {renderFormattedDate(lastUpdatedAt ?? "")}
              </div>
            </Tooltip>

            {issue.priority && issue.priority !== "none" && (
              <Tooltip tooltipHeading={t("priority")} tooltipContent={`${issue.priority ?? t("none")}`}>
                <div className="nodedc-external-priority-inline flex items-center justify-center">
                  <PriorityIcon priority={issue.priority} className="h-3.5 w-3.5" />
                </div>
              </Tooltip>
            )}
          </div>
        </div>
      </div>
    </Link>
  );
});
