"use client";

import React, { useEffect, useState } from "react";
import Modal from "@/components/elements/Modal";
import RoundedButton from "@/components/elements/RoundedButton";
import BoldIcon from "@/components/ui/BoldIcon";
import { FiMoreHorizontal } from "react-icons/fi";
import { Post } from "@/types/types";
import useAxios from "@/hooks/useAxios";
import toast from "react-hot-toast";
import ReelsPostAnalyticsModal from "./ReelsPostAnalyticsModal";
import { useTranslation } from "react-i18next";
import { useAppLanguage } from "@/contexts/LanguageProvider";
import { useQueryClient } from "@tanstack/react-query";
import { useRouter } from "next/navigation";

const REPORT_REASON_IDS = [
  "inappropriate",
  "spam",
  "fraud",
  "harassment",
  "other",
] as const;

type Props = {
  postData: Post;
  isOwnPost: boolean;
  viewCount?: number;
  variant?: "default" | "reels";
};

export default function ReelsPostOptionsMenu({
  postData,
  isOwnPost,
  viewCount = 0,
  variant = "default",
}: Props) {
  const { t } = useTranslation("common");
  const { language } = useAppLanguage();
  const numberLocale = language === "en" ? "en-US" : "fa-IR";
  const { request } = useAxios();
  const queryClient = useQueryClient();
  const router = useRouter();
  const canEdit = isOwnPost;
  const [open, setOpen] = useState(false);
  const [reportOpen, setReportOpen] = useState(false);
  const [analyticsOpen, setAnalyticsOpen] = useState(false);
  const [reportReason, setReportReason] = useState("");
  const [reportText, setReportText] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [isPinned, setIsPinned] = useState(Boolean(postData.is_pinned));
  const [isArchived, setIsArchived] = useState(Boolean(postData.is_archived));

  useEffect(() => {
    setIsPinned(Boolean(postData.is_pinned));
  }, [postData.is_pinned, postData._id]);

  useEffect(() => {
    setIsArchived(Boolean(postData.is_archived));
  }, [postData.is_archived, postData._id]);

  const submitReport = async () => {
    if (!reportReason.trim()) {
      toast.error(t("posts.selectReportReason"));
      return;
    }
    setSubmitting(true);
    try {
      await request(
        "POST",
        "/posts/report",
        {
          postId: postData._id,
          reason: reportReason,
          text: reportText,
        },
        { noToast: true }
      );
      toast.success(t("posts.reportSubmitted"));
      setReportOpen(false);
      setOpen(false);
      setReportReason("");
      setReportText("");
    } catch {
      toast.error(t("posts.reportFailed"));
    } finally {
      setSubmitting(false);
    }
  };

  const pinPost = async () => {
    try {
      const res = await request<{
        unpinned?: boolean;
        pinned_post_ids?: string[];
        message?: string;
      }>(
        "POST",
        "/account/pin-post",
        { postId: postData._id },
        { noToast: true }
      );
      const unpinned = Boolean(res?.unpinned);
      setIsPinned(!unpinned);
      toast.success(unpinned ? t("posts.postUnpinned") : t("posts.postPinned"));
      setOpen(false);
      void queryClient.invalidateQueries({ queryKey: ["posts"] });
    } catch (err: unknown) {
      const message = (
        err as { response?: { data?: { message?: string } } }
      )?.response?.data?.message;
      toast.error(message || t("posts.pinFailed"));
    }
  };

  const toggleArchive = async () => {
    try {
      const res = await request<{ is_archived?: boolean; message?: string }>(
        "POST",
        "/account/archive-post",
        { postId: postData._id },
        { noToast: true }
      );
      const archived = Boolean(res?.is_archived);
      setIsArchived(archived);
      toast.success(archived ? t("posts.postArchived") : t("posts.postUnarchived"));
      setOpen(false);
      void queryClient.invalidateQueries({ queryKey: ["posts"] });
      void queryClient.invalidateQueries({ queryKey: ["archived-posts"] });
      if (archived) {
        router.back();
      }
    } catch (err: unknown) {
      const message = (
        err as { response?: { data?: { message?: string } } }
      )?.response?.data?.message;
      toast.error(message || t("posts.archiveFailed"));
    }
  };

  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(true)}
        className={
          variant === "reels"
            ? "inline-flex shrink-0 items-center justify-center"
            : "gentle-transition flex h-10 w-10 items-center justify-center rounded-full bg-black/40 text-white backdrop-blur-md active:scale-90"
        }
        aria-label={t("posts.moreOptions")}
      >
        {variant === "reels" ? (
          <FiMoreHorizontal
            size={28}
            strokeWidth={2.75}
            className="text-white drop-shadow-lg"
            aria-hidden
          />
        ) : (
          <BoldIcon
            name="more-2"
            size={22}
            tinted
            className="text-white"
          />
        )}
      </button>

      <Modal
        isOpen={open}
        onClose={() => setOpen(false)}
        height="fit"
        panelClassName="!p-0 max-h-[70dvh] overflow-hidden"
      >
        <div className="flex flex-col py-2">
          <button
            type="button"
            onClick={() => {
              setOpen(false);
              setReportOpen(true);
            }}
            className="px-5 py-3.5 text-right text-sm font-semibold text-red-500 active:bg-neutral-100 dark:active:bg-neutral-800"
          >
            {t("posts.reportPost")}
          </button>
          <button
            type="button"
            onClick={() => setOpen(false)}
            className="px-5 py-3.5 text-right text-sm active:bg-neutral-100 dark:active:bg-neutral-800"
          >
            {t("posts.postViews", {
              count: viewCount.toLocaleString(numberLocale),
            })}
          </button>
          {isOwnPost ? (
            <>
              {canEdit ? (
                <button
                  type="button"
                  onClick={() => {
                    setOpen(false);
                    router.push(`/new-post?edit=${postData._id}`);
                  }}
                  className="px-5 py-3.5 text-right text-sm active:bg-neutral-100 dark:active:bg-neutral-800"
                >
                  {t("posts.editPost")}
                </button>
              ) : null}
              <button
                type="button"
                onClick={() => {
                  setOpen(false);
                  setAnalyticsOpen(true);
                }}
                className="px-5 py-3.5 text-right text-sm active:bg-neutral-100 dark:active:bg-neutral-800"
              >
                {t("posts.viewAnalytics")}
              </button>
              <button
                type="button"
                onClick={() => void pinPost()}
                className="px-5 py-3.5 text-right text-sm active:bg-neutral-100 dark:active:bg-neutral-800"
              >
                {isPinned ? t("posts.unpinPost") : t("posts.pinPost")}
              </button>
              <button
                type="button"
                onClick={() => void toggleArchive()}
                className="px-5 py-3.5 text-right text-sm active:bg-neutral-100 dark:active:bg-neutral-800"
              >
                {isArchived ? t("posts.publishPost") : t("posts.archivePost")}
              </button>
            </>
          ) : null}
        </div>
      </Modal>

      <Modal
        isOpen={reportOpen}
        onClose={() => setReportOpen(false)}
        height="fit"
        panelClassName="!p-4"
      >
        <p className="mb-3 text-center text-sm font-bold text-red-500">
          {t("posts.reportReasonTitle")}
        </p>
        <select
          value={reportReason}
          onChange={(e) => setReportReason(e.target.value)}
          className="mb-3 w-full rounded-xl border border-neutral-200 bg-transparent px-3 py-2 text-sm dark:border-neutral-700"
        >
          <option value="">{t("posts.selectReason")}</option>
          {REPORT_REASON_IDS.map((id) => (
            <option key={id} value={t(`posts.reportReasonValues.${id}`)}>
              {t(`posts.reportReasons.${id}`)}
            </option>
          ))}
        </select>
        <textarea
          value={reportText}
          onChange={(e) => setReportText(e.target.value)}
          placeholder={t("posts.reportNotesPlaceholder")}
          rows={3}
          className="mb-4 w-full resize-none rounded-xl border border-neutral-200 bg-transparent px-3 py-2 text-sm dark:border-neutral-700"
        />
        <RoundedButton
          type="button"
          variant="primary"
          disabled={submitting}
          onClick={() => void submitReport()}
          className="h-10 w-full text-sm"
        >
          {submitting ? t("posts.submittingReport") : t("posts.submitReport")}
        </RoundedButton>
      </Modal>

      {analyticsOpen ? (
        <ReelsPostAnalyticsModal
          postData={postData}
          isOpen={analyticsOpen}
          onClose={() => setAnalyticsOpen(false)}
        />
      ) : null}
    </>
  );
}
