import { useNavigate } from "@remix-run/react";
import { MessageCircleMore } from "lucide-react";
import { ProductDetail } from "src/api/types";
import { Button } from "~/components/ui/button";
import { useCreateChatThread } from "~/requestHandler/use-chat-hooks";
import { useRootData } from "~/hooks/use-root-data";
import { useState } from "react";
import { LoginRequiredDialog } from "~/components/LoginRequiredDialog";

export const ContactButton = ({ product }: { product: ProductDetail }) => {
  const navigate = useNavigate();
  const { user } = useRootData();
  const [isLoginDialogOpen, setIsLoginDialogOpen] = useState(false);
  const { mutate: createChatThread, isPending: isCreatingChatThread } =
    useCreateChatThread();
  const handleCreateChatThread = () => {
    if (!user) {
      setIsLoginDialogOpen(true);
      return;
    }
    if (!product.seller?.id) return;
    createChatThread(product.seller.id, {
      onSuccess: (threadData) => {
        navigate(`/profile/threads/${threadData.id}`);
      },
    });
  };
  return (
    <>
      <div className="mt-10 px-4 pb-4 w-full">
        <Button
          variant="primary"
          onClick={handleCreateChatThread}
          disabled={!product.seller?.id || isCreatingChatThread}
          size="lg"
          className="w-full font-bold"
        >
          <MessageCircleMore size={24} />
          {isCreatingChatThread ? "در حال اتصال..." : "گفتگو با فروشنده"}
        </Button>
      </div>
      <LoginRequiredDialog
        loginTitle="برای ارسال پیام به فروشنده ابتدا باید وارد حساب کاربری خود شوید."
        isOpen={isLoginDialogOpen}
        onOpenChange={setIsLoginDialogOpen}
      />
    </>
  );
};
