"use client";

import { useRef, useState } from "react";
import Image from "next/image";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { Modal } from "@/components/ui/Modal";
import { Button } from "@/components/ui/Button";
import { useAuthStore } from "@/store/authStore";
import type { CommunityPostRecord } from "@/features/community/communityRecord";
import Contactus from "./Contactus";
import { canContactPostAuthor } from "@/features/community/communityContact";

/**
 * «للتواصل» on an idea post (PDF p.26): opens a message box that reaches the
 * author through `POST /posts/{id}/contact-creator/`. Shared by the post card
 * and the post page so both offer it with the same rules.
 */
export default function ContactAuthorButton({
  post,
  tone = "purple",
}: {
  post: Pick<CommunityPostRecord, "id" | "proposing_idea" | "is_creator" | "user">;
  tone?: "purple" | "orange";
}) {
  const { t } = useTranslation();
  const user = useAuthStore((s) => s.user);
  const [open, setOpen] = useState(false);
  const [isSending, setIsSending] = useState(false);
  const formRef = useRef<HTMLFormElement | null>(null);

  if (!canContactPostAuthor(post, user?.id)) return null;

  return (
    <>
      <button
        type="button"
        className={`flex gap-2 smallscreen:gap-[4px] smallscreen:text-xs cursor-pointer text-sm font-bold items-center ${
          tone === "purple" ? "text-primary-5" : "text-[#FC9555]"
        }`}
        onClick={(e) => {
          e.preventDefault();
          e.stopPropagation();
          if (!user?.auth_token) {
            toast.info(t("COMMON.LOGIN_TO_CONTACT"));
            return;
          }
          setOpen(true);
        }}
      >
        <span className="relative w-[18px] h-[18px]">
          <Image
            src={tone === "purple" ? "/assets/community/contactus.svg" : "/assets/community/orangecontact_icn.svg"}
            alt=""
            fill
            className="object-contain"
            unoptimized
          />
        </span>
        {t("COMMON.CONTACT_IDEA_AUTHOR")}
      </button>
      <Modal
        open={open}
        onClose={() => !isSending && setOpen(false)}
        title={t("COMMON.CONTACT_IDEA_AUTHOR")}
        size="md"
        footer={
          <div className="flex xss:flex-col justify-center w-full gap-5">
            <Button
              variant="primary"
              size="medium"
              className="xss:!w-full"
              // This dialog's own form — not the first <form> in the document.
              onClick={() => formRef.current?.requestSubmit()}
              disabled={isSending}
              loading={isSending}
            >
              {t("COMMON.SEND")}
            </Button>
          </div>
        }
      >
        <Contactus
          postId={post.id}
          formRef={formRef}
          onLoadingChange={setIsSending}
          afterReplyCreation={() => setOpen(false)}
        />
      </Modal>
    </>
  );
}
