"use client";

import { useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { Card, CardContent, CardFooter } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
  MoreVertical,
  Edit,
  Archive,
  Trash2,
  Eye,
  Star,
  Users,
  MessageSquare,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";

type Tour = {
  id: string;
  title: string;
  slug: string;
  city: string;
  published: boolean;
  avgRating: number | null;
  priceCents: number | null;
  images: { url: string; altText: string | null }[];
  _count: {
    bookings: number;
    reviews: number;
  };
};

interface TourManagementCardProps {
  tour: Tour;
}

export default function TourManagementCard({ tour }: TourManagementCardProps) {
  const router = useRouter();
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [showArchiveDialog, setShowArchiveDialog] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [isArchiving, setIsArchiving] = useState(false);

  const handleDelete = async () => {
    setIsDeleting(true);
    try {
      const response = await fetch(`/api/tours/${tour.id}`, {
        method: "DELETE",
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || "Failed to delete tour");
      }

      toast.success("Tour deleted successfully!", {
        description: `"${tour.title}" has been permanently deleted.`,
      });

      router.refresh();
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : "Failed to delete tour";
      toast.error("Failed to delete tour", {
        description: errorMessage,
      });
    } finally {
      setIsDeleting(false);
      setShowDeleteDialog(false);
    }
  };

  const handleArchive = async () => {
    setIsArchiving(true);
    try {
      const response = await fetch(`/api/tours/${tour.id}/archive`, {
        method: "POST",
      });

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

      toast.success("Tour archived successfully!", {
        description: `"${tour.title}" has been archived and unpublished.`,
      });

      router.refresh();
    } catch {
      toast.error("Failed to archive tour", {
        description: "Please try again later.",
      });
    } finally {
      setIsArchiving(false);
      setShowArchiveDialog(false);
    }
  };

  const imageUrl = tour.images[0]?.url || "/placeholder-tour.jpg";

  return (
    <>
      <Card className="overflow-hidden hover:shadow-lg transition-shadow">
        <div className="relative h-48 bg-linear-to-br from-blue-400 to-purple-500">
          <Image
            src={imageUrl}
            alt={tour.images[0]?.altText || tour.title}
            fill
            className="object-cover"
          />
          <div className="absolute top-2 right-2 flex gap-2">
            <Badge variant={tour.published ? "default" : "secondary"}>
              {tour.published ? "Published" : "Draft"}
            </Badge>
          </div>
        </div>

        <CardContent className="pt-4">
          <div className="mb-2">
            <h3 className="font-semibold text-lg line-clamp-1">{tour.title}</h3>
            <p className="text-sm text-muted-foreground">{tour.city}</p>
          </div>

          <div className="flex items-center gap-4 text-sm text-muted-foreground">
            <div className="flex items-center gap-1">
              <Star className="h-4 w-4" />
              <span>{tour.avgRating?.toFixed(1) || "No rating"}</span>
            </div>
            <div className="flex items-center gap-1">
              <Users className="h-4 w-4" />
              <span>{tour._count.bookings} bookings</span>
            </div>
            <div className="flex items-center gap-1">
              <MessageSquare className="h-4 w-4" />
              <span>{tour._count.reviews} reviews</span>
            </div>
          </div>

          {tour.priceCents !== null && (
            <div className="mt-3">
              <span className="text-lg font-bold">
                CHF {(tour.priceCents / 100).toFixed(2)}
              </span>
              <span className="text-sm text-muted-foreground"> per person</span>
            </div>
          )}
        </CardContent>

        <CardFooter className="flex gap-2 pt-0">
          <Link href={`/tours/${tour.slug}`} className="flex-1">
            <Button variant="outline" size="sm" className="w-full">
              <Eye className="mr-2 h-4 w-4" />
              View
            </Button>
          </Link>

          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline" size="sm">
                <MoreVertical className="h-4 w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem asChild>
                <Link href={`/tours/edit/${tour.id}`} className="cursor-pointer">
                  <Edit className="mr-2 h-4 w-4" />
                  Edit
                </Link>
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem
                onClick={() => setShowArchiveDialog(true)}
                className="cursor-pointer"
              >
                <Archive className="mr-2 h-4 w-4" />
                Archive
              </DropdownMenuItem>
              <DropdownMenuItem
                onClick={() => setShowDeleteDialog(true)}
                className="cursor-pointer text-destructive focus:text-destructive"
              >
                <Trash2 className="mr-2 h-4 w-4" />
                Delete
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </CardFooter>
      </Card>

      {/* Delete Dialog */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Tour</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete &quot;{tour.title}&quot;? This action
              cannot be undone. If you have confirmed bookings, consider
              archiving instead.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              disabled={isDeleting}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {isDeleting ? "Deleting..." : "Delete"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Archive Dialog */}
      <AlertDialog open={showArchiveDialog} onOpenChange={setShowArchiveDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Archive Tour</AlertDialogTitle>
            <AlertDialogDescription>
              Archive &quot;{tour.title}&quot;? The tour will be hidden from public
              view but can be restored later. This will also unpublish the tour.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isArchiving}>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={handleArchive} disabled={isArchiving}>
              {isArchiving ? "Archiving..." : "Archive"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}
