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

interface WorkspaceWithStatus extends Workspace {
  isBooked?: boolean
  currentUser?: {
    name: string
    photo?: string
  }
}

export default function FloorPlan() {
  const [selectedFloor, setSelectedFloor] = useState('1')
  const [selectedDate, setSelectedDate] = useState(new Date().toISOString().split('T')[0])
  const [selectedTime, setSelectedTime] = useState(new Date().toISOString().substring(11, 16))
  const [workspaces, setWorkspaces] = useState<WorkspaceWithStatus[]>([])
  const [loading, setLoading] = useState(true)
  const [hoveredWorkspace, setHoveredWorkspace] = useState<WorkspaceWithStatus | null>(null)

  const floors = ['EG', '1', '2', '3', '4']

  useEffect(() => {
    loadFloorData()
  }, [selectedFloor, selectedDate, selectedTime])

  const loadFloorData = async () => {
    try {
      setLoading(true)
      
      // Get all workspaces for the floor
      const workspaceResponse = await api.get('/workspaces', {
        params: { floor: selectedFloor }
      })
      
      // Get bookings for the selected time
      const dateTime = new Date(`${selectedDate}T${selectedTime}:00`).toISOString()
      const bookingResponse = await api.get('/bookings', {
        params: {
          from_date: dateTime,
          to_date: dateTime,
          status: 'confirmed'
        }
      })

      // Map bookings to workspaces
      const bookingMap = new Map()
      bookingResponse.data.forEach((booking: any) => {
        if (new Date(booking.start_time) <= new Date(dateTime) && 
            new Date(booking.end_time) > new Date(dateTime)) {
          bookingMap.set(booking.workspace_id, {
            name: `${booking.first_name} ${booking.last_name}`,
            photo: booking.photo
          })
        }
      })

      // Combine workspace and booking data
      const workspacesWithStatus = workspaceResponse.data.map((ws: Workspace) => ({
        ...ws,
        isBooked: bookingMap.has(ws.id),
        currentUser: bookingMap.get(ws.id)
      }))

      setWorkspaces(workspacesWithStatus)
    } catch (error) {
      console.error('Failed to load floor data:', error)
    } finally {
      setLoading(false)
    }
  }

  const getWorkspaceColor = (workspace: WorkspaceWithStatus) => {
    if (!workspace.is_active) return 'bg-gray-300'
    if (workspace.isBooked) return 'bg-red-500'
    return 'bg-green-500'
  }

  const renderWorkspace = (workspace: WorkspaceWithStatus) => {
    const size = workspace.type === 'meeting_room' ? 'w-24 h-16' : 'w-16 h-12'
    
    return (
      <div
        key={workspace.id}
        className={`absolute ${size} ${getWorkspaceColor(workspace)} rounded cursor-pointer transition-all hover:scale-105 flex items-center justify-center text-white text-xs font-medium`}
        style={{
          left: `${(workspace.position_x || 0) * 4}px`,
          top: `${(workspace.position_y || 0) * 4}px`
        }}
        onMouseEnter={() => setHoveredWorkspace(workspace)}
        onMouseLeave={() => setHoveredWorkspace(null)}
      >
        {workspace.name}
      </div>
    )
  }

  return (
    <div className="p-6">
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
          Anwesenheitsübersicht
        </h1>
        <p className="text-gray-600 dark:text-gray-400">
          Sehen Sie auf einen Blick, wer wo im Büro ist
        </p>
      </div>

      {/* Controls */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-6">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Etage
            </label>
            <select
              value={selectedFloor}
              onChange={(e) => setSelectedFloor(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"
            >
              {floors.map(floor => (
                <option key={floor} value={floor}>Etage {floor}</option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Datum
            </label>
            <input
              type="date"
              value={selectedDate}
              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">
              Uhrzeit
            </label>
            <input
              type="time"
              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"
            />
          </div>
        </div>

        <div className="flex items-center gap-6 mt-4">
          <div className="flex items-center gap-2">
            <div className="w-4 h-4 bg-green-500 rounded"></div>
            <span className="text-sm text-gray-600 dark:text-gray-400">Frei</span>
          </div>
          <div className="flex items-center gap-2">
            <div className="w-4 h-4 bg-red-500 rounded"></div>
            <span className="text-sm text-gray-600 dark:text-gray-400">Belegt</span>
          </div>
          <div className="flex items-center gap-2">
            <div className="w-4 h-4 bg-gray-300 rounded"></div>
            <span className="text-sm text-gray-600 dark:text-gray-400">Inaktiv</span>
          </div>
        </div>
      </div>

      {/* Floor Plan */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
        {loading ? (
          <div className="text-center py-16">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          </div>
        ) : (
          <>
            <div className="relative bg-gray-100 dark:bg-gray-900 rounded-lg p-8" style={{ minHeight: '600px' }}>
              {/* Grid background */}
              <div 
                className="absolute inset-0 opacity-10"
                style={{
                  backgroundImage: 'repeating-linear-gradient(0deg, #888 0, #888 1px, transparent 1px, transparent 40px), repeating-linear-gradient(90deg, #888 0, #888 1px, transparent 1px, transparent 40px)',
                  backgroundSize: '40px 40px'
                }}
              />

              {/* Workspaces */}
              {workspaces.map(workspace => renderWorkspace(workspace))}

              {/* Hover tooltip */}
              {hoveredWorkspace && (
                <div className="absolute z-10 bg-gray-900 text-white p-3 rounded-lg shadow-lg"
                     style={{
                       left: `${(hoveredWorkspace.position_x || 0) * 4 + 70}px`,
                       top: `${(hoveredWorkspace.position_y || 0) * 4}px`
                     }}>
                  <p className="font-medium">{hoveredWorkspace.name}</p>
                  <p className="text-sm text-gray-300">
                    {hoveredWorkspace.type === 'desk' ? 'Arbeitsplatz' : 
                     hoveredWorkspace.type === 'meeting_room' ? 'Meetingraum' : 
                     hoveredWorkspace.type === 'phone_booth' ? 'Telefonbox' : 'Sonstiges'}
                  </p>
                  {hoveredWorkspace.isBooked && hoveredWorkspace.currentUser && (
                    <div className="mt-2 pt-2 border-t border-gray-700">
                      <p className="text-sm">Belegt von:</p>
                      <p className="font-medium">{hoveredWorkspace.currentUser.name}</p>
                    </div>
                  )}
                  {hoveredWorkspace.equipment && hoveredWorkspace.equipment.length > 0 && (
                    <p className="text-sm text-gray-300 mt-1">
                      {hoveredWorkspace.equipment.join(', ')}
                    </p>
                  )}
                </div>
              )}
            </div>

            {/* Statistics */}
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mt-6">
              <div className="bg-gray-50 dark:bg-gray-700 rounded-lg p-4">
                <p className="text-sm text-gray-600 dark:text-gray-400">Gesamt</p>
                <p className="text-2xl font-bold text-gray-900 dark:text-white">
                  {workspaces.length}
                </p>
              </div>
              <div className="bg-gray-50 dark:bg-gray-700 rounded-lg p-4">
                <p className="text-sm text-gray-600 dark:text-gray-400">Frei</p>
                <p className="text-2xl font-bold text-green-600">
                  {workspaces.filter(ws => ws.is_active && !ws.isBooked).length}
                </p>
              </div>
              <div className="bg-gray-50 dark:bg-gray-700 rounded-lg p-4">
                <p className="text-sm text-gray-600 dark:text-gray-400">Belegt</p>
                <p className="text-2xl font-bold text-red-600">
                  {workspaces.filter(ws => ws.isBooked).length}
                </p>
              </div>
              <div className="bg-gray-50 dark:bg-gray-700 rounded-lg p-4">
                <p className="text-sm text-gray-600 dark:text-gray-400">Auslastung</p>
                <p className="text-2xl font-bold text-blue-600">
                  {workspaces.length > 0 
                    ? Math.round((workspaces.filter(ws => ws.isBooked).length / workspaces.filter(ws => ws.is_active).length) * 100)
                    : 0}%
                </p>
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  )
}
