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

import { observer } from "mobx-react";
import { useTranslation } from "@plane/i18n";
import {
  DuplicatePropertyIcon,
  DueDatePropertyIcon,
  LabelPropertyIcon,
  MembersPropertyIcon,
  PriorityPropertyIcon,
  StatePropertyIcon,
} from "@plane/propel/icons";
import type { TInboxDuplicateIssueDetails, TIssue } from "@plane/types";
import { ControlLink } from "@plane/ui";
import { cn, generateWorkItemLink, getDate, renderFormattedPayloadDate } from "@plane/utils";
import { SidebarPropertyListItem } from "@/components/common/layout/sidebar/property-list-item";
import { DateDropdown } from "@/components/dropdowns/date";
import { IntakeStateDropdown } from "@/components/dropdowns/intake-state/dropdown";
import { MemberDropdown } from "@/components/dropdowns/member/dropdown";
import { PriorityDropdown } from "@/components/dropdowns/priority";
import { StateDropdown } from "@/components/dropdowns/state/dropdown";
import { IssueLabelSelect } from "@/components/issues/select";
import type { TIssueOperations } from "@/components/issues/issue-detail";
import { useLabel } from "@/hooks/store/use-label";
import { useProject } from "@/hooks/store/use-project";
import { useAppRouter } from "@/hooks/use-app-router";

type Props = {
  workspaceSlug: string;
  projectId: string;
  issue: Partial<TIssue>;
  issueOperations: TIssueOperations;
  isEditable: boolean;
  duplicateIssueDetails: TInboxDuplicateIssueDetails | undefined;
  isIntakeAccepted: boolean;
};

const CONTROL_CONTAINER_CLASS_NAME = "w-full text-left h-7.5";
const CONTROL_CLASS_NAME = "text-body-xs-medium";

export const InboxIssueContentProperties = observer(function InboxIssueContentProperties(props: Props) {
  const { workspaceSlug, projectId, issue, issueOperations, isEditable, duplicateIssueDetails, isIntakeAccepted } =
    props;

  const router = useAppRouter();
  const { t } = useTranslation();
  const { currentProjectDetails } = useProject();
  const { getLabelById } = useLabel();

  const minDate = issue.start_date ? getDate(issue.start_date) : null;
  minDate?.setDate(minDate.getDate());

  if (!issue || !issue.id) return <></>;

  const selectedAssigneeIds = issue.assignee_ids ?? [];
  const selectedLabelsCount = issue.label_ids?.length ?? 0;
  const singleLabelDetails =
    selectedLabelsCount === 1 && issue.label_ids?.[0] ? getLabelById(issue.label_ids[0]) : undefined;
  const duplicateWorkItemLink = generateWorkItemLink({
    workspaceSlug: workspaceSlug?.toString(),
    projectId,
    issueId: duplicateIssueDetails?.id,
    projectIdentifier: currentProjectDetails?.identifier,
    sequenceId: duplicateIssueDetails?.sequence_id,
  });

  return (
    <div>
      <h6 className="text-body-xs-medium">{t("common.properties")}</h6>
      <div className={cn("mt-3 w-full space-y-3", !isEditable && "opacity-60")}>
        <SidebarPropertyListItem icon={StatePropertyIcon} label={t("common.state")}>
          {isIntakeAccepted ? (
            <StateDropdown
              value={issue.state_id}
              onChange={(val) => issue.id && issueOperations.update(workspaceSlug, projectId, issue.id, { state_id: val })}
              projectId={projectId}
              disabled={!isEditable}
              buttonVariant="transparent-with-text"
              className="group w-full grow"
              buttonContainerClassName={CONTROL_CONTAINER_CLASS_NAME}
              buttonClassName={cn(CONTROL_CLASS_NAME, !issue.state_id && "text-placeholder")}
              dropdownArrow
              dropdownArrowClassName="hidden h-3.5 w-3.5 group-hover:inline"
            />
          ) : (
            <IntakeStateDropdown
              value={issue.state_id}
              onChange={(val) => issue.id && issueOperations.update(workspaceSlug, projectId, issue.id, { state_id: val })}
              projectId={projectId}
              disabled={!isEditable}
              buttonVariant="transparent-with-text"
              className="group w-full grow"
              buttonContainerClassName={CONTROL_CONTAINER_CLASS_NAME}
              buttonClassName={cn(CONTROL_CLASS_NAME, !issue.state_id && "text-placeholder")}
              dropdownArrow
              dropdownArrowClassName="hidden h-3.5 w-3.5 group-hover:inline"
            />
          )}
        </SidebarPropertyListItem>

        <SidebarPropertyListItem icon={MembersPropertyIcon} label={t("common.assignees")}>
          <MemberDropdown
            value={selectedAssigneeIds}
            onChange={(val) =>
              issue.id && issueOperations.update(workspaceSlug, projectId, issue.id, { assignee_ids: val })
            }
            disabled={!isEditable}
            projectId={projectId?.toString() ?? ""}
            multiple
            buttonVariant={selectedAssigneeIds.length > 1 ? "transparent-without-text" : "transparent-with-text"}
            className="group w-full grow"
            buttonContainerClassName={CONTROL_CONTAINER_CLASS_NAME}
            buttonClassName={cn(
              "justify-between text-body-xs-medium",
              selectedAssigneeIds.length === 0 && "text-placeholder"
            )}
            hideIcon={selectedAssigneeIds.length === 0}
            dropdownArrow
            dropdownArrowClassName="hidden h-3.5 w-3.5 group-hover:inline"
            placeholder={t("issue.add.assignee")}
          />
        </SidebarPropertyListItem>

        <SidebarPropertyListItem icon={PriorityPropertyIcon} label={t("common.priority")}>
          <PriorityDropdown
            value={issue.priority}
            onChange={(val) => issue.id && issueOperations.update(workspaceSlug, projectId, issue.id, { priority: val })}
            disabled={!isEditable}
            buttonVariant="transparent-with-text"
            className="w-full grow rounded-sm"
            buttonContainerClassName={CONTROL_CONTAINER_CLASS_NAME}
            buttonClassName={cn(
              "whitespace-nowrap text-body-xs-medium [&_svg]:size-3.5",
              (!issue.priority || issue.priority === "none") && "text-placeholder"
            )}
          />
        </SidebarPropertyListItem>

        <SidebarPropertyListItem icon={DueDatePropertyIcon} label={t("common.order_by.due_date")}>
          <DateDropdown
            placeholder={t("issues.properties.add_due_date")}
            value={issue.target_date || null}
            onChange={(val) =>
              issue.id &&
              issueOperations.update(workspaceSlug, projectId, issue.id, {
                target_date: val ? renderFormattedPayloadDate(val) : null,
              })
            }
            minDate={minDate ?? undefined}
            disabled={!isEditable}
            buttonVariant="transparent-with-text"
            className="group w-full grow"
            buttonContainerClassName={CONTROL_CONTAINER_CLASS_NAME}
            buttonClassName={cn(CONTROL_CLASS_NAME, !issue.target_date && "text-placeholder")}
            hideIcon
            clearIconClassName="hidden h-3 w-3 group-hover:inline text-primary"
          />
        </SidebarPropertyListItem>

        <SidebarPropertyListItem icon={LabelPropertyIcon} label={t("common.labels")}>
          <IssueLabelSelect
            value={issue.label_ids || []}
            onChange={(labelIds) => issue.id && issueOperations.update(workspaceSlug, projectId, issue.id, { label_ids: labelIds })}
            projectId={projectId}
            disabled={!isEditable}
            placement="top-start"
            rootClassName="w-full grow overflow-visible"
            buttonContainerClassName="w-full text-left h-7.5 rounded-full border-0 bg-transparent shadow-none outline-none"
            label={
              <div className="flex min-h-7.5 w-full items-center gap-2 rounded-full px-2 py-1 text-body-xs-medium">
                <LabelPropertyIcon className="h-3.5 w-3.5 flex-shrink-0 text-tertiary" />
                <span className={selectedLabelsCount > 0 ? "truncate text-primary" : "truncate text-placeholder"}>
                  {selectedLabelsCount > 0
                    ? selectedLabelsCount === 1
                      ? singleLabelDetails?.name ?? t("common.labels")
                      : `${selectedLabelsCount} ${t("common.labels").toLocaleLowerCase()}`
                    : t("common.labels")}
                </span>
              </div>
            }
          />
        </SidebarPropertyListItem>

        {duplicateIssueDetails && (
          <SidebarPropertyListItem icon={DuplicatePropertyIcon} label={t("issues.properties.duplicate_of")}>
            <ControlLink
              href={duplicateWorkItemLink}
              onClick={() => {
                router.push(duplicateWorkItemLink);
              }}
              target="_self"
              className="flex min-h-7.5 items-center rounded-full px-2 py-1 text-body-xs-medium"
            >
              {`${currentProjectDetails?.identifier}-${duplicateIssueDetails.sequence_id}`}
            </ControlLink>
          </SidebarPropertyListItem>
        )}
      </div>
    </div>
  );
});
