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

export function AdminCalendar() {
  const [currentMonth, setCurrentMonth] = useState(new Date());
  const [selectedDate, setSelectedDate] = useState<string | null>(null);

  const { data: bookings } = 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()
  );

  const getTreatmentName = (treatmentId: string) => {
    return treatments?.find(t => t.id === treatmentId)?.name || "Unbekannte Behandlung";
  };

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

  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;
    }
  };

  // Filter upcoming bookings (today and future, not cancelled)
  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);
  });

  // Get bookings for a specific date
  const getBookingsForDate = (date: string) => {
    return upcomingBookings?.filter(booking => booking.appointmentDate === date) || [];
  };

  // Calendar generation
  const year = currentMonth.getFullYear();
  const month = currentMonth.getMonth();

  const firstDay = new Date(year, month, 1);
  const lastDay = new Date(year, month + 1, 0);
  const startDate = new Date(firstDay);
  startDate.setDate(startDate.getDate() - firstDay.getDay());

  const calendarDays: Date[] = [];
  const currentDate: Date = new Date(startDate);

  for (let i = 0; i < 42; i++) {
    calendarDays.push(new Date(currentDate));
    currentDate.setDate(currentDate.getDate() + 1);
  }

  const monthNames = [
    "Januar", "Februar", "März", "April", "Mai", "Juni",
    "Juli", "August", "September", "Oktober", "November", "Dezember"
  ];

  const dayNames = ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"];

  const navigateMonth = (direction: 'prev' | 'next') => {
    const newMonth = new Date(currentMonth);
    if (direction === 'prev') {
      newMonth.setMonth(month - 1);
    } else {
      newMonth.setMonth(month + 1);
    }
    setCurrentMonth(newMonth);
    setSelectedDate(null);
  };

  const handleStatusUpdate = (bookingId: string, newStatus: string) => {
    const sessionId = localStorage.getItem('sessionId');
    if (!sessionId) return;

    updateBookingStatus({
      sessionId,
      id: bookingId,
      status: newStatus as "pending" | "confirmed" | "cancelled" | "completed"
    });
  };

  const today = new Date().toISOString().split('T')[0];

  return (
    <div className="max-w-7xl mx-auto">
      <h2 className="text-2xl font-bold text-gray-900 mb-6">Kalender - Bevorstehende Buchungen</h2>

      {/* 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-yellow-600">
            {upcomingBookings?.filter(b => b.status === "pending").length || 0}
          </div>
          <div className="text-sm text-gray-600">Ausstehende Bestätigungen</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4">
          <div className="text-2xl font-bold text-green-600">
            {upcomingBookings?.filter(b => b.status === "confirmed").length || 0}
          </div>
          <div className="text-sm text-gray-600">Bestätigte Termine</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4">
          <div className="text-2xl font-bold text-blue-600">
            {upcomingBookings?.filter(b => b.appointmentDate === today).length || 0}
          </div>
          <div className="text-sm text-gray-600">Heute</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4">
          <div className="text-2xl font-bold text-purple-600">
            {upcomingBookings?.length || 0}
          </div>
          <div className="text-sm text-gray-600">Bevorstehende Termine</div>
        </div>
      </div>

      {/* Calendar */}
      <div className="bg-white rounded-lg shadow-lg overflow-hidden">
        {/* Calendar Header */}
        <div className="flex items-center justify-between p-4 bg-pink-50 border-b">
          <button
            onClick={() => navigateMonth('prev')}
            className="p-2 hover:bg-pink-100 rounded-md transition-colors"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
            </svg>
          </button>
          
          <h3 className="text-xl font-semibold text-gray-900">
            {monthNames[month]} {year}
          </h3>
          
          <button
            onClick={() => navigateMonth('next')}
            className="p-2 hover:bg-pink-100 rounded-md transition-colors"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
            </svg>
          </button>
        </div>

        {/* Calendar Grid */}
        <div className="grid grid-cols-7">
          {/* Day headers */}
          {dayNames.map(day => (
            <div key={day} className="p-3 text-center font-semibold text-gray-600 bg-gray-50 border-b">
              {day}
            </div>
          ))}

          {/* Calendar days */}
          {calendarDays.map((date, index) => {
            const dateStr = date.toISOString().split('T')[0];
            const isCurrentMonth = date.getMonth() === month;
            const isToday = dateStr === today;
            const isSelected = selectedDate === dateStr;
            const dayBookings = getBookingsForDate(dateStr);

            return (
              <div
                key={index}
                className={`min-h-[120px] p-2 border-r border-b cursor-pointer hover:bg-gray-50 transition-colors ${
                  !isCurrentMonth ? 'bg-gray-50 text-gray-400' : 'bg-white'
                } ${isToday ? 'bg-pink-50' : ''} ${isSelected ? 'bg-pink-100' : ''}`}
                onClick={() => setSelectedDate(isSelected ? null : dateStr)}
              >
                <div className={`text-sm font-medium mb-1 ${
                  isToday ? 'text-pink-600' : isCurrentMonth ? 'text-gray-900' : 'text-gray-400'
                }`}>
                  {date.getDate()}
                </div>
                
                {/* Show bookings for this day */}
                <div className="space-y-1">
                  {dayBookings.slice(0, 2).map(booking => (
                    <div
                      key={booking.id}
                      className={`text-xs p-1 rounded border-l-2 ${getStatusColor(booking.status)} truncate`}
                      title={`${booking.customerName} - ${getTreatmentName(booking.treatmentId)} (${booking.appointmentTime})`}
                    >
                      <div className="font-medium">{booking.appointmentTime}</div>
                      <div className="truncate">{booking.customerName}</div>
                    </div>
                  ))}
                  {dayBookings.length > 2 && (
                    <div className="text-xs text-gray-500 font-medium">
                      +{dayBookings.length - 2} weitere
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Selected Date Details */}
      {selectedDate && (
        <div className="mt-6 bg-white rounded-lg shadow-lg p-6">
          <div className="flex justify-between items-center mb-4">
            <h3 className="text-lg font-semibold text-gray-900">
              Termine für {new Date(selectedDate).toLocaleDateString('de-DE', {
                weekday: 'long',
                year: 'numeric',
                month: 'long',
                day: 'numeric'
              })}
            </h3>
            <button
              onClick={() => setSelectedDate(null)}
              className="text-gray-400 hover:text-gray-600"
            >
              <svg className="w-5 h-5" 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>

          {getBookingsForDate(selectedDate).length === 0 ? (
            <p className="text-gray-500 text-center py-8">Keine Termine für diesen Tag</p>
          ) : (
            <div className="space-y-4">
              {getBookingsForDate(selectedDate).map(booking => (
                <div key={booking.id} className="border rounded-lg p-4 hover:shadow-md transition-shadow">
                  <div className="flex justify-between items-start">
                    <div className="flex-1">
                      <div className="flex items-center space-x-3 mb-2">
                        <h4 className="font-semibold text-gray-900">{booking.customerName}</h4>
                        <span className={`px-2 py-1 rounded-full text-xs font-medium border ${getStatusColor(booking.status)}`}>
                          {getStatusText(booking.status)}
                        </span>
                      </div>
                      
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm text-gray-600">
                        <div>
                          <strong>Behandlung:</strong> {getTreatmentName(booking.treatmentId)}
                        </div>
                        <div>
                          <strong>Uhrzeit:</strong> {booking.appointmentTime}
                        </div>
                        <div>
                          <strong>E-Mail:</strong> {booking.customerEmail}
                        </div>
                        <div>
                          <strong>Telefon:</strong> {booking.customerPhone}
                        </div>
                      </div>
                      
                      {booking.notes && (
                        <div className="mt-3 text-sm">
                          <strong>Notizen:</strong>
                          <p className="text-gray-600 mt-1">{booking.notes}</p>
                        </div>
                      )}
                    </div>

                    {/* Status Update Buttons */}
                    <div className="flex flex-col space-y-2 ml-4">
                      {booking.status === "pending" && (
                        <>
                          <button
                            onClick={() => handleStatusUpdate(booking.id, "confirmed")}
                            className="px-3 py-1 bg-green-600 text-white text-sm rounded hover:bg-green-700 transition-colors"
                          >
                            Bestätigen
                          </button>
                          <button
                            onClick={() => handleStatusUpdate(booking.id, "cancelled")}
                            className="px-3 py-1 bg-red-600 text-white text-sm rounded hover:bg-red-700 transition-colors"
                          >
                            Stornieren
                          </button>
                        </>
                      )}
                      
                      {booking.status === "confirmed" && (
                        <button
                          onClick={() => handleStatusUpdate(booking.id, "completed")}
                          className="px-3 py-1 bg-blue-600 text-white text-sm rounded hover:bg-blue-700 transition-colors"
                        >
                          Als erledigt markieren
                        </button>
                      )}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}
