"use client";

import { useState } from "react";
import Modal from "@/components/elements/Modal";
import useAxios from "@/hooks/useAxios";
import { IGift } from "@/types/types";
import RoundedButton from "@/components/elements/RoundedButton";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

type GiftReplyModalProps = {
  isOpen: boolean;
  onClose: () => void;
  item: IGift | null;
  onReplied: () => void;
};

function GiftReplyModal({ isOpen, onClose, item, onReplied }: GiftReplyModalProps) {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const [replyText, setReplyText] = useState(item?.reply || "");
  const [submitting, setSubmitting] = useState(false);

  const submitReply = async () => {
    if (!replyText.trim()) {
      toast.error(t("settings.gifts.replyRequired"));
      return;
    }
    setSubmitting(true);
    try {
      await request("POST", "/gifts/reply", {
        giftId: item?._id,
        reply: replyText,
      });
      toast.success(t("settings.gifts.replySubmitted"));
      onReplied();
      onClose();
    } catch (err: unknown) {
      const message =
        (err as { response?: { data?: { message?: string } } })?.response
          ?.data?.message || t("shops.unknownError");
      toast.error(message);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Modal height="fit" isOpen={isOpen} onClose={onClose}>
      <div className="flex flex-col items-center gap-4 py-5">
        <span className="text-sm font-bold">{t("settings.gifts.replyTitle")}</span>
        {item?.message ? (
          <p className="w-full rounded-2xl bg-neutral-100 p-3 text-xs text-neutral-600 dark:bg-neutral-800 dark:text-neutral-300">
            {item.message}
          </p>
        ) : null}
        <textarea
          value={replyText}
          onChange={(e) => setReplyText(e.target.value)}
          className="h-24 w-full rounded-3xl border border-border-secondary-light bg-secondary-light p-4 font-medium dark:border-border-secondary-dark dark:bg-secondary-dark"
        />
        <RoundedButton
          className="mt-2 h-9 w-36"
          disabled={submitting}
          onClick={() => void submitReply()}
        >
          {t("settings.gifts.submitReply")}
        </RoundedButton>
      </div>
    </Modal>
  );
}

export default GiftReplyModal;
