import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { api } from '../services/api'
import type { Workspace, Booking, WorkspaceFilter } from '@skillmate/shared'

export default function DeskBooking() {
  const navigate = useNavigate()
  const [workspaces, setWorkspaces] = useState<Workspace[]>([])
  const [myBookings, setMyBookings] = useState<Booking[]>([])
  const [selectedDate, setSelectedDate] = useState(new Date().toISOString().split('T')[0])
  const [selectedTime, setSelectedTime] = useState('09:00')
  const [duration, setDuration] = useState(8) // hours
  const [filter, setFilter] = useState<WorkspaceFilter>({})
  const [loading, setLoading] = useState(true)
  const [showBookingModal, setShowBookingModal] = useState(false)
  const [selectedWorkspace, setSelectedWorkspace] = useState<Workspace | null>(null)

  useEffect(() => {
    loadData()
  }, [selectedDate, filter])

  const loadData = async () => {
    try {
      setLoading(true)
      
      // Calculate start and end times
      const startTime = new Date(`${selectedDate}T${selectedTime}:00`).toISOString()
      const endTime = new Date(new Date(startTime).getTime() + duration * 60 * 60 * 1000).toISOString()

      // Load available workspaces
      const availableResponse = await api.post('/workspaces/availability', {
        start_time: startTime,
        end_time: endTime,
        type: filter.type || 'desk'
      })
      setWorkspaces(availableResponse.data)

      // Load user's bookings
      const bookingsResponse = await api.get('/bookings/my-bookings', {
        params: {
          from_date: selectedDate,
          status: 'confirmed'
        }
      })
      setMyBookings(bookingsResponse.data)
    } catch (error) {
      console.error('Failed to load data:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleBook = async (workspace: Workspace) => {
    try {
      const startTime = new Date(`${selectedDate}T${selectedTime}:00`).toISOString()
      const endTime = new Date(new Date(startTime).getTime() + duration * 60 * 60 * 1000).toISOString()

      await api.post('/bookings', {
        workspace_id: workspace.id,
        start_time: startTime,
        end_time: endTime
      })

      // Reload data
      await loadData()
      
      // Show success message
      alert('Arbeitsplatz erfolgreich gebucht!')
    } catch (error: any) {
      alert(error.response?.data?.error || 'Buchung fehlgeschlagen')
    }
  }

  const handleCancelBooking = async (bookingId: string) => {
    if (!confirm('Möchten Sie diese Buchung wirklich stornieren?')) return

    try {
      await api.post(`/bookings/${bookingId}/cancel`)
      await loadData()
      alert('Buchung erfolgreich storniert')
    } catch (error) {
      alert('Stornierung fehlgeschlagen')
    }
  }

  const handleCheckIn = async (bookingId: string) => {
    try {
      await api.post(`/bookings/${bookingId}/check-in`)
      await loadData()
      alert('Check-in erfolgreich')
    } catch (error: any) {
      alert(error.response?.data?.error || 'Check-in fehlgeschlagen')
    }
  }

  return (
    <div className="p-6">
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
          Arbeitsplatz buchen
        </h1>
        <p className="text-gray-600 dark:text-gray-400">
          Buchen Sie Ihren Arbeitsplatz flexibel und einfach
        </p>
      </div>

      {/* Filter Section */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-6">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Datum
            </label>
            <input
              type="date"
              value={selectedDate}
              min={new Date().toISOString().split('T')[0]}
              onChange={(e) => setSelectedDate(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Startzeit
            </label>
            <select
              value={selectedTime}
              onChange={(e) => setSelectedTime(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
            >
              {Array.from({ length: 13 }, (_, i) => i + 6).map(hour => (
                <option key={hour} value={`${hour.toString().padStart(2, '0')}:00`}>
                  {hour}:00 Uhr
                </option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Dauer (Stunden)
            </label>
            <select
              value={duration}
              onChange={(e) => setDuration(Number(e.target.value))}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
            >
              {[1, 2, 4, 6, 8, 10].map(hours => (
                <option key={hours} value={hours}>{hours} Stunden</option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Typ
            </label>
            <select
              value={filter.type || 'desk'}
              onChange={(e) => setFilter({ ...filter, type: e.target.value })}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
            >
              <option value="desk">Schreibtisch</option>
              <option value="meeting_room">Meetingraum</option>
              <option value="phone_booth">Telefonbox</option>
              <option value="parking">Parkplatz</option>
            </select>
          </div>
        </div>
      </div>

      {/* My Bookings */}
      {myBookings.length > 0 && (
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-6">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
            Meine Buchungen heute
          </h2>
          <div className="space-y-3">
            {myBookings.map(booking => (
              <div
                key={booking.id}
                className="flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-700 rounded-lg"
              >
                <div>
                  <h3 className="font-medium text-gray-900 dark:text-white">
                    {booking.workspace?.name || 'Arbeitsplatz'}
                  </h3>
                  <p className="text-sm text-gray-600 dark:text-gray-400">
                    {new Date(booking.start_time).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' })} - 
                    {new Date(booking.end_time).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' })}
                  </p>
                </div>
                <div className="flex gap-2">
                  {!booking.check_in_time && new Date(booking.start_time) <= new Date(new Date().getTime() + 15 * 60 * 1000) && (
                    <button
                      onClick={() => handleCheckIn(booking.id)}
                      className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700"
                    >
                      Check-in
                    </button>
                  )}
                  <button
                    onClick={() => handleCancelBooking(booking.id)}
                    className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700"
                  >
                    Stornieren
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Available Workspaces */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
        <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
          Verfügbare Arbeitsplätze
        </h2>

        {loading ? (
          <div className="text-center py-8">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          </div>
        ) : workspaces.length === 0 ? (
          <p className="text-gray-600 dark:text-gray-400 text-center py-8">
            Keine Arbeitsplätze für den gewählten Zeitraum verfügbar
          </p>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {workspaces.map(workspace => (
              <div
                key={workspace.id}
                className="border border-gray-200 dark:border-gray-700 rounded-lg p-4 hover:shadow-lg transition-shadow"
              >
                <h3 className="font-medium text-gray-900 dark:text-white mb-2">
                  {workspace.name}
                </h3>
                <div className="space-y-1 text-sm text-gray-600 dark:text-gray-400 mb-4">
                  <p>Etage: {workspace.floor}</p>
                  {workspace.building && <p>Gebäude: {workspace.building}</p>}
                  {workspace.equipment && workspace.equipment.length > 0 && (
                    <p>Ausstattung: {workspace.equipment.join(', ')}</p>
                  )}
                </div>
                <button
                  onClick={() => handleBook(workspace)}
                  className="w-full px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
                >
                  Jetzt buchen
                </button>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
