/**
 * 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";
// plane imports
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, getFileURL } from "@plane/utils";
// components
import { ButtonAvatars } from "@/components/dropdowns/member/avatar";
import { NodedcWorkItemCard, getNodedcWorkItemCardAppearance } from "@/components/issues/issue-layouts/shared/nodedc-work-item-card";
// hooks
import { useLabel } from "@/hooks/store/use-label";
import { useMember } from "@/hooks/store/use-member";
import { useProjectInbox } from "@/hooks/store/use-project-inbox";
import { usePlatformOS } from "@/hooks/use-platform-os";
// plane web imports
// local imports
import { InboxIssueStatus } from "../inbox-issue-status";

type InboxIssueListItemProps = {
  workspaceSlug: string;
  projectId: string;
  projectIdentifier?: string;
  inboxIssueId: string;
  setIsMobileSidebar: (value: boolean) => void;
};

export const InboxIssueListItem = observer(function InboxIssueListItem(props: InboxIssueListItemProps) {
  const { workspaceSlug, projectId, inboxIssueId, projectIdentifier, setIsMobileSidebar } = props;
  // router
  const searchParams = useSearchParams();
  const selectedInboxIssueId = searchParams.get("inboxIssueId");
  const { t } = useTranslation();
  // store
  const { getIssueInboxByIssueId } = useProjectInbox();
  const { projectLabels } = useLabel();
  const { isMobile } = usePlatformOS();
  const { getUserDetails } = useMember();
  const inboxIssue = getIssueInboxByIssueId(inboxIssueId);
  const issue = inboxIssue?.issue;

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

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

  const createdByDetails = issue?.created_by ? getUserDetails(issue?.created_by) : undefined;
  const isActive = selectedInboxIssueId === issue.id;
  const { pillBackgroundClasses, subtleTextClasses } = getNodedcWorkItemCardAppearance(isActive);
  const visibleLabels = (issue.label_ids ?? [])
    .map((labelId) => projectLabels?.find((label) => label.id === labelId))
    .filter((label) => !!label)
    .slice(0, 2);
  const extraLabelCount = Math.max((issue.label_ids ?? []).length - visibleLabels.length, 0);

  return (
    <Link
      id={`inbox-issue-list-item-${issue.id}`}
      key={`${projectId}_${issue.id}`}
      className="block"
      href={`/${workspaceSlug}/projects/${projectId}/intake?inboxIssueId=${issue.id}`}
      onClick={(e) => handleIssueRedirection(e, issue.id)}
    >
      <NodedcWorkItemCard
        isActive={isActive}
        surfaceClassName="transition-transform duration-200 hover:-translate-y-0.5"
        header={
          <div className="flex items-start justify-between gap-3">
            <div className="flex min-w-0 flex-1 items-center gap-3">
              {createdByDetails && createdByDetails.email?.includes("intake@plane.so") ? (
                <Avatar src={getFileURL("")} name={"NODE.DC"} size="md" showTooltip />
              ) : createdByDetails ? (
                <ButtonAvatars showTooltip={false} userIds={createdByDetails?.id} />
              ) : null}
              <div className="min-w-0">
                <div className="truncate text-body-sm-medium leading-5">
                  {createdByDetails?.display_name ?? "NODE.DC"}
                </div>
              </div>
            </div>

            {inboxIssue.status !== -2 && <InboxIssueStatus inboxIssue={inboxIssue} iconSize={12} />}
          </div>
        }
        subtitle={
          <span className={cn("truncate", subtleTextClasses)}>
            {projectIdentifier}-{issue.sequence_id}
          </span>
        }
        title={issue.name}
        titleClassName="line-clamp-3 text-left text-[1.05rem]"
        titleContainerClassName="items-start justify-start px-0 py-5 text-left"
        footerClassName="items-end"
        footer={
          <>
            <div className="flex min-w-0 flex-wrap items-center gap-2">
              <Tooltip
                tooltipHeading={t("created_at")}
                tooltipContent={`${renderFormattedDate(issue.created_at ?? "")}`}
                isMobile={isMobile}
              >
                <div className={cn("rounded-full px-3 py-1.5 text-12", pillBackgroundClasses)}>
                  {renderFormattedDate(issue.created_at ?? "")}
                </div>
              </Tooltip>

              {visibleLabels.map((labelDetails) => {
                if (!labelDetails) return null;
                return (
                  <div key={labelDetails.id} className={cn("inline-flex items-center gap-2 rounded-full px-3 py-1 text-11 font-medium", pillBackgroundClasses)}>
                    <span className="h-2 w-2 rounded-full" style={{ backgroundColor: labelDetails.color }} />
                    <span className="truncate">{labelDetails.name}</span>
                  </div>
                );
              })}

              {extraLabelCount > 0 && (
                <div className={cn("inline-flex items-center rounded-full px-3 py-1 text-11 font-medium", pillBackgroundClasses)}>
                  +{extraLabelCount}
                </div>
              )}
            </div>

            <div className="flex shrink-0 items-center gap-2">
              {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>
          </>
        }
      />
    </Link>
  );
});
