"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 {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { RotateCcw, 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;
  avgRating: number | null;
  priceCents: number | null;
  images: { url: string; altText: string | null }[];
  _count: {
    bookings: number;
    reviews: number;
  };
};

interface ArchivedTourCardProps {
  tour: Tour;
}

export default function ArchivedTourCard({ tour }: ArchivedTourCardProps) {
  const router = useRouter();
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [showUnarchiveDialog, setShowUnarchiveDialog] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [isUnarchiving, setIsUnarchiving] = 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 permanently deleted!", {
        description: `"${tour.title}" has been permanently removed.`,
      });

      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 handleUnarchive = async () => {
    setIsUnarchiving(true);
    try {
      const response = await fetch(`/api/tours/${tour.id}/unarchive`, {
        method: "POST",
      });

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

      toast.success("Tour restored successfully!", {
        description: `"${tour.title}" has been restored to your active tours.`,
      });

      router.push("/dashboard");
      router.refresh();
    } catch {
      toast.error("Failed to restore tour", {
        description: "Please try again later.",
      });
    } finally {
      setIsUnarchiving(false);
      setShowUnarchiveDialog(false);
    }
  };

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

  return (
    <>
      <Card className="overflow-hidden opacity-75">
        <div className="relative h-48 bg-linear-to-br from-gray-400 to-gray-600">
          <Image
            src={imageUrl}
            alt={tour.images[0]?.altText || tour.title}
            fill
            className="object-cover grayscale"
          />
          <div className="absolute top-2 right-2">
            <Badge variant="secondary">Archived</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>

          <Button
            variant="outline"
            size="sm"
            onClick={() => setShowUnarchiveDialog(true)}
          >
            <RotateCcw className="mr-2 h-4 w-4" />
            Restore
          </Button>

          <Button
            variant="outline"
            size="sm"
            onClick={() => setShowDeleteDialog(true)}
          >
            <Trash2 className="h-4 w-4 text-destructive" />
          </Button>
        </CardFooter>
      </Card>

      {/* Delete Dialog */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Tour Permanently</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to permanently delete &quot;{tour.title}&quot;?
              This action cannot be undone.
            </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 Permanently"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Unarchive Dialog */}
      <AlertDialog
        open={showUnarchiveDialog}
        onOpenChange={setShowUnarchiveDialog}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Restore Tour</AlertDialogTitle>
            <AlertDialogDescription>
              Restore &quot;{tour.title}&quot; from the archive? The tour will be
              moved back to your active tours (but will remain unpublished until
              you publish it again).
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isUnarchiving}>
              Cancel
            </AlertDialogCancel>
            <AlertDialogAction onClick={handleUnarchive} disabled={isUnarchiving}>
              {isUnarchiving ? "Restoring..." : "Restore"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}
