"use client";

import Image from "next/image";
import Link from "next/link";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  Calendar,
  MapPin,
  Users,
  Clock,
  CheckCircle2,
  XCircle,
  AlertCircle,
  Loader2,
  Ban,
} from "lucide-react";
import { format } from "date-fns";
import { useState } from "react";
import { toast } from "sonner";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";

interface BookingCardProps {
  booking: {
    id: string;
    date: string;
    numberOfGuests: number;
    totalPrice: number;
    status: "PENDING" | "CONFIRMED" | "REJECTED" | "COMPLETED" | "CANCELLED";
    notes?: string | null;
    tour: {
      id: string;
      title: string;
      slug: string;
      city: string;
      meetingPoint?: string | null;
      durationMin?: number | null;
      priceCents?: number | null;
      images: { url: string }[];
      createdBy: {
        id: string;
        name: string | null;
        email: string;
        image: string | null;
      };
    };
    user: {
      id: string;
      name: string | null;
      email: string;
      image: string | null;
    };
  };
  currentUserId: string;
  onUpdate?: () => void;
}

export function BookingCard({
  booking,
  currentUserId,
  onUpdate,
}: BookingCardProps) {
  const [isUpdating, setIsUpdating] = useState(false);
  const isGuide = booking.tour.createdBy.id === currentUserId;
  const isTourist = booking.user.id === currentUserId;

  const handleUpdateStatus = async (status: "CONFIRMED" | "REJECTED") => {
    setIsUpdating(true);
    try {
      const response = await fetch(`/api/bookings/${booking.id}`, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ status }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Failed to update booking");
      }

      toast.success(data.message || `Booking ${status.toLowerCase()}`);
      onUpdate?.();
    } catch (error) {
      console.error("Error updating booking:", error);
      toast.error(
        error instanceof Error ? error.message : "Failed to update booking"
      );
    } finally {
      setIsUpdating(false);
    }
  };

  const handleCompleteBooking = async () => {
    setIsUpdating(true);
    try {
      const response = await fetch(`/api/bookings/${booking.id}/complete`, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
        },
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Failed to complete booking");
      }

      toast.success(data.message || "Booking marked as completed!");
      onUpdate?.();
    } catch (error) {
      console.error("Error completing booking:", error);
      toast.error(
        error instanceof Error ? error.message : "Failed to complete booking"
      );
    } finally {
      setIsUpdating(false);
    }
  };

  const handleCancelBooking = async () => {
    setIsUpdating(true);
    try {
      const response = await fetch(`/api/bookings/${booking.id}/cancel`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Failed to cancel booking");
      }

      toast.success(data.message || "Booking cancelled successfully");
      onUpdate?.();
    } catch (error) {
      console.error("Error cancelling booking:", error);
      toast.error(
        error instanceof Error ? error.message : "Failed to cancel booking"
      );
    } finally {
      setIsUpdating(false);
    }
  };

  const getStatusBadge = () => {
    switch (booking.status) {
      case "CONFIRMED":
        return (
          <Badge className="bg-green-500">
            <CheckCircle2 className="w-3 h-3 mr-1" />
            Confirmed
          </Badge>
        );
      case "COMPLETED":
        return (
          <Badge className="bg-blue-500">
            <CheckCircle2 className="w-3 h-3 mr-1" />
            Completed
          </Badge>
        );
      case "REJECTED":
        return (
          <Badge variant="destructive">
            <XCircle className="w-3 h-3 mr-1" />
            Rejected
          </Badge>
        );
      case "CANCELLED":
        return (
          <Badge variant="secondary" className="bg-gray-500 text-white">
            <Ban className="w-3 h-3 mr-1" />
            Cancelled
          </Badge>
        );
      case "PENDING":
        return (
          <Badge variant="secondary">
            <AlertCircle className="w-3 h-3 mr-1" />
            Pending
          </Badge>
        );
    }
  };

  const bookingDate = new Date(booking.date);
  // const isPastDate = bookingDate < new Date();

  return (
    <Card>
      <CardHeader className="flex flex-row items-start gap-4 space-y-0 pb-4">
        <Link
          href={`/tours/${booking.tour.slug}`}
          className="relative w-24 h-24 shrink-0 rounded-lg overflow-hidden"
        >
          <Image
            src={booking.tour.images[0]?.url || "/placeholder-tour.jpg"}
            alt={booking.tour.title}
            fill
            className="object-cover hover:scale-105 transition-transform"
          />
        </Link>

        <div className="flex-1 space-y-2">
          <div className="flex items-start justify-between gap-2">
            <Link
              href={`/tours/${booking.tour.slug}`}
              className="font-semibold text-lg hover:underline"
            >
              {booking.tour.title}
            </Link>
            {getStatusBadge()}
          </div>

          <div className="flex items-center gap-2 text-sm text-muted-foreground">
            <MapPin className="w-4 h-4" />
            {booking.tour.city}
          </div>
        </div>
      </CardHeader>

      <CardContent className="space-y-4">
        {/* Booking Details */}
        <div className="grid grid-cols-2 gap-4 text-sm">
          <div className="flex items-center gap-2">
            <Calendar className="w-4 h-4 text-muted-foreground" />
            <span>{format(bookingDate, "PPP")}</span>
          </div>
          <div className="flex items-center gap-2">
            <Users className="w-4 h-4 text-muted-foreground" />
            <span>
              {booking.numberOfGuests} guest
              {booking.numberOfGuests !== 1 ? "s" : ""}
            </span>
          </div>
          {booking.tour.durationMin && (
            <div className="flex items-center gap-2">
              <Clock className="w-4 h-4 text-muted-foreground" />
              <span>{booking.tour.durationMin} minutes</span>
            </div>
          )}
          <div className="flex items-center gap-2 font-semibold">
            <span>CHF {(booking.totalPrice / 100).toFixed(2)}</span>
          </div>
        </div>

        {/* Tourist/Guide Info */}
        <div className="flex items-center gap-3 pt-2">
          <Avatar>
            <AvatarImage
              src={
                isGuide
                  ? booking.user.image || undefined
                  : booking.tour.createdBy.image || undefined
              }
            />
            <AvatarFallback>
              {isGuide
                ? booking.user.name?.[0] || "T"
                : booking.tour.createdBy.name?.[0] || "G"}
            </AvatarFallback>
          </Avatar>
          <div>
            <Link 
              href={`/users/${isGuide ? booking.user.id : booking.tour.createdBy.id}`}
              className="text-sm font-medium hover:text-blue-600 hover:underline"
            >
              {isGuide ? booking.user.name || "Tourist" : booking.tour.createdBy.name || "Guide"}
            </Link>
            <p className="text-xs text-muted-foreground">
              {isGuide ? "Tourist" : "Tour Guide"}
            </p>
          </div>
        </div>

        {/* Notes */}
        {booking.notes && (
          <div className="bg-muted p-3 rounded-lg text-sm">
            <p className="font-medium mb-1">Special Requests:</p>
            <p className="text-muted-foreground">{booking.notes}</p>
          </div>
        )}

        {/* Meeting Point */}
        {booking.status === "CONFIRMED" && booking.tour.meetingPoint && (
          <div className="bg-blue-50 dark:bg-blue-950 p-3 rounded-lg text-sm">
            <p className="font-medium mb-1 flex items-center gap-2">
              <MapPin className="w-4 h-4" />
              Meeting Point:
            </p>
            <p className="text-muted-foreground">{booking.tour.meetingPoint}</p>
          </div>
        )}

        {/* Action Buttons for Guides */}
        {isGuide && booking.status === "PENDING" && (
          <div className="flex gap-2 pt-2">
            <Button
              onClick={() => handleUpdateStatus("CONFIRMED")}
              disabled={isUpdating}
              className="flex-1"
            >
              {isUpdating ? (
                <Loader2 className="w-4 h-4 animate-spin mr-2" />
              ) : (
                <CheckCircle2 className="w-4 h-4 mr-2" />
              )}
              Confirm
            </Button>
            <Button
              onClick={() => handleUpdateStatus("REJECTED")}
              disabled={isUpdating}
              variant="outline"
              className="flex-1"
            >
              {isUpdating ? (
                <Loader2 className="w-4 h-4 animate-spin mr-2" />
              ) : (
                <XCircle className="w-4 h-4 mr-2" />
              )}
              Reject
            </Button>
          </div>
        )}

        {/* Complete Button for Guides */}
        {isGuide && booking.status === "CONFIRMED" && (
          <div className="pt-2">
            <Button
              onClick={handleCompleteBooking}
              disabled={isUpdating}
              className="w-full"
            >
              {isUpdating ? (
                <Loader2 className="w-4 h-4 animate-spin mr-2" />
              ) : (
                <CheckCircle2 className="w-4 h-4 mr-2" />
              )}
              Mark as Completed
            </Button>
            <p className="text-xs text-muted-foreground text-center mt-2">
              This allows the tourist to leave a review
            </p>
          </div>
        )}

        {/* Review Button for Tourists */}
        {isTourist && booking.status === "COMPLETED" && (
          <Link href={`/tours/${booking.tour.slug}?review=true`}>
            <Button variant="outline" className="w-full">
              Leave a Review
            </Button>
          </Link>
        )}

        {/* Info for tourists with confirmed bookings that aren't completed yet */}
        {isTourist && booking.status === "CONFIRMED" && (
          <div className="bg-blue-50 dark:bg-blue-950 p-3 rounded-lg text-sm">
            <p className="text-muted-foreground">
              Waiting for guide to mark this tour as completed. You&apos;ll be able to leave a review once it&apos;s marked complete.
            </p>
          </div>
        )}

        {/* Cancel Button - Available for both tourist and guide */}
        {(booking.status === "PENDING" || booking.status === "CONFIRMED") && (
          <AlertDialog>
            <AlertDialogTrigger asChild>
              <Button 
                variant="outline" 
                className="w-full text-destructive hover:bg-destructive/10"
                disabled={isUpdating}
              >
                {isUpdating ? (
                  <Loader2 className="w-4 h-4 animate-spin mr-2" />
                ) : (
                  <Ban className="w-4 h-4 mr-2" />
                )}
                Cancel Booking
              </Button>
            </AlertDialogTrigger>
            <AlertDialogContent>
              <AlertDialogHeader>
                <AlertDialogTitle>Cancel this booking?</AlertDialogTitle>
                <AlertDialogDescription>
                  This action cannot be undone. Both the tourist and guide will be
                  notified of the cancellation.
                </AlertDialogDescription>
              </AlertDialogHeader>
              <AlertDialogFooter>
                <AlertDialogCancel>Keep Booking</AlertDialogCancel>
                <AlertDialogAction
                  onClick={handleCancelBooking}
                  className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                >
                  Cancel Booking
                </AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>
        )}
      </CardContent>
    </Card>
  );
}
