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 [showDeleteConfirm, setShowDeleteConfirm] = useState<string | null>(null);
  const [sendDeleteEmail, setSendDeleteEmail] = useState(false);
  const [deleteActionType, setDeleteActionType] = useState<'delete' | 'cancel'>('delete');
  
  // CalDAV state
  const [caldavData, setCaldavData] = useState<any>(null);
  const [showCaldavInstructions, setShowCaldavInstructions] = useState(false);
  
  // Manual booking modal state
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [createFormData, setCreateFormData] = useState({
    customerName: '',
    treatmentId: '',
    appointmentDate: '',
    appointmentTime: '',
    customerEmail: '',
    customerPhone: '',
    notes: ''
  });
  const [createError, setCreateError] = useState<string>('');

  // Reschedule modal state
  const [showRescheduleModal, setShowRescheduleModal] = useState<string | null>(null);
  const [rescheduleFormData, setRescheduleFormData] = useState({
    appointmentDate: '',
    appointmentTime: ''
  });
  const [rescheduleError, setRescheduleError] = useState<string>('');

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

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

  // Optional query for available times when treatment and date are selected
  const { data: availableTimes } = useQuery({
    ...queryClient.recurringAvailability.getAvailableTimes.queryOptions({
      input: {
        date: createFormData.appointmentDate,
        treatmentIds: createFormData.treatmentId ? [createFormData.treatmentId] : []
      }
    }),
    enabled: !!createFormData.appointmentDate && !!createFormData.treatmentId
  });

  // Available times for reschedule modal
  const { data: rescheduleAvailableTimes } = useQuery({
    ...queryClient.recurringAvailability.getAvailableTimes.queryOptions({
      input: {
        date: rescheduleFormData.appointmentDate,
        treatmentIds: (() => {
          const booking = showRescheduleModal ? bookings?.find(b => b.id === showRescheduleModal) : null;
          if (!booking) return [];
          // Use new treatments array if available
          if (booking.treatments && Array.isArray(booking.treatments) && booking.treatments.length > 0) {
            return booking.treatments.map((t: any) => t.id);
          }
          // Fallback to deprecated treatmentId for backward compatibility
          return booking.treatmentId ? [booking.treatmentId] : [];
        })()
      }
    }),
    enabled: !!showRescheduleModal && !!rescheduleFormData.appointmentDate
  });

  const { mutate: updateBookingStatus } = useMutation(
    queryClient.bookings.updateStatus.mutationOptions()
  );

  const { mutate: removeBooking } = useMutation(
    queryClient.bookings.remove.mutationOptions()
  );

  const { mutate: createManualBooking } = useMutation(
    queryClient.bookings.createManual.mutationOptions()
  );

  // Propose reschedule mutation
  const { mutate: proposeReschedule, isPending: isProposingReschedule } = useMutation(
    queryClient.bookings.proposeReschedule.mutationOptions()
  );

  // CalDAV token generation mutation
  const { mutate: generateCalDAVToken, isPending: isGeneratingToken } = useMutation(
    queryClient.bookings.generateCalDAVToken.mutationOptions()
  );

  const getTreatmentNames = (booking: any) => {
    // Handle new treatments array structure
    if (booking.treatments && Array.isArray(booking.treatments) && booking.treatments.length > 0) {
      return booking.treatments.map((t: any) => t.name).join(", ");
    }
    // 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 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 handleDeleteBooking = () => {
    const sessionId = localStorage.getItem('sessionId');
    if (!sessionId || !showDeleteConfirm) return;

    if (deleteActionType === 'cancel') {
      // For cancel action, use updateStatus instead of remove
      updateBookingStatus({
        sessionId,
        id: showDeleteConfirm,
        status: "cancelled"
      }, {
        onSuccess: () => {
          setShowDeleteConfirm(null);
          setSendDeleteEmail(false);
          setDeleteActionType('delete');
        },
        onError: () => {
          // no-op; errors can be surfaced via existing patterns/toasts later
        }
      });
    } else {
      // For delete action, use remove with email option
      removeBooking({
        sessionId,
        id: showDeleteConfirm,
        sendEmail: sendDeleteEmail,
      }, {
        onSuccess: () => {
          setShowDeleteConfirm(null);
          setSendDeleteEmail(false);
          setDeleteActionType('delete');
        },
        onError: () => {
          // no-op; errors can be surfaced via existing patterns/toasts later
        }
      });
    }
  };

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

  const handleCreateBooking = () => {
    const sessionId = localStorage.getItem('sessionId');
    if (!sessionId) return;

    // Convert treatmentId to treatments array
    const selectedTreatment = treatments?.find(t => t.id === createFormData.treatmentId);
    if (!selectedTreatment) {
      setCreateError('Bitte wähle eine Behandlung aus.');
      return;
    }

    const treatmentsArray = [{
      id: selectedTreatment.id,
      name: selectedTreatment.name,
      duration: selectedTreatment.duration,
      price: selectedTreatment.price
    }];

    createManualBooking({
      sessionId,
      treatments: treatmentsArray,
      customerName: createFormData.customerName,
      appointmentDate: createFormData.appointmentDate,
      appointmentTime: createFormData.appointmentTime,
      customerEmail: createFormData.customerEmail,
      customerPhone: createFormData.customerPhone,
      notes: createFormData.notes
    }, {
      onSuccess: () => {
        setShowCreateModal(false);
        setCreateFormData({
          customerName: '',
          treatmentId: '',
          appointmentDate: '',
          appointmentTime: '',
          customerEmail: '',
          customerPhone: '',
          notes: ''
        });
        setCreateError('');
      },
      onError: (error: any) => {
        setCreateError(error?.message || 'Fehler beim Erstellen der Buchung');
      }
    });
  };

  const handleFormChange = (field: string, value: string) => {
    setCreateFormData(prev => ({
      ...prev,
      [field]: value,
      // Reset time when treatment or date changes
      ...(field === 'treatmentId' || field === 'appointmentDate' ? { appointmentTime: '' } : {})
    }));
    setCreateError('');
  };

  const handleRescheduleFormChange = (field: string, value: string) => {
    setRescheduleFormData(prev => ({
      ...prev,
      [field]: value,
      ...(field === 'appointmentDate' ? { appointmentTime: '' } : {})
    }));
    setRescheduleError('');
  };

  const handleRescheduleBooking = () => {
    const sessionId = localStorage.getItem('sessionId');
    if (!sessionId || !showRescheduleModal) return;
    const booking = bookings?.find(b => b.id === showRescheduleModal);
    if (!booking) return;

    proposeReschedule({
      sessionId,
      bookingId: booking.id,
      proposedDate: rescheduleFormData.appointmentDate,
      proposedTime: rescheduleFormData.appointmentTime,
    }, {
      onSuccess: () => {
        setShowRescheduleModal(null);
        setRescheduleFormData({ appointmentDate: '', appointmentTime: '' });
        setRescheduleError('');
      },
      onError: (error: any) => {
        setRescheduleError(error?.message || 'Fehler beim Senden des Vorschlags');
      }
    });
  };

  const handleGenerateCalDAVToken = () => {
    const sessionId = localStorage.getItem('sessionId');
    if (!sessionId) return;

    generateCalDAVToken({
      sessionId
    }, {
      onSuccess: (data) => {
        setCaldavData(data);
        setShowCaldavInstructions(true);
      },
      onError: (error: any) => {
        console.error('CalDAV Token Generation Error:', error);
      }
    });
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text).then(() => {
      // Optional: Show success message
    }).catch(err => {
      console.error('Failed to copy text: ', err);
    });
  };

  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>

      {/* CalDAV Integration */}
      <div className="bg-white rounded-lg shadow p-6 mb-6">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h3 className="text-lg font-semibold text-gray-900">Kalender-Abonnement</h3>
            <p className="text-sm text-gray-600">Abonniere deinen Terminkalender in deiner Kalender-App</p>
          </div>
          <button
            onClick={handleGenerateCalDAVToken}
            disabled={isGeneratingToken}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-sm font-medium"
          >
            {isGeneratingToken ? 'Generiere...' : 'CalDAV-Link erstellen'}
          </button>
        </div>
        
        {caldavData && (
          <div className="border-t pt-4">
            <div className="bg-gray-50 rounded-lg p-4 mb-4">
              <div className="flex items-center justify-between mb-2">
                <label className="text-sm font-medium text-gray-700">CalDAV-URL:</label>
                <button
                  onClick={() => copyToClipboard(caldavData.caldavUrl)}
                  className="text-blue-600 hover:text-blue-800 text-sm"
                >
                  Kopieren
                </button>
              </div>
              <input
                type="text"
                value={caldavData.caldavUrl}
                readOnly
                className="w-full p-2 bg-white border border-gray-300 rounded text-sm font-mono"
              />
              <div className="text-xs text-gray-500 mt-2">
                Gültig bis: {new Date(caldavData.expiresAt).toLocaleString('de-DE')}
              </div>
            </div>
            
            <div className="text-sm text-gray-600">
              <p className="mb-2">
                <strong>So abonnierst du den Kalender:</strong>
              </p>
              <ul className="list-disc list-inside space-y-1 text-sm">
                {caldavData.instructions.steps.map((step: string, index: number) => (
                  <li key={index}>{step}</li>
                ))}
              </ul>
              <p className="mt-3 text-amber-700 bg-amber-50 p-2 rounded">
                <strong>Hinweis:</strong> {caldavData.instructions.note}
              </p>
            </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>
          
          <div className="flex items-center space-x-4">
            <h3 className="text-xl font-semibold text-gray-900">
              {monthNames[month]} {year}
            </h3>
            <button
              onClick={() => setShowCreateModal(true)}
              className="px-4 py-2 bg-pink-600 text-white rounded-lg hover:bg-pink-700 transition-colors text-sm font-medium"
            >
              Termin erstellen
            </button>
          </div>
          
          <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} - ${getTreatmentNames(booking)} (${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> {getTreatmentNames(booking)}
                        </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={() => {
                              setDeleteActionType('cancel');
                              setShowDeleteConfirm(booking.id);
                              setSendDeleteEmail(true); // Default to sending email for cancel
                            }}
                            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>
                          <button
                            onClick={() => {
                              setShowRescheduleModal(booking.id);
                              setRescheduleFormData({ appointmentDate: '', appointmentTime: '' });
                              setRescheduleError('');
                            }}
                            className="px-3 py-1 bg-orange-600 text-white text-sm rounded hover:bg-orange-700 transition-colors"
                          >
                            Umbuchen
                          </button>
                        </>
                      )}
                      {(() => {
                        const isPastDate = booking.appointmentDate < today;
                        const isCompleted = booking.status === 'completed';
                        const shouldDisableDelete = isPastDate || isCompleted;
                        
                        return (
                          <button
                            onClick={() => {
                              if (!shouldDisableDelete) {
                                setDeleteActionType('delete');
                                setShowDeleteConfirm(booking.id);
                                setSendDeleteEmail(isPastDate || isCompleted ? false : false); // Disable email for past/completed
                              }
                            }}
                            disabled={shouldDisableDelete}
                            className={`px-3 py-1 text-sm rounded transition-colors ${
                              shouldDisableDelete 
                                ? 'bg-gray-400 text-gray-200 cursor-not-allowed' 
                                : 'bg-red-600 text-white hover:bg-red-700'
                            }`}
                            title={shouldDisableDelete ? 'Löschen für vergangene/abgeschlossene Termine nicht verfügbar' : ''}
                          >
                            Löschen
                          </button>
                        );
                      })()}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
      {showDeleteConfirm !== null && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl p-6 w-full max-w-md">
            <h4 className="text-lg font-semibold text-gray-900 mb-2">
              {deleteActionType === 'cancel' ? 'Termin stornieren?' : 'Termin löschen?'}
            </h4>
            <p className="text-sm text-gray-600 mb-4">
              {deleteActionType === 'cancel' 
                ? 'Dieser Termin wird als storniert markiert. Der Zeitslot wird wieder freigegeben.'
                : 'Dieser Termin wird als storniert markiert. Der Zeitslot wird wieder freigegeben.'
              }
            </p>
            {deleteActionType === 'delete' && (
              <label className="flex items-center space-x-2 mb-4">
                <input
                  type="checkbox"
                  checked={sendDeleteEmail}
                  onChange={(e) => setSendDeleteEmail(e.target.checked)}
                  className="h-4 w-4 text-pink-600 border-gray-300 rounded"
                />
                <span className="text-sm text-gray-700">Stornierungsmail an Kunde senden</span>
              </label>
            )}
            <div className="flex flex-col sm:flex-row sm:space-x-3 space-y-2 sm:space-y-0">
              <button
                onClick={() => { 
                  setShowDeleteConfirm(null); 
                  setSendDeleteEmail(false); 
                  setDeleteActionType('delete');
                }}
                className="px-4 py-2 rounded bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors w-full"
              >
                Abbrechen
              </button>
              <button
                onClick={handleDeleteBooking}
                className="px-4 py-2 rounded bg-red-600 text-white hover:bg-red-700 transition-colors w-full"
              >
                {deleteActionType === 'cancel' ? 'Stornieren' : 'Löschen'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Create Manual Booking Modal */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl p-6 w-full max-w-md max-h-[90vh] overflow-y-auto">
            <h4 className="text-lg font-semibold text-gray-900 mb-4">Termin erstellen</h4>
            
            {createError && (
              <div className="mb-4 bg-red-50 border border-red-200 text-red-700 px-3 py-2 rounded-md text-sm">
                {createError}
              </div>
            )}

            <div className="space-y-4">
              {/* Customer Name */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Kundenname *
                </label>
                <input
                  type="text"
                  value={createFormData.customerName}
                  onChange={(e) => handleFormChange('customerName', e.target.value)}
                  className="w-full p-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-pink-500 focus:border-pink-500"
                  required
                />
              </div>

              {/* Treatment */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Behandlung *
                </label>
                <select
                  value={createFormData.treatmentId}
                  onChange={(e) => handleFormChange('treatmentId', e.target.value)}
                  className="w-full p-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-pink-500 focus:border-pink-500"
                  required
                >
                  <option value="">Behandlung wählen</option>
                  {treatments?.map(treatment => (
                    <option key={treatment.id} value={treatment.id}>
                      {treatment.name}
                    </option>
                  ))}
                </select>
              </div>

              {/* Date */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Datum *
                </label>
                <input
                  type="date"
                  value={createFormData.appointmentDate}
                  onChange={(e) => handleFormChange('appointmentDate', e.target.value)}
                  min={today}
                  className="w-full p-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-pink-500 focus:border-pink-500"
                  required
                />
              </div>

              {/* Time */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Uhrzeit *
                </label>
                <select
                  value={createFormData.appointmentTime}
                  onChange={(e) => handleFormChange('appointmentTime', e.target.value)}
                  disabled={!createFormData.treatmentId || !createFormData.appointmentDate}
                  className="w-full p-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-pink-500 focus:border-pink-500 disabled:bg-gray-100"
                  required
                >
                  <option value="">Zeit wählen</option>
                  {availableTimes?.map(time => (
                    <option key={time} value={time}>
                      {time}
                    </option>
                  ))}
                </select>
                {(!createFormData.treatmentId || !createFormData.appointmentDate) && (
                  <p className="text-xs text-gray-500 mt-1">
                    Wähle zuerst Behandlung und Datum
                  </p>
                )}
              </div>

              {/* Email */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  E-Mail (optional)
                </label>
                <input
                  type="email"
                  value={createFormData.customerEmail}
                  onChange={(e) => handleFormChange('customerEmail', e.target.value)}
                  className="w-full p-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-pink-500 focus:border-pink-500"
                />
              </div>

              {/* Phone */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Telefon (optional)
                </label>
                <input
                  type="tel"
                  value={createFormData.customerPhone}
                  onChange={(e) => handleFormChange('customerPhone', e.target.value)}
                  className="w-full p-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-pink-500 focus:border-pink-500"
                />
              </div>

              {/* Notes */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Notizen (optional)
                </label>
                <textarea
                  value={createFormData.notes}
                  onChange={(e) => handleFormChange('notes', e.target.value)}
                  rows={3}
                  className="w-full p-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-pink-500 focus:border-pink-500"
                />
              </div>
            </div>

            <div className="flex space-x-3 mt-6">
              <button
                onClick={() => {
                  setShowCreateModal(false);
                  setCreateFormData({
                    customerName: '',
                    treatmentId: '',
                    appointmentDate: '',
                    appointmentTime: '',
                    customerEmail: '',
                    customerPhone: '',
                    notes: ''
                  });
                  setCreateError('');
                }}
                className="flex-1 px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 transition-colors"
              >
                Abbrechen
              </button>
              <button
                onClick={handleCreateBooking}
                disabled={!createFormData.customerName || !createFormData.treatmentId || !createFormData.appointmentDate || !createFormData.appointmentTime}
                className="flex-1 px-4 py-2 bg-pink-600 text-white rounded-md hover:bg-pink-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                Termin erstellen
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Reschedule Modal */}
      {showRescheduleModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl p-6 w-full max-w-md max-h-[90vh] overflow-y-auto">
            <h4 className="text-lg font-semibold text-gray-900 mb-4">Termin umbuchen</h4>

            {rescheduleError && (
              <div className="mb-4 bg-red-50 border border-red-200 text-red-700 px-3 py-2 rounded-md text-sm">
                {rescheduleError}
              </div>
            )}

            {(() => {
              const booking = bookings?.find(b => b.id === showRescheduleModal);
              const treatmentName = booking ? getTreatmentNames(booking) : '';
              return booking ? (
                <div className="mb-4 text-sm text-gray-700">
                  <div className="mb-2"><strong>Kunde:</strong> {booking.customerName}</div>
                  <div className="mb-2"><strong>Aktueller Termin:</strong> {booking.appointmentDate} um {booking.appointmentTime} Uhr</div>
                  <div className="mb-2"><strong>Behandlung:</strong> {treatmentName}</div>
                </div>
              ) : null;
            })()}

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Neues Datum</label>
                <input
                  type="date"
                  value={rescheduleFormData.appointmentDate}
                  onChange={(e) => handleRescheduleFormChange('appointmentDate', e.target.value)}
                  min={today}
                  className="w-full p-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-orange-500 focus:border-orange-500"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Neue Uhrzeit</label>
                <select
                  value={rescheduleFormData.appointmentTime}
                  onChange={(e) => handleRescheduleFormChange('appointmentTime', e.target.value)}
                  disabled={!rescheduleFormData.appointmentDate}
                  className="w-full p-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-orange-500 focus:border-orange-500 disabled:bg-gray-100"
                >
                  <option value="">Zeit wählen</option>
                  {rescheduleAvailableTimes?.map(time => (
                    <option key={time} value={time}>{time}</option>
                  ))}
                </select>
                {!rescheduleFormData.appointmentDate && (
                  <p className="text-xs text-gray-500 mt-1">Wähle zuerst ein Datum</p>
                )}
              </div>
              <div className="bg-amber-50 border border-amber-200 text-amber-800 px-3 py-2 rounded-md text-sm">
                Der Kunde erhält eine E-Mail mit dem Vorschlag. Er hat 48 Stunden Zeit zu antworten.
              </div>
            </div>

            <div className="flex space-x-3 mt-6">
              <button
                onClick={() => {
                  setShowRescheduleModal(null);
                  setRescheduleFormData({ appointmentDate: '', appointmentTime: '' });
                  setRescheduleError('');
                }}
                className="flex-1 px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 transition-colors"
              >
                Abbrechen
              </button>
              <button
                onClick={handleRescheduleBooking}
                disabled={!rescheduleFormData.appointmentDate || !rescheduleFormData.appointmentTime || isProposingReschedule}
                className="flex-1 px-4 py-2 bg-orange-600 text-white rounded-md hover:bg-orange-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {isProposingReschedule ? 'Senden...' : 'Vorschlag senden'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
