"use client";

import { useState, useEffect, useCallback } from "react";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardFooter,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { cn, formatTime, formatCurrency, formatDate } from "@/lib/utils";
import type { SelectedSlot } from "./booking-calendar";

interface Client {
  id: string;
  firstName: string;
  lastName: string;
  email: string | null;
  phone: string | null;
  level: string | null;
  memberships: Array<{
    id: string;
    status: string;
    remainingHours: number | null;
    plan: {
      id: string;
      name: string;
      discountPercent: number | null;
    };
  }>;
}

interface ClientsResponse {
  data: Client[];
  pagination: {
    total: number;
    limit: number;
    offset: number;
    hasMore: boolean;
  };
}

interface BookingInfo {
  id: string;
  startTime: string;
  endTime: string;
  status: string;
  totalPrice: number;
  paymentType: string;
  client: {
    id: string;
    firstName: string;
    lastName: string;
    email: string | null;
    phone: string | null;
  };
  court: {
    id: string;
    name: string;
    type: string;
  };
}

interface BookingDialogProps {
  courtId: string;
  date: string;
  slot: SelectedSlot;
  onClose: () => void;
  onBookingCreated?: () => void;
  onBookingCancelled?: () => void;
}

export function BookingDialog({
  courtId,
  date,
  slot,
  onClose,
  onBookingCreated,
  onBookingCancelled,
}: BookingDialogProps) {
  const [searchQuery, setSearchQuery] = useState("");
  const [clients, setClients] = useState<Client[]>([]);
  const [selectedClient, setSelectedClient] = useState<Client | null>(null);
  const [loadingClients, setLoadingClients] = useState(false);
  const [loadingBooking, setLoadingBooking] = useState(false);
  const [booking, setBooking] = useState<BookingInfo | null>(null);
  const [loadingBookingInfo, setLoadingBookingInfo] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [creatingBooking, setCreatingBooking] = useState(false);
  const [cancellingBooking, setCancellingBooking] = useState(false);

  // Parse slot time to Date for display
  const [hours, minutes] = slot.time.split(":").map(Number);
  const slotDate = new Date(date);
  slotDate.setHours(hours, minutes, 0, 0);

  // Fetch booking info if slot is not available
  const fetchBookingInfo = useCallback(async () => {
    if (!slot.bookingId) return;

    setLoadingBookingInfo(true);
    try {
      const response = await fetch(`/api/bookings/${slot.bookingId}`);
      if (!response.ok) {
        throw new Error("Error loading booking");
      }
      const data = await response.json();
      setBooking(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Unknown error");
    } finally {
      setLoadingBookingInfo(false);
    }
  }, [slot.bookingId]);

  // Fetch clients based on search
  const fetchClients = useCallback(async (search: string) => {
    if (!search || search.trim().length < 2) {
      setClients([]);
      return;
    }

    setLoadingClients(true);
    try {
      const response = await fetch(
        `/api/clients?search=${encodeURIComponent(search)}&limit=10`
      );
      if (!response.ok) {
        throw new Error("Error searching players");
      }
      const data: ClientsResponse = await response.json();
      setClients(data.data);
    } catch (err) {
      console.error("Error fetching clients:", err);
      setClients([]);
    } finally {
      setLoadingClients(false);
    }
  }, []);

  // Load booking info on mount if slot is booked
  useEffect(() => {
    if (!slot.available && slot.bookingId) {
      fetchBookingInfo();
    }
  }, [slot.available, slot.bookingId, fetchBookingInfo]);

  // Debounce client search
  useEffect(() => {
    const timer = setTimeout(() => {
      fetchClients(searchQuery);
    }, 300);

    return () => clearTimeout(timer);
  }, [searchQuery, fetchClients]);

  // Handle booking creation
  const handleCreateBooking = async () => {
    if (!selectedClient) return;

    setCreatingBooking(true);
    setError(null);

    try {
      // Calculate end time (1 hour later)
      const endDate = new Date(slotDate);
      endDate.setHours(endDate.getHours() + 1);

      const response = await fetch("/api/bookings", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          courtId,
          clientId: selectedClient.id,
          startTime: slotDate.toISOString(),
          endTime: endDate.toISOString(),
          paymentType: "CASH",
        }),
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || "Error creating booking");
      }

      onBookingCreated?.();
      onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Error creating booking");
    } finally {
      setCreatingBooking(false);
    }
  };

  // Handle booking cancellation
  const handleCancelBooking = async () => {
    if (!slot.bookingId) return;

    setCancellingBooking(true);
    setError(null);

    try {
      const response = await fetch(`/api/bookings/${slot.bookingId}`, {
        method: "DELETE",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          cancelReason: "Cancelled by administrator",
        }),
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || "Error cancelling booking");
      }

      onBookingCancelled?.();
      onClose();
    } catch (err) {
      setError(
        err instanceof Error ? err.message : "Error cancelling booking"
      );
    } finally {
      setCancellingBooking(false);
    }
  };

  // Handle click outside to close
  const handleOverlayClick = (e: React.MouseEvent) => {
    if (e.target === e.currentTarget) {
      onClose();
    }
  };

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
      onClick={handleOverlayClick}
    >
      <Card className="w-full max-w-md max-h-[90vh] overflow-hidden flex flex-col">
        <CardHeader className="pb-4">
          <div className="flex items-center justify-between">
            <CardTitle className="text-lg">
              {slot.available ? "New Booking" : "Booking Details"}
            </CardTitle>
            <button
              onClick={onClose}
              className="rounded-full p-1 hover:bg-primary-100 transition-colors"
            >
              <svg
                className="h-5 w-5 text-primary-500"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M6 18L18 6M6 6l12 12"
                />
              </svg>
            </button>
          </div>
          <div className="text-sm text-primary-600 space-y-1 mt-2">
            <p>
              <span className="font-medium">Court:</span> {slot.courtName}
            </p>
            <p>
              <span className="font-medium">Date:</span> {formatDate(date)}
            </p>
            <p>
              <span className="font-medium">Time:</span> {formatTime(slotDate)}
            </p>
            <p>
              <span className="font-medium">Price:</span>{" "}
              {formatCurrency(slot.price)}
            </p>
          </div>
        </CardHeader>

        <CardContent className="flex-1 overflow-y-auto">
          {error && (
            <div className="mb-4 rounded-md bg-red-50 border border-red-200 p-3 text-sm text-red-700">
              {error}
            </div>
          )}

          {/* Available slot - show client search */}
          {slot.available && (
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-primary-700 mb-2">
                  Search Player
                </label>
                <Input
                  type="text"
                  placeholder="Name, email or phone..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  autoFocus
                />
              </div>

              {/* Client search results */}
              <div className="space-y-2">
                {loadingClients && (
                  <div className="flex items-center justify-center py-4">
                    <div className="h-5 w-5 animate-spin rounded-full border-2 border-primary-200 border-t-primary-600" />
                  </div>
                )}

                {!loadingClients && searchQuery.length >= 2 && clients.length === 0 && (
                  <p className="text-sm text-primary-500 text-center py-4">
                    No players found.
                  </p>
                )}

                {!loadingClients &&
                  clients.map((client) => (
                    <button
                      key={client.id}
                      type="button"
                      onClick={() => setSelectedClient(client)}
                      className={cn(
                        "w-full rounded-md border p-3 text-left transition-all",
                        "hover:border-primary-400 hover:bg-primary-50",
                        selectedClient?.id === client.id
                          ? "border-primary-500 bg-primary-50 ring-2 ring-primary-500"
                          : "border-primary-200 bg-white"
                      )}
                    >
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="font-medium text-primary-800">
                            {client.firstName} {client.lastName}
                          </p>
                          <p className="text-xs text-primary-500">
                            {client.email || client.phone || "No contact"}
                          </p>
                        </div>
                        {client.memberships.length > 0 && (
                          <span className="text-xs bg-accent-100 text-accent-700 px-2 py-1 rounded-full">
                            {client.memberships[0].plan.name}
                          </span>
                        )}
                      </div>
                    </button>
                  ))}
              </div>

              {/* Selected client summary */}
              {selectedClient && (
                <div className="mt-4 rounded-md border border-accent-200 bg-accent-50 p-3">
                  <p className="text-sm font-medium text-accent-800">
                    Selected player:
                  </p>
                  <p className="text-sm text-accent-700">
                    {selectedClient.firstName} {selectedClient.lastName}
                  </p>
                  {selectedClient.memberships.length > 0 && (
                    <p className="text-xs text-accent-600 mt-1">
                      Membership: {selectedClient.memberships[0].plan.name}
                      {selectedClient.memberships[0].remainingHours !== null &&
                        selectedClient.memberships[0].remainingHours > 0 && (
                          <span className="ml-2">
                            ({selectedClient.memberships[0].remainingHours}h remaining)
                          </span>
                        )}
                    </p>
                  )}
                </div>
              )}
            </div>
          )}

          {/* Booked slot - show booking info */}
          {!slot.available && (
            <div className="space-y-4">
              {loadingBookingInfo && (
                <div className="flex items-center justify-center py-8">
                  <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary-200 border-t-primary-600" />
                </div>
              )}

              {!loadingBookingInfo && booking && (
                <div className="space-y-4">
                  <div className="rounded-md border border-primary-200 bg-primary-50 p-4 space-y-3">
                    <div>
                      <p className="text-xs text-primary-500">Player</p>
                      <p className="font-medium text-primary-800">
                        {booking.client.firstName} {booking.client.lastName}
                      </p>
                      {booking.client.phone && (
                        <p className="text-sm text-primary-600">
                          {booking.client.phone}
                        </p>
                      )}
                      {booking.client.email && (
                        <p className="text-sm text-primary-600">
                          {booking.client.email}
                        </p>
                      )}
                    </div>

                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <p className="text-xs text-primary-500">Status</p>
                        <p
                          className={cn(
                            "text-sm font-medium",
                            booking.status === "CONFIRMED" && "text-accent-600",
                            booking.status === "PENDING" && "text-yellow-600",
                            booking.status === "CANCELLED" && "text-red-600"
                          )}
                        >
                          {booking.status === "CONFIRMED" && "Confirmed"}
                          {booking.status === "PENDING" && "Pending"}
                          {booking.status === "CANCELLED" && "Cancelled"}
                          {booking.status === "COMPLETED" && "Completed"}
                          {booking.status === "NO_SHOW" && "No Show"}
                        </p>
                      </div>
                      <div>
                        <p className="text-xs text-primary-500">Payment Type</p>
                        <p className="text-sm text-primary-800">
                          {booking.paymentType === "CASH" && "Cash"}
                          {booking.paymentType === "CARD" && "Card"}
                          {booking.paymentType === "TRANSFER" && "Transfer"}
                          {booking.paymentType === "MEMBERSHIP" && "Membership"}
                          {booking.paymentType === "FREE" && "Free"}
                        </p>
                      </div>
                    </div>

                    <div>
                      <p className="text-xs text-primary-500">Total</p>
                      <p className="text-lg font-semibold text-primary-800">
                        {formatCurrency(Number(booking.totalPrice))}
                      </p>
                    </div>
                  </div>
                </div>
              )}

              {!loadingBookingInfo && !booking && (
                <div className="text-center py-4 text-primary-500">
                  <p>Could not load booking information.</p>
                </div>
              )}
            </div>
          )}
        </CardContent>

        <CardFooter className="border-t border-primary-200 bg-primary-50 pt-4">
          <div className="flex w-full gap-3">
            <Button variant="outline" onClick={onClose} className="flex-1">
              Close
            </Button>

            {slot.available && (
              <Button
                variant="accent"
                onClick={handleCreateBooking}
                disabled={!selectedClient || creatingBooking}
                className="flex-1"
              >
                {creatingBooking ? (
                  <span className="flex items-center gap-2">
                    <div className="h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white" />
                    Creating...
                  </span>
                ) : (
                  "Create Booking"
                )}
              </Button>
            )}

            {!slot.available && booking && booking.status !== "CANCELLED" && (
              <Button
                variant="destructive"
                onClick={handleCancelBooking}
                disabled={cancellingBooking}
                className="flex-1"
              >
                {cancellingBooking ? (
                  <span className="flex items-center gap-2">
                    <div className="h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white" />
                    Cancelling...
                  </span>
                ) : (
                  "Cancel Booking"
                )}
              </Button>
            )}
          </div>
        </CardFooter>
      </Card>
    </div>
  );
}
