"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Eye, EyeOff, Edit, LayoutDashboard, Loader2 } from "lucide-react";
import { toast } from "sonner";

interface PreviewActionsProps {
  tourId: string;
  isPublished: boolean;
  isArchived: boolean;
}

export function PreviewActions({ tourId, isPublished, isArchived }: PreviewActionsProps) {
  const router = useRouter();
  const [isPublishing, setIsPublishing] = useState(false);

  const handlePublishToggle = async () => {
    setIsPublishing(true);
    try {
      const response = await fetch(`/api/tours/${tourId}`, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          published: !isPublished,
        }),
      });

      if (!response.ok) {
        throw new Error("Failed to update tour");
      }

      toast.success(
        isPublished 
          ? "Tour unpublished successfully. It's now hidden from tourists." 
          : "Tour published successfully! It's now live and visible to tourists."
      );
      
      router.refresh();
    } catch (error) {
      console.error("Error toggling publish status:", error);
      toast.error("Failed to update tour. Please try again.");
    } finally {
      setIsPublishing(false);
    }
  };

  return (
    <div className="flex flex-wrap gap-3">
      {!isArchived && (
        <Button
          onClick={handlePublishToggle}
          disabled={isPublishing}
          size="lg"
          variant={isPublished ? "outline" : "default"}
          className={isPublished ? "" : "bg-green-600 hover:bg-green-700"}
        >
          {isPublishing ? (
            <>
              <Loader2 className="w-4 h-4 mr-2 animate-spin" />
              {isPublished ? "Unpublishing..." : "Publishing..."}
            </>
          ) : (
            <>
              {isPublished ? (
                <>
                  <EyeOff className="w-4 h-4 mr-2" />
                  Unpublish Tour
                </>
              ) : (
                <>
                  <Eye className="w-4 h-4 mr-2" />
                  Publish Tour
                </>
              )}
            </>
          )}
        </Button>
      )}

      <Button
        onClick={() => router.push(`/tours/edit/${tourId}`)}
        variant="outline"
        size="lg"
      >
        <Edit className="w-4 h-4 mr-2" />
        Edit Tour
      </Button>

      <Button
        onClick={() => router.push("/dashboard")}
        variant="outline"
        size="lg"
      >
        <LayoutDashboard className="w-4 h-4 mr-2" />
        Go to Dashboard
      </Button>
    </div>
  );
}
