import { useState } from "react";
import { useAuthStore } from "@/pages/auth/store/AuthStore";
import { useSendEmail } from "@/pages/received/hooks/useEmailData";
import { SendEmailDto } from "@/pages/received/types/Types";
import { MessageDetail } from "@/pages/received/types/Types";
import { toast } from "@/components/Toast";

interface UseReplyProps {
  originalMessage: MessageDetail;
  onSuccess?: () => void;
  onError?: (error: string) => void;
}

export const useReply = ({
  originalMessage,
  onSuccess,
  onError,
}: UseReplyProps) => {
  const { email: userEmail } = useAuthStore();
  const [content, setContent] = useState<string>("");
  const [isExpanded, setIsExpanded] = useState<boolean>(false);

  // API hooks
  const sendEmailMutation = useSendEmail();

  const resetForm = () => {
    setContent("");
    setIsExpanded(false);
  };

  const handleSendReply = async (html: string) => {
    if (!content.trim()) {
      toast("لطفا متن پیام را وارد کنید", "error");
      return false;
    }

    if (!originalMessage) {
      toast("اطلاعات پیام یافت نشد", "error");
      return false;
    }

    // Format date to Persian
    const originalDate = new Date(originalMessage.date);
    const persianDate = new Intl.DateTimeFormat("fa-IR", {
      weekday: "long",
      year: "numeric",
      month: "long",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    }).format(originalDate);

    const htmlContent = `
      <div dir="rtl" style="font-family: 'Irancell', Arial, sans-serif; line-height: 1.6;">
        <div style="margin-bottom: 10px; padding: 15px;">
          ${content}
        </div>
        
        <div style="border-top: 2px solid #e9ecef; padding-top: 10px;">
          <div style=" font-size: 12px; margin-bottom: 10px; padding: 8px;  border-radius: 4px;">
             در پاسخ به پیام ارسالی در تاریخ ${persianDate}
            <br />
             از: ${originalMessage.from.name} &lt;${originalMessage.from.address}&gt;
          </div>
          
          <div >
              ${html}
          </div>
        </div>
      </div>
    `;

    const replyData: SendEmailDto = {
      from: { address: userEmail || "sender@example.com" },
      to: [
        {
          address: originalMessage.from.address,
          name: originalMessage.from.name,
        },
      ],
      replyTo: {
        name: originalMessage.from.name,
        address: originalMessage.from.address,
      },
      subject: originalMessage.subject.startsWith("Re:")
        ? originalMessage.subject
        : `Re: ${originalMessage.subject}`,
      html: htmlContent,
      text: `${content.replace(/<[^>]*>/g, "")}

═══════════════════════════════════════════════════════

📩 در پاسخ به پیام ارسالی در تاریخ ${persianDate}
📧 از: ${originalMessage.from.name} <${originalMessage.from.address}>

متن پیام اصلی:
${
  originalMessage.text ||
  originalMessage.html?.join("").replace(/<[^>]*>/g, "") ||
  ""
}`,
    };

    try {
      await sendEmailMutation.mutateAsync(replyData);
      toast("پاسخ با موفقیت ارسال شد", "success");
      resetForm();
      onSuccess?.();
      return true;
    } catch {
      const errorMessage = "خطا در ارسال پاسخ";
      toast(errorMessage, "error");
      onError?.(errorMessage);
      return false;
    }
  };

  const handleSaveDraft = async () => {
    if (!content.trim()) {
      toast("متن پیام خالی است", "error");
      return false;
    }

    try {
      // TODO: Implement save draft functionality
      toast("پیش‌نویس ذخیره شد", "success");
      return true;
    } catch {
      const errorMessage = "خطا در ذخیره پیش‌نویس";
      toast(errorMessage, "error");
      onError?.(errorMessage);
      return false;
    }
  };

  const expandReply = () => {
    setIsExpanded(true);
  };

  const collapseReply = () => {
    setIsExpanded(false);
    resetForm();
  };

  return {
    // State
    content,
    isExpanded,
    isSending: sendEmailMutation.isPending,

    // Handlers
    setContent,
    expandReply,
    collapseReply,
    handleSendReply,
    handleSaveDraft,
    resetForm,

    // Original message data
    originalMessage,
  };
};
