import { useState, useEffect } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { queryClient } from "@/client/rpc-client";

export function AdminBookings() {
  const [filterMode, setFilterMode] = useState<"upcoming" | "all" | "date">("upcoming");
  const [selectedDate, setSelectedDate] = useState(new Date().toISOString().split('T')[0]);
  const [selectedPhoto, setSelectedPhoto] = useState<string>("");
  const [showPhotoModal, setShowPhotoModal] = useState(false);
  const [showCancelConfirm, setShowCancelConfirm] = useState<string | null>(null);
  const [showMessageModal, setShowMessageModal] = useState<string | null>(null);
  const [messageText, setMessageText] = useState<string>("");
  const [successMsg, setSuccessMsg] = useState<string>("");
  const [errorMsg, setErrorMsg] = useState<string>("");

  // Auto-clear messages after 5 seconds
  useEffect(() => {
    if (errorMsg) {
      const timer = setTimeout(() => setErrorMsg(""), 5000);
      return () => clearTimeout(timer);
    }
  }, [errorMsg]);

  useEffect(() => {
    if (successMsg) {
      const timer = setTimeout(() => setSuccessMsg(""), 5000);
      return () => clearTimeout(timer);
    }
  }, [successMsg]);

  const { data: bookings, refetch: refetchBookings } = useQuery(
    queryClient.bookings.live.list.experimental_liveOptions()
  );

  const { data: treatments } = useQuery(
    queryClient.treatments.live.list.experimental_liveOptions()
  );

  const { mutate: updateBookingStatus } = useMutation(
    queryClient.bookings.updateStatus.mutationOptions({
      onSuccess: (data, variables) => {
        const statusText = getStatusText(variables.status);
        setSuccessMsg(`Buchung wurde erfolgreich auf "${statusText}" gesetzt.`);
        setShowCancelConfirm(null);
        // Manually refetch bookings to ensure live updates
        refetchBookings();
      },
      onError: (error: any) => {
        setErrorMsg(error?.message || "Fehler beim Aktualisieren der Buchung.");
        setShowCancelConfirm(null);
      }
    })
  );

  const { mutate: sendMessage, isPending: isSendingMessage } = useMutation(
    queryClient.bookings.sendCustomerMessage.mutationOptions({
      onSuccess: () => {
        setSuccessMsg("Nachricht wurde erfolgreich gesendet.");
        setShowMessageModal(null);
        setMessageText("");
      },
      onError: (error: any) => {
        setErrorMsg(error?.message || "Fehler beim Senden der Nachricht.");
      }
    })
  );

  const getTreatmentNames = (booking: any) => {
    // Handle new treatments array structure
    if (booking.treatments && Array.isArray(booking.treatments) && booking.treatments.length > 0) {
      const names = booking.treatments
        .map((t: any) => t.name)
        .filter((name: string) => name && name.trim())
        .join(", ");
      return names || "Keine Behandlung";
    }
    // Fallback to deprecated treatmentId for backward compatibility
    if (booking.treatmentId) {
      return treatments?.find(t => t.id === booking.treatmentId)?.name || "Unbekannte Behandlung";
    }
    return "Keine Behandlung";
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case "pending": return "bg-yellow-100 text-yellow-800";
      case "confirmed": return "bg-green-100 text-green-800";
      case "cancelled": return "bg-red-100 text-red-800";
      case "completed": return "bg-blue-100 text-blue-800";
      default: return "bg-gray-100 text-gray-800";
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case "pending": return "Ausstehend";
      case "confirmed": return "Bestätigt";
      case "cancelled": return "Storniert";
      case "completed": return "Abgeschlossen";
      default: return status;
    }
  };

  const openPhotoModal = (photoData: string) => {
    setSelectedPhoto(photoData);
    setShowPhotoModal(true);
  };

  const closePhotoModal = () => {
    setShowPhotoModal(false);
    setSelectedPhoto("");
  };

  const openMessageModal = (bookingId: string) => {
    setShowMessageModal(bookingId);
    setMessageText("");
  };

  const closeMessageModal = () => {
    setShowMessageModal(null);
    setMessageText("");
  };

  const handleSendMessage = () => {
    if (!showMessageModal || !messageText.trim()) {
      setErrorMsg("Bitte gib eine Nachricht ein.");
      return;
    }
    
    sendMessage({
      sessionId: localStorage.getItem("sessionId") || "",
      bookingId: showMessageModal,
      message: messageText.trim(),
    });
  };

  // Check if booking is in the future
  const isFutureBooking = (appointmentDate: string) => {
    const today = new Date().toISOString().split("T")[0];
    return appointmentDate >= today;
  };

  // Filter bookings based on selected filter mode
  const filteredBookings = bookings?.filter(booking => {
    if (filterMode === "upcoming") {
      // Show all future bookings (not cancelled)
      const bookingDate = new Date(booking.appointmentDate);
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      bookingDate.setHours(0, 0, 0, 0);
      return bookingDate >= today && booking.status !== "cancelled";
    } else if (filterMode === "date") {
      // Show bookings for specific date
      return booking.appointmentDate === selectedDate;
    } else {
      // Show all bookings
      return true;
    }
  }).sort((a, b) => {
    if (a.appointmentDate === b.appointmentDate) {
      return a.appointmentTime.localeCompare(b.appointmentTime);
    }
    return a.appointmentDate.localeCompare(b.appointmentDate);
  });

  const upcomingBookings = bookings?.filter(booking => {
    const bookingDate = new Date(booking.appointmentDate);
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    return bookingDate >= today && booking.status !== "cancelled";
  }).sort((a, b) => {
    if (a.appointmentDate === b.appointmentDate) {
      return a.appointmentTime.localeCompare(b.appointmentTime);
    }
    return a.appointmentDate.localeCompare(b.appointmentDate);
  });

  return (
    <div className="max-w-6xl mx-auto">
      {/* Success/Error Messages */}
      {(successMsg || errorMsg) && (
        <div className="mb-4">
          {errorMsg && (
            <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md">
              <div className="flex items-center">
                <svg className="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                </svg>
                <span className="font-medium">Fehler:</span>
                <span className="ml-1">{errorMsg}</span>
              </div>
            </div>
          )}
          {successMsg && (
            <div className="bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-md">
              <div className="flex items-center">
                <svg className="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                </svg>
                <span className="font-medium">Erfolg:</span>
                <span className="ml-1">{successMsg}</span>
              </div>
            </div>
          )}
        </div>
      )}

      {/* Quick Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
        <div className="bg-white rounded-lg shadow p-4">
          <div className="text-2xl font-bold text-pink-600">
            {bookings?.filter(b => b.status === "pending").length || 0}
          </div>
          <div className="text-sm text-gray-600">Pending Approval</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4">
          <div className="text-2xl font-bold text-green-600">
            {bookings?.filter(b => b.status === "confirmed").length || 0}
          </div>
          <div className="text-sm text-gray-600">Confirmed</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4">
          <div className="text-2xl font-bold text-blue-600">
            {upcomingBookings?.length || 0}
          </div>
          <div className="text-sm text-gray-600">Upcoming</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4">
          <div className="text-2xl font-bold text-gray-600">
            {bookings?.length || 0}
          </div>
          <div className="text-sm text-gray-600">Total Bookings</div>
        </div>
      </div>

      {/* Filter Section */}
      <div className="bg-white rounded-lg shadow p-4 mb-6">
        <div className="flex flex-col space-y-4">
          <div className="flex items-center space-x-2">
            <label className="text-sm font-medium text-gray-700">Filter:</label>
            <button
              onClick={() => setFilterMode("upcoming")}
              className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
                filterMode === "upcoming"
                  ? "bg-pink-600 text-white"
                  : "bg-gray-100 text-gray-700 hover:bg-gray-200"
              }`}
            >
              Zukünftige
            </button>
            <button
              onClick={() => setFilterMode("all")}
              className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
                filterMode === "all"
                  ? "bg-pink-600 text-white"
                  : "bg-gray-100 text-gray-700 hover:bg-gray-200"
              }`}
            >
              Alle
            </button>
            <button
              onClick={() => setFilterMode("date")}
              className={`px-4 py-2 rounded-md text-sm font-medium transition-colors ${
                filterMode === "date"
                  ? "bg-pink-600 text-white"
                  : "bg-gray-100 text-gray-700 hover:bg-gray-200"
              }`}
            >
              Datum
            </button>
          </div>
          
          {filterMode === "date" && (
            <div className="flex items-center space-x-4 pl-16">
              <label className="text-sm font-medium text-gray-700">Wähle Datum:</label>
              <input
                type="date"
                value={selectedDate}
                onChange={(e) => setSelectedDate(e.target.value)}
                className="p-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-pink-500 focus:border-pink-500"
              />
            </div>
          )}
        </div>
      </div>

      {/* Bookings Table */}
      <div className="bg-white rounded-lg shadow-lg overflow-hidden">
        <table className="w-full">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Customer
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Treatment
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Date & Time
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Inspiration
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Status
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Actions
              </th>
            </tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {filteredBookings?.map((booking) => (
              <tr key={booking.id} className="hover:bg-gray-50">
                <td className="px-6 py-4 whitespace-nowrap">
                  <div>
                    <div className="text-sm font-medium text-gray-900">{booking.customerName}</div>
                    <div className="text-sm text-gray-500">{booking.customerEmail || '—'}</div>
                    <div className="text-sm text-gray-500">{booking.customerPhone || '—'}</div>
                  </div>
                </td>
                <td className="px-6 py-4">
                  <div className="text-sm text-gray-900">{getTreatmentNames(booking)}</div>
                  {booking.notes && (
                     <div className="text-sm text-gray-500">Notizen: {booking.notes}</div>
                  )}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                  <div>{new Date(booking.appointmentDate).toLocaleDateString()}</div>
                  <div>{booking.appointmentTime}</div>
                  {booking.slotId && (
                    <div className="text-xs text-gray-500">Slot-ID: {booking.slotId}</div>
                  )}
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  {booking.inspirationPhoto ? (
                    <button
                      onClick={() => openPhotoModal(booking.inspirationPhoto!)}
                      className="block"
                    >
                      <img
                        src={booking.inspirationPhoto}
                        alt="Inspiration"
                        className="w-12 h-12 object-cover rounded-lg border border-gray-200 hover:border-pink-300 cursor-pointer"
                      />
                    </button>
                  ) : (
                    <span className="text-gray-400 text-sm">Kein Foto</span>
                  )}
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${getStatusColor(booking.status)}`}>
                    {booking.status}
                  </span>
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                  <div className="flex flex-col space-y-2">
                    <div className="flex space-x-2">
                      {booking.status === "pending" && (
                        <>
                          <button
                            onClick={() => updateBookingStatus({ sessionId: localStorage.getItem("sessionId") || "", id: booking.id, status: "confirmed" })}
                            className="text-green-600 hover:text-green-900"
                          >
                            Confirm
                          </button>
                          <button
                            onClick={() => setShowCancelConfirm(booking.id)}
                            className="text-red-600 hover:text-red-900"
                          >
                            Cancel
                          </button>
                        </>
                      )}
                      {booking.status === "confirmed" && (
                        <>
                          <button
                            onClick={() => updateBookingStatus({ sessionId: localStorage.getItem("sessionId") || "", id: booking.id, status: "completed" })}
                            className="text-blue-600 hover:text-blue-900"
                          >
                            Complete
                          </button>
                          <button
                            onClick={() => setShowCancelConfirm(booking.id)}
                            className="text-red-600 hover:text-red-900"
                          >
                            Cancel
                          </button>
                        </>
                      )}
                      {(booking.status === "cancelled" || booking.status === "completed") && (
                        <button
                          onClick={() => updateBookingStatus({ sessionId: localStorage.getItem("sessionId") || "", id: booking.id, status: "confirmed" })}
                          className="text-green-600 hover:text-green-900"
                        >
                          Reactivate
                        </button>
                      )}
                    </div>
                    {/* Show message button for future bookings with email */}
                    {isFutureBooking(booking.appointmentDate) && booking.customerEmail && (
                      <button
                        onClick={() => openMessageModal(booking.id)}
                        className="text-pink-600 hover:text-pink-900 text-left"
                        title="Nachricht an Kunden senden"
                      >
                        💬 Nachricht
                      </button>
                    )}
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        
        {!filteredBookings?.length && (
          <div className="text-center py-8 text-gray-500">
            {filterMode === "date"
              ? `Keine Buchungen für ${new Date(selectedDate).toLocaleDateString()} gefunden`
              : filterMode === "upcoming"
              ? "Keine zukünftigen Buchungen verfügbar."
              : "Keine Buchungen verfügbar."
            }
          </div>
        )}
      </div>

      {/* Photo Modal */}
      {showPhotoModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 max-w-2xl max-h-[90vh] overflow-auto">
            <div className="flex justify-between items-center mb-4">
              <h3 className="text-lg font-semibold text-gray-900">Inspiration Foto</h3>
              <button
                onClick={closePhotoModal}
                className="text-gray-400 hover:text-gray-600 text-2xl"
              >
                ×
              </button>
            </div>
            <div className="flex justify-center">
              <img
                src={selectedPhoto}
                alt="Inspiration Foto"
                className="max-w-full max-h-[70vh] object-contain rounded-lg"
              />
            </div>
            <div className="mt-4 text-center">
              <button
                onClick={closePhotoModal}
                className="bg-pink-600 text-white px-4 py-2 rounded-md hover:bg-pink-700"
              >
                Schließen
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Cancel Confirmation Modal */}
      {showCancelConfirm && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 max-w-md w-full mx-4">
            <h3 className="text-lg font-medium text-gray-900 mb-4">Buchung stornieren</h3>
            <p className="text-gray-600 mb-6">
              Bist du sicher, dass du diese Buchung stornieren möchtest? Diese Aktion kann nicht rückgängig gemacht werden.
            </p>
            <div className="flex space-x-3">
              <button
                onClick={() => {
                  const sessionId = localStorage.getItem("sessionId") || "";
                  updateBookingStatus({ sessionId, id: showCancelConfirm, status: "cancelled" });
                }}
                className="flex-1 bg-red-600 text-white py-2 px-4 rounded-md hover:bg-red-700 transition-colors"
              >
                Ja, stornieren
              </button>
              <button
                onClick={() => setShowCancelConfirm(null)}
                className="flex-1 bg-gray-200 text-gray-800 py-2 px-4 rounded-md hover:bg-gray-300 transition-colors"
              >
                Abbrechen
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Message Modal */}
      {showMessageModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 max-w-2xl w-full mx-4">
            <div className="flex justify-between items-center mb-4">
              <h3 className="text-lg font-medium text-gray-900">Nachricht an Kunden senden</h3>
              <button
                onClick={closeMessageModal}
                className="text-gray-400 hover:text-gray-600 text-2xl"
                disabled={isSendingMessage}
              >
                ×
              </button>
            </div>
            
            {(() => {
              const booking = bookings?.find(b => b.id === showMessageModal);
              if (!booking) return null;
              
              // Calculate totals for multiple treatments
              const hasTreatments = booking.treatments && Array.isArray(booking.treatments) && booking.treatments.length > 0;
              const totalDuration = hasTreatments 
                ? booking.treatments.reduce((sum: number, t: any) => sum + (t.duration || 0), 0)
                : (booking.bookedDurationMinutes || 0);
              const totalPrice = hasTreatments
                ? booking.treatments.reduce((sum: number, t: any) => sum + (t.price || 0), 0)
                : 0;
              
              return (
                <div className="mb-4 bg-gray-50 p-4 rounded-md">
                  <p className="text-sm text-gray-700">
                    <strong>Kunde:</strong> {booking.customerName}
                  </p>
                  <p className="text-sm text-gray-700">
                    <strong>E-Mail:</strong> {booking.customerEmail}
                  </p>
                  <p className="text-sm text-gray-700">
                    <strong>Termin:</strong> {new Date(booking.appointmentDate).toLocaleDateString()} um {booking.appointmentTime}
                  </p>
                  <div className="text-sm text-gray-700 mt-2">
                    <strong>Behandlungen:</strong>
                    {hasTreatments ? (
                      <div className="mt-1 ml-2">
                        {booking.treatments.map((treatment: any, index: number) => (
                          <div key={index} className="mb-1">
                            • {treatment.name} ({treatment.duration} Min., {treatment.price}€)
                          </div>
                        ))}
                        {booking.treatments.length > 1 && (
                          <div className="mt-2 pt-2 border-t border-gray-300 font-semibold">
                            Gesamt: {totalDuration} Min., {totalPrice.toFixed(2)}€
                          </div>
                        )}
                      </div>
                    ) : booking.treatmentId ? (
                      <div className="mt-1 ml-2">
                        • {treatments?.find(t => t.id === booking.treatmentId)?.name || "Unbekannte Behandlung"}
                      </div>
                    ) : (
                      <span className="ml-2 text-gray-500">Keine Behandlung</span>
                    )}
                  </div>
                </div>
              );
            })()}
            
            <div className="mb-4">
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Deine Nachricht
              </label>
              <textarea
                value={messageText}
                onChange={(e) => setMessageText(e.target.value)}
                placeholder="Schreibe hier deine Nachricht an den Kunden..."
                rows={6}
                maxLength={5000}
                className="w-full p-3 border border-gray-300 rounded-md focus:ring-2 focus:ring-pink-500 focus:border-pink-500"
                disabled={isSendingMessage}
              />
              <p className="text-xs text-gray-500 mt-1">
                {messageText.length} / 5000 Zeichen
              </p>
            </div>
            
            <div className="bg-blue-50 border-l-4 border-blue-400 p-3 mb-4">
              <p className="text-sm text-blue-700">
                💡 <strong>Hinweis:</strong> Der Kunde kann direkt auf diese E-Mail antworten. Die Antwort geht an die in den Einstellungen hinterlegte Admin-E-Mail-Adresse.
              </p>
            </div>
            
            <div className="flex space-x-3">
              <button
                onClick={handleSendMessage}
                disabled={isSendingMessage || !messageText.trim()}
                className="flex-1 bg-pink-600 text-white py-2 px-4 rounded-md hover:bg-pink-700 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed"
              >
                {isSendingMessage ? "Wird gesendet..." : "Nachricht senden"}
              </button>
              <button
                onClick={closeMessageModal}
                disabled={isSendingMessage}
                className="flex-1 bg-gray-200 text-gray-800 py-2 px-4 rounded-md hover:bg-gray-300 transition-colors disabled:bg-gray-100 disabled:cursor-not-allowed"
              >
                Abbrechen
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}