"use client";

import { Post } from "@/types/types";
import React, { useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { motion, AnimatePresence } from "framer-motion";
import ReportModal from "@/components/main/ReportModal";
import CommentsModal from "@/components/models/MainModelCard/CommentsModal";
import ModelDetailModal from "@/components/models/ModelDetailModal";
import ModelServiceModal from "@/components/models/ModelServiceModal";
import { useUserById } from "@/hooks/getUserById";
import SharePostModal from "@/components/main/SharePostModal";
import SendPostModal from "@/components/posts/SendPostModal";
import { buildStorageUrl, staticIconUrl } from "@/components/main/BaseUrl";
import { SocialStatButton, SocialIconButton } from "@/components/ui/SocialStatButton";
import {
  POST_SOCIAL_ICONS,
  PostSocialIcon,
  usePostSocialState,
} from "@/hooks/usePostSocialActions";
import { POST_ACTIONS_ROW_CLASS } from "@/constants/pageLayout";
import { useExploreReelsUi } from "@/contexts/ExploreReelsUiContext";
import ReelsPostOptionsMenu from "./ReelsPostOptionsMenu";
import BoldIcon from "@/components/ui/BoldIcon";
import { useTranslation } from "react-i18next";

interface ReelsPostActionsProps {
  postData: Post;
  social: ReturnType<typeof usePostSocialState>;
  alwaysVisible?: boolean;
  onCommentClick?: () => void;
  allowSave?: boolean;
  sharingStory?: boolean;
  onShareToStory?: () => void;
}

function ReelsProfileFollowButton({
  userName,
  profileImage,
  following,
  isOwnPost,
  onToggleFollow,
}: {
  userName: string;
  profileImage?: string;
  following: boolean;
  isOwnPost: boolean;
  onToggleFollow: () => void;
}) {
  const { t } = useTranslation("common");
  const avatar = (
    <div className="relative h-12 w-12 overflow-hidden rounded-full border-2 border-white shadow-lg">
      <Image
        src={profileImage ? buildStorageUrl(profileImage) : "/images/fake-avatar.png"}
        alt={userName}
        fill
        className="rounded-full object-cover"
        unoptimized
      />
    </div>
  );

  if (isOwnPost) {
    return (
      <Link href={`/users/${userName}`} className="mb-0 block">
        {avatar}
      </Link>
    );
  }

  return (
    <button
      type="button"
      onClick={onToggleFollow}
      className="relative mb-0 block"
      aria-label={following ? t("posts.unfollow") : t("posts.follow")}
    >
      {avatar}
      <span className="absolute -bottom-1 left-1/2 flex h-5 w-5 -translate-x-1/2 items-center justify-center rounded-full border border-white bg-white shadow-md">
        {following ? (
          <BoldIcon
            name="tick-circle"
            size={14}
            tinted
            className="text-[#FF107D]"
          />
        ) : (
          <span
            aria-hidden
            className="flex h-full w-full items-center justify-center text-[17px] font-bold leading-none text-[#FF107D] translate-y-px"
          >
            +
          </span>
        )}
      </span>
    </button>
  );
}

function ReelsStoryShareButton({
  disabled,
  onClick,
}: {
  disabled?: boolean;
  onClick?: () => void;
}) {
  const { t } = useTranslation("common");
  return (
    <button
      type="button"
      disabled={disabled}
      onClick={onClick}
      className="inline-flex shrink-0 items-center justify-center disabled:opacity-60"
      aria-label={t("posts.addToStory")}
    >
      <Image
        src={staticIconUrl("/images/icons/story.png")}
        alt=""
        width={36}
        height={36}
        className="h-9 w-9 invert brightness-125 drop-shadow-lg"
        unoptimized
      />
    </button>
  );
}

export default function ReelsPostActions({
  postData,
  social,
  alwaysVisible = false,
  onCommentClick,
  allowSave = true,
  sharingStory = false,
  onShareToStory,
}: ReelsPostActionsProps) {
  const { t } = useTranslation("common");
  const { user_id, user_name } = postData;

  const user = useUserById(user_id);
  const expertise = user?.expertise;
  const hair_color = user?.hair_color;
  const eye_color = user?.eye_color;
  const height = user?.height;
  const size = user?.size;
  const weight = user?.weight;
  const services = user?.services;

  const exploreUi = useExploreReelsUi();
  const [localExpanded, setLocalExpanded] = useState(false);
  const expanded = exploreUi ? exploreUi.actionsExpanded : localExpanded;
  const setExpanded = exploreUi
    ? exploreUi.setActionsExpanded
    : setLocalExpanded;

  const [showReportModal, setShowReportModal] = useState(false);
  const [showCommentsModal, setShowCommentsModal] = useState(false);
  const [showShareModal, setShowShareModal] = useState(false);
  const [showSendModal, setShowSendModal] = useState(false);
  const [showServicesModal, setShowServicesModal] = useState(false);

  const openComments = () => {
    if (onCommentClick) {
      onCommentClick();
      return;
    }
    setShowCommentsModal(true);
  };

  const postIconSize = "sm" as const;
  const reelsIconSize = "md" as const;
  const actionButtonClass = "text-white drop-shadow-md";
  const reelsActionButtonClass = "text-white brightness-125 drop-shadow-lg";

  const collaborationModals = showServicesModal &&
    (expertise === "مدلینگ" ? (
      <ModelDetailModal
        hairColor={hair_color}
        eyeColor={eye_color}
        height={height}
        size={size}
        weight={weight}
        isOpen={showServicesModal}
        onClose={() => setShowServicesModal(false)}
        isMain
        userId={user_id}
      />
    ) : (
      <ModelServiceModal
        services={services}
        isOpen={showServicesModal}
        onClose={() => setShowServicesModal(false)}
        userId={user_id}
      />
    ));

  const postPageActions = (
    <>
      <SocialIconButton
        layout="horizontal"
        onClick={() => setShowServicesModal(true)}
        className={actionButtonClass}
        aria-label={t("posts.collaborationRequest")}
        icon={<PostSocialIcon {...POST_SOCIAL_ICONS.collaboration(postIconSize)} />}
      />
      {!social.isOwnPost && (
        <SocialIconButton
          layout="horizontal"
          onClick={social.toggleFollow}
          className={actionButtonClass}
          aria-label={social.following ? t("posts.unfollow") : t("posts.follow")}
          icon={
            <PostSocialIcon
              {...POST_SOCIAL_ICONS.follow(social.following, postIconSize)}
            />
          }
        />
      )}
      <SocialStatButton
        layout="horizontal"
        count={social.sendsCount}
        onClick={() => setShowSendModal(true)}
        className={actionButtonClass}
        aria-label={t("posts.send")}
        icon={<PostSocialIcon {...POST_SOCIAL_ICONS.send(postIconSize)} />}
      />
      <SocialStatButton
        layout="horizontal"
        count={0}
        showZero={false}
        onClick={() => {
          social.trackShare();
          if (social.shareUrl) setShowShareModal(true);
        }}
        className={actionButtonClass}
        aria-label={t("posts.share")}
        icon={<PostSocialIcon {...POST_SOCIAL_ICONS.share(postIconSize)} />}
      />
      {allowSave ? (
        <SocialIconButton
          layout="horizontal"
          onClick={social.toggleSave}
          className={actionButtonClass}
          aria-label={social.saved ? t("posts.removeFavorite") : t("posts.favorite")}
          icon={
            <PostSocialIcon
              {...POST_SOCIAL_ICONS.save(social.saved, postIconSize)}
            />
          }
        />
      ) : null}
      <SocialStatButton
        layout="horizontal"
        count={social.commentCount}
        onClick={openComments}
        className={actionButtonClass}
        aria-label={t("posts.comment")}
        icon={<PostSocialIcon {...POST_SOCIAL_ICONS.comment(postIconSize)} />}
      />
      <SocialStatButton
        layout="horizontal"
        likeCount={social.likesCountState}
        onClick={social.toggleLike}
        className={actionButtonClass}
        aria-label={t("posts.like")}
        icon={
          <PostSocialIcon
            {...POST_SOCIAL_ICONS.like(social.liked, postIconSize)}
          />
        }
      />
    </>
  );

  const reelsActions = (
    <>
      <ReelsProfileFollowButton
        userName={user_name}
        profileImage={user?.profile_image}
        following={social.following}
        isOwnPost={social.isOwnPost}
        onToggleFollow={social.toggleFollow}
      />
      <SocialIconButton
        layout="vertical"
        onClick={() => setShowServicesModal(true)}
        className={reelsActionButtonClass}
        aria-label={t("posts.collaborationRequest")}
        icon={
          <PostSocialIcon {...POST_SOCIAL_ICONS.collaboration(reelsIconSize)} />
        }
      />
      <SocialStatButton
        layout="vertical"
        likeCount={social.likesCountState}
        onClick={social.toggleLike}
        className={reelsActionButtonClass}
        aria-label={t("posts.like")}
        icon={
          <PostSocialIcon
            {...POST_SOCIAL_ICONS.like(social.liked, reelsIconSize)}
          />
        }
      />
      <SocialStatButton
        layout="vertical"
        count={social.commentCount}
        onClick={openComments}
        className={reelsActionButtonClass}
        aria-label={t("posts.comment")}
        icon={<PostSocialIcon {...POST_SOCIAL_ICONS.comment(reelsIconSize)} />}
      />
      <SocialStatButton
        layout="vertical"
        count={0}
        showZero={false}
        onClick={() => {
          social.trackShare();
          if (social.shareUrl) setShowShareModal(true);
        }}
        className={reelsActionButtonClass}
        aria-label={t("posts.share")}
        icon={<PostSocialIcon {...POST_SOCIAL_ICONS.share(reelsIconSize)} />}
      />
      <SocialStatButton
        layout="vertical"
        count={social.sendsCount}
        onClick={() => setShowSendModal(true)}
        className={reelsActionButtonClass}
        aria-label={t("posts.send")}
        icon={<PostSocialIcon {...POST_SOCIAL_ICONS.send(reelsIconSize)} />}
      />
      {allowSave ? (
        <SocialIconButton
          layout="vertical"
          onClick={social.toggleSave}
          className={reelsActionButtonClass}
          aria-label={social.saved ? t("posts.removeFavorite") : t("posts.favorite")}
          icon={
            <PostSocialIcon
              {...POST_SOCIAL_ICONS.save(social.saved, reelsIconSize)}
            />
          }
        />
      ) : null}
    </>
  );

  const optionsMenu = (
    <ReelsPostOptionsMenu
      postData={postData}
      isOwnPost={social.isOwnPost}
      viewCount={postData.viewsCount ?? 0}
      variant="reels"
    />
  );

  return (
    <>
      {showReportModal && (
        <ReportModal
          isOpen={showReportModal}
          onClose={() => setShowReportModal(false)}
        />
      )}
      {showCommentsModal && !onCommentClick && (
        <CommentsModal
          isOpen={showCommentsModal}
          onClose={() => setShowCommentsModal(false)}
          userId={user_id}
          postId={postData._id}
        />
      )}
      <SharePostModal
        open={showShareModal}
        onClose={() => setShowShareModal(false)}
        url={social.shareUrl}
      />
      {social.currentUserId && (
        <SendPostModal
          open={showSendModal}
          onClose={() => setShowSendModal(false)}
          postData={postData}
          currentUserId={social.currentUserId}
          onSent={(count) => social.setSendsCount(count)}
        />
      )}
      {collaborationModals}

      {alwaysVisible ? (
        <div className="absolute inset-x-0 bottom-[calc(7.25rem+env(safe-area-inset-bottom))] z-30">
          <div className={POST_ACTIONS_ROW_CLASS}>{postPageActions}</div>
        </div>
      ) : (
        <div className="absolute bottom-36 left-3 z-30 flex flex-col items-center gap-4">
          {onShareToStory ? (
            <ReelsStoryShareButton
              disabled={sharingStory}
              onClick={onShareToStory}
            />
          ) : null}
          <AnimatePresence mode="wait">
            {!expanded ? (
              <motion.div
                key="collapsed"
                initial={{ opacity: 0, scale: 0.8 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0, scale: 0.8 }}
                transition={{ duration: 0.2 }}
                className="flex flex-col items-center gap-3"
              >
                <button
                  type="button"
                  onClick={() => setExpanded(true)}
                  className="flex items-center justify-center"
                  aria-label={t("posts.showActions")}
                >
                  <Image
                    width={28}
                    height={28}
                    alt=""
                    src="/images/icons/actions-toggle.svg"
                    className="drop-shadow-lg invert"
                  />
                </button>
                {optionsMenu}
              </motion.div>
            ) : (
              <motion.div
                key="actions"
                initial={{ opacity: 0, y: 12 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: 12 }}
                transition={{ duration: 0.25, ease: "easeOut" }}
                className="flex flex-col items-center gap-4"
              >
                {reelsActions}
                <button
                  type="button"
                  onClick={() => setExpanded(false)}
                  className="flex items-center justify-center"
                  aria-label={t("posts.close")}
                >
                  <Image
                    width={28}
                    height={28}
                    alt=""
                    src="/images/icons/actions-toggle.svg"
                    className="drop-shadow-lg invert opacity-80"
                  />
                </button>
                {optionsMenu}
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      )}
    </>
  );
}

/** @deprecated */
export function ReelsCollaborationButton({
  postData,
}: {
  postData: Post;
}) {
  const { t } = useTranslation("common");
  const user = useUserById(postData.user_id);
  const [showServicesModal, setShowServicesModal] = useState(false);

  return (
    <>
      {showServicesModal &&
        (user?.expertise === "مدلینگ" ? (
          <ModelDetailModal
            hairColor={user?.hair_color}
            eyeColor={user?.eye_color}
            height={user?.height}
            size={user?.size}
            weight={user?.weight}
            isOpen={showServicesModal}
            onClose={() => setShowServicesModal(false)}
            isMain
            userId={postData.user_id}
          />
        ) : (
          <ModelServiceModal
            services={user?.services}
            isOpen={showServicesModal}
            onClose={() => setShowServicesModal(false)}
            userId={postData.user_id}
          />
        ))}
      <button
        type="button"
        onClick={() => setShowServicesModal(true)}
        className="shrink-0 rounded-lg border border-white/80 px-3 py-1.5 text-xs font-semibold text-white backdrop-blur-sm transition active:scale-95"
      >
        {t("posts.collaborationRequest")}
      </button>
    </>
  );
}
