'use client'

import { useState, useEffect, useMemo } from 'react'
import { useAdBookings } from '@/hooks/use-ad-bookings'
import { Calendar } from '@/components/ui/calendar'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Badge } from '@/components/ui/badge'
import { Modifiers, DayButton } from 'react-day-picker'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'

interface AvailabilityCalendarProps {
  selectedPlacement: string
  onPlacementChange: (placement: string) => void
}

interface AvailabilityData {
  date: string
  availableSlots: number
  bookedSlots: number
  status: 'free' | 'available' | 'limited' | 'soldout'
}

export function AvailabilityCalendar({
  selectedPlacement,
  onPlacementChange
}: AvailabilityCalendarProps) {
  const [selectedDates, setSelectedDates] = useState<Date[]>([])
  const [currentMonth, setCurrentMonth] = useState<Date>(new Date())
  
  // Use cached bookings data
  const { bookingsData, loading, getAvailability } = useAdBookings(6)
  
  // Generate availability data for current month from cached bookings
  const availability = useMemo(() => {
    if (!bookingsData) return []
    
    const year = currentMonth.getFullYear()
    const month = currentMonth.getMonth()
    const firstDay = new Date(year, month, 1)
    const lastDay = new Date(year, month + 1, 0)
    
    const availabilityList: AvailabilityData[] = []
    const current = new Date(firstDay)
    
    while (current <= lastDay) {
      const avail = getAvailability(current, selectedPlacement)
      if (avail) {
        availabilityList.push(avail)
      } else {
        // Date not in bookings (should be free)
        const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(current.getDate()).padStart(2, '0')}`
        availabilityList.push({
          date: dateStr,
          bookedSlots: 0,
          availableSlots: 5,
          status: 'free'
        })
      }
      current.setDate(current.getDate() + 1)
    }
    
    return availabilityList
  }, [bookingsData, currentMonth, selectedPlacement, getAvailability])
  
  // Create modifiers for calendar styling
  const modifiers: Record<string, Date[]> = {
    free: [],
    available: [],
    limited: [],
    soldout: []
  }
  // Store availability data by date for dot rendering
  const availabilityByDate = new Map<string, AvailabilityData>()
  availability.forEach(item => {
    availabilityByDate.set(item.date, item)
  })
  
  const modifiersClassNames: Record<string, string> = {
    free: '',
    available: '',
    limited: '',
    soldout: 'opacity-60 cursor-not-allowed'
  }
  
  availability.forEach((item) => {
    // Parse date string (YYYY-MM-DD) to Date object using local timezone
    const [year, month, day] = item.date.split('-').map(Number)
    const date = new Date(year, month - 1, day)
    
    if (item.status === 'free') {
      modifiers.free?.push(date)
    } else if (item.status === 'available') {
      modifiers.available?.push(date)
    } else if (item.status === 'limited') {
      modifiers.limited?.push(date)
    } else if (item.status === 'soldout') {
      modifiers.soldout?.push(date)
    }
  })
  
  // Normalize date to YYYY-MM-DD format (same as API)
  const normalizeDate = (date: Date): string => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }
  
  // Get availability info for a specific date
  const getAvailabilityInfo = (date: Date): AvailabilityData | null => {
    const dateStr = normalizeDate(date)
    return availability.find(item => item.date === dateStr) || null
  }
  
  // Handle date selection - prevent selection of sold out dates
  const handleDateSelect = (dates: Date[] | undefined) => {
    if (!dates) {
      setSelectedDates([])
      return
    }
    
    // Filter out sold out dates
    const availableDates = dates.filter(date => {
      const info = getAvailabilityInfo(date)
      return info && info.status !== 'soldout'
    })
    
    setSelectedDates(availableDates)
  }
  
  // Handle month navigation
  const handleMonthChange = (month: Date) => {
    setCurrentMonth(month)
    setSelectedDates([]) // Clear selection when month changes
  }
  
  return (
    <div className="bg-white p-6 md:p-8 rounded-2xl shadow-xl border border-gray-200/50">
      <Tabs value={selectedPlacement} onValueChange={onPlacementChange}>
        <TabsList className="grid w-full grid-cols-3 mb-8 bg-gradient-to-r from-gray-50 to-gray-100 p-1.5 rounded-xl border border-gray-200">
          <TabsTrigger 
            value="top-banner" 
            className="data-[state=active]:bg-white data-[state=active]:shadow-md data-[state=active]:text-blue-700 font-semibold transition-all rounded-lg"
          >
            Premium Sponsored
          </TabsTrigger>
          <TabsTrigger 
            value="right-side"
            className="data-[state=active]:bg-white data-[state=active]:shadow-md data-[state=active]:text-blue-700 font-semibold transition-all rounded-lg"
          >
            Featured
          </TabsTrigger>
          <TabsTrigger 
            value="left-side"
            className="data-[state=active]:bg-white data-[state=active]:shadow-md data-[state=active]:text-blue-700 font-semibold transition-all rounded-lg"
          >
            Sponsored
          </TabsTrigger>
        </TabsList>
        
        <TabsContent value={selectedPlacement} className="mt-0">
          <div className="grid md:grid-cols-2 gap-8 lg:gap-12">
            {/* Calendar Section */}
            <div>
              {loading ? (
                <div className="flex items-center justify-center h-[400px] border-2 border-dashed border-gray-200 rounded-xl bg-gradient-to-br from-gray-50 to-white">
                  <div className="text-center">
                    <div className="relative">
                      <div className="animate-spin rounded-full h-12 w-12 border-4 border-blue-200 border-t-blue-600 mx-auto mb-4"></div>
                      <div className="absolute inset-0 flex items-center justify-center">
                        <div className="w-6 h-6 bg-blue-600 rounded-full animate-pulse"></div>
                      </div>
                    </div>
                    <p className="text-sm font-medium text-gray-700">Loading availability...</p>
                    <p className="text-xs text-gray-500 mt-1">Please wait</p>
                  </div>
                </div>
              ) : (
                <div className="bg-white rounded-2xl shadow-xl border border-gray-200/50 overflow-hidden">
                  <div className="bg-gradient-to-r from-blue-50 via-indigo-50 to-purple-50 px-6 py-5 border-b border-gray-200/50">
                    <div className="flex items-center justify-between">
                      <div>
                        <h4 className="text-base font-bold text-gray-900">Availability Calendar</h4>
                        <p className="text-xs text-gray-600 mt-1">Choose dates to view booking status</p>
                      </div>
                      <div className="flex items-center gap-2 px-3 py-1.5 bg-white/80 rounded-full border border-green-200">
                        <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
                        <span className="text-xs text-gray-700 font-semibold">Live</span>
                      </div>
                    </div>
                  </div>
                  <div className="p-8">
                    <Calendar
                      mode="multiple"
                      selected={selectedDates}
                      onSelect={handleDateSelect}
                      month={currentMonth}
                      onMonthChange={handleMonthChange}
                      modifiers={modifiers}
                      modifiersClassNames={modifiersClassNames}
                      disabled={(date) => {
                        const today = new Date()
                        today.setHours(0, 0, 0, 0)
                        // Disable past dates
                        if (date < today) return true
                        
                        // Disable dates within 48 hours (48-hour booking window)
                        const minBookingDate = new Date(today.getTime() + 48 * 60 * 60 * 1000)
                        if (date < minBookingDate) return true
                        
                        const info = getAvailabilityInfo(date)
                        return info?.status === 'soldout' || false
                      }}
                      className="rounded-lg"
                      classNames={{
                        months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",
                        month: "space-y-4",
                        caption: "flex justify-center pt-1 relative items-center mb-4",
                        caption_label: "text-base font-bold text-gray-900",
                        nav: "space-x-1 flex items-center",
                        button_previous: "absolute left-1 hover:bg-gray-100 rounded-md p-2 transition-colors",
                        button_next: "absolute right-1 hover:bg-gray-100 rounded-md p-2 transition-colors",
                        month_caption: "flex justify-center pt-1 relative items-center",
                        table: "w-full border-collapse space-y-1",
                        head_row: "flex mb-3",
                        head_cell: "text-gray-500 rounded-md w-9 font-semibold text-xs flex-1 text-center",
                        row: "flex w-full mt-2",
                        cell: "text-center text-sm p-0 relative flex-1 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",
                        day: "h-10 w-10 p-0 font-normal aria-selected:opacity-100 hover:bg-gray-100 rounded-md transition-colors flex flex-col items-center justify-center gap-1 relative",
                        day_selected: "bg-blue-600 text-white hover:bg-blue-700 hover:text-white focus:bg-blue-600 focus:text-white",
                        day_today: "bg-gray-100 text-gray-900 font-semibold",
                        day_outside: "text-gray-400 opacity-50",
                        day_disabled: "text-gray-300 opacity-50 cursor-not-allowed",
                        day_range_middle: "aria-selected:bg-accent aria-selected:text-accent-foreground",
                        day_hidden: "invisible"
                      }}
                      formatters={{
                        formatDay: (date) => {
                          return String(date.getDate())
                        }
                      }}
                      components={{
                        DayButton: (props: any) => {
                          const { day, modifiers, children, ...buttonProps } = props
                          const date = day.date
                          const info = getAvailabilityInfo(date)
                          const dateStr = normalizeDate(date)
                          const isSelected = selectedDates.some(d => normalizeDate(d) === dateStr)
                          
                          // Get dot color based on status
                          let dotColor = ''
                          if (info) {
                            if (info.status === 'free') dotColor = 'bg-blue-500'
                            else if (info.status === 'available') dotColor = 'bg-green-500'
                            else if (info.status === 'limited') dotColor = 'bg-yellow-500'
                            else if (info.status === 'soldout') dotColor = 'bg-red-500'
                          }
                          
                          return (
                            <button
                              {...buttonProps}
                              className={cn(
                                props.className,
                                "relative flex flex-col items-center justify-center gap-1"
                              )}
                              title={info ? `${info.bookedSlots}/5 slots booked - ${info.status}` : 'No bookings'}
                              disabled={info?.status === 'soldout'}
                            >
                              {children}
                              {info && info.status !== 'soldout' && (
                                <span className={`w-1.5 h-1.5 rounded-full ${dotColor} ${isSelected ? 'opacity-100' : 'opacity-80'}`}></span>
                              )}
                              {info && info.status === 'soldout' && (
                                <span className="w-1.5 h-1.5 rounded-full bg-red-500 opacity-50"></span>
                              )}
                            </button>
                          )
                        }
                      }}
                    />
                  </div>
                </div>
              )}
            </div>
            
            {/* Legend and Info Section */}
            <div className="space-y-6">
              {/* Legend */}
              <div className="bg-gradient-to-br from-white to-gray-50/50 p-6 rounded-2xl shadow-lg border border-gray-200/50">
                <h3 className="font-bold text-lg mb-5 text-gray-900 flex items-center gap-2">
                  <span className="w-1 h-6 bg-gradient-to-b from-blue-500 to-indigo-600 rounded-full"></span>
                  Availability Status
                </h3>
                <div className="space-y-3">
                  <div className="flex items-center gap-3 p-3 rounded-xl bg-white/80 hover:bg-white transition-all hover:shadow-sm">
                    <div className="flex flex-col items-center gap-1">
                      <div className="w-8 h-8 rounded-md bg-gray-50 border border-gray-200 flex items-center justify-center text-sm font-semibold text-gray-700">
                        16
                      </div>
                      <div className="w-1.5 h-1.5 rounded-full bg-blue-500"></div>
                    </div>
                    <div className="flex-1">
                      <span className="font-bold text-gray-900 block text-sm">Completely Available</span>
                      <p className="text-xs text-gray-600 mt-0.5">0 ads booked</p>
                    </div>
                  </div>
                  <div className="flex items-center gap-3 p-3 rounded-xl bg-white/80 hover:bg-white transition-all hover:shadow-sm">
                    <div className="flex flex-col items-center gap-1">
                      <div className="w-8 h-8 rounded-md bg-gray-50 border border-gray-200 flex items-center justify-center text-sm font-semibold text-gray-700">
                        16
                      </div>
                      <div className="w-1.5 h-1.5 rounded-full bg-green-500"></div>
                    </div>
                    <div className="flex-1">
                      <span className="font-bold text-gray-900 block text-sm">Available</span>
                      <p className="text-xs text-gray-600 mt-0.5">1-2 ads booked</p>
                    </div>
                  </div>
                  <div className="flex items-center gap-3 p-3 rounded-xl bg-white/80 hover:bg-white transition-all hover:shadow-sm">
                    <div className="flex flex-col items-center gap-1">
                      <div className="w-8 h-8 rounded-md bg-gray-50 border border-gray-200 flex items-center justify-center text-sm font-semibold text-gray-700">
                        16
                      </div>
                      <div className="w-1.5 h-1.5 rounded-full bg-yellow-500"></div>
                    </div>
                    <div className="flex-1">
                      <span className="font-bold text-gray-900 block text-sm">Limited</span>
                      <p className="text-xs text-gray-600 mt-0.5">3-4 ads booked</p>
                    </div>
                  </div>
                  <div className="flex items-center gap-3 p-3 rounded-xl bg-white/80 hover:bg-white transition-all hover:shadow-sm">
                    <div className="flex flex-col items-center gap-1">
                      <div className="w-8 h-8 rounded-md bg-gray-50 border border-gray-200 flex items-center justify-center text-sm font-semibold text-gray-700 opacity-60">
                        16
                      </div>
                      <div className="w-1.5 h-1.5 rounded-full bg-red-500 opacity-50"></div>
                    </div>
                    <div className="flex-1">
                      <span className="font-bold text-gray-900 block text-sm">Sold Out</span>
                      <p className="text-xs text-gray-600 mt-0.5">5 ads booked</p>
                    </div>
                  </div>
                </div>
              </div>
              
              {/* Selected Dates Summary */}
              {selectedDates.length > 0 && (
                <div className="bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 p-6 rounded-2xl border border-blue-200/50 shadow-lg">
                  <div className="flex items-center justify-between mb-4">
                    <h4 className="font-bold text-gray-900 flex items-center gap-2 text-lg">
                      <span className="w-2 h-2 bg-blue-600 rounded-full animate-pulse"></span>
                      Selected Dates
                    </h4>
                    <Badge variant="secondary" className="bg-blue-600 text-white border-0 shadow-md font-semibold">
                      {selectedDates.length} {selectedDates.length === 1 ? 'day' : 'days'}
                    </Badge>
                  </div>
                  
                  <div className="space-y-2.5 mb-5 max-h-40 overflow-y-auto pr-2">
                    {selectedDates.slice(0, 5).map((date, idx) => {
                      const info = getAvailabilityInfo(date)
                      return (
                        <div 
                          key={idx} 
                          className="flex items-center justify-between text-sm bg-white/90 p-3 rounded-xl border border-blue-100/50 shadow-sm hover:shadow-md transition-shadow"
                        >
                          <span className="font-semibold text-gray-800">
                            {date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
                          </span>
                          <Badge variant="outline" className="text-xs font-bold border-blue-300 text-blue-700">
                            {info?.bookedSlots || 0}/5 slots
                          </Badge>
                        </div>
                      )
                    })}
                    {selectedDates.length > 5 && (
                      <div className="text-xs text-gray-600 text-center py-2 font-semibold bg-white/60 rounded-lg">
                        +{selectedDates.length - 5} more {selectedDates.length - 5 === 1 ? 'date' : 'dates'}
                      </div>
                    )}
                  </div>
                  
                  <div className="pt-4 border-t border-blue-200/50">
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-sm font-bold text-gray-800">Estimated Cost:</span>
                      <Badge className="bg-gradient-to-r from-blue-600 to-indigo-600 text-white text-lg px-4 py-2 shadow-lg font-bold">
                        ${(() => {
                          const prices: Record<string, number> = {
                            'top-banner': 11,
                            'right-side': 5,
                            'left-side': 7
                          }
                          return selectedDates.length * (prices[selectedPlacement] || 7)
                        })()}
                      </Badge>
                    </div>
                    <p className="text-xs text-gray-600 font-medium">
                      Based on daily rate × {selectedDates.length} {selectedDates.length === 1 ? 'day' : 'days'}
                    </p>
                  </div>
                </div>
              )}
              
              {/* Empty State */}
              {selectedDates.length === 0 && !loading && (
                <div className="text-center py-8 text-gray-500">
                  <div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-3">
                    <svg className="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                    </svg>
                  </div>
                  <p className="text-sm font-medium">Select dates from the calendar</p>
                  <p className="text-xs mt-1">Choose your preferred dates to see pricing</p>
                </div>
              )}
            </div>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  )
}


