'use client'

import { useState, useMemo } from 'react'
import { useRouter } from 'next/navigation'
import { useAdBookings } from '@/hooks/use-ad-bookings'
import { useBooking } from '@/contexts/booking-context'
import { Calendar } from '@/components/ui/calendar'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { cn } from '@/lib/utils'
import { Calendar as CalendarIcon, CheckCircle2, AlertCircle, XCircle } from 'lucide-react'

interface ProfessionalBookingCalendarProps {
  selectedPlacement: string
  onPlacementChange: (placement: string) => void
  onDatesSelected?: (dates: Date[]) => void
}

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

export function ProfessionalBookingCalendar({
  selectedPlacement,
  onPlacementChange,
  onDatesSelected
}: ProfessionalBookingCalendarProps) {
  const router = useRouter()
  const { setBookingData } = useBooking()
  const [selectedDates, setSelectedDates] = useState<Date[]>([])
  const [currentMonth, setCurrentMonth] = useState<Date>(new Date())
  const [isNavigating, setIsNavigating] = useState(false)
  
  // Use cached bookings data
  const { bookingsData, loading, getAvailability } = useAdBookings(6)
  
  // Get placement details
  const placementDetails: Record<string, { name: string; price: number; dimensions: string }> = {
    'top-banner': { name: 'Premium Sponsored', price: 11, dimensions: '1200x450px' },
    'right-side': { name: 'Featured Ad', price: 5, dimensions: '320x600px' },
    'left-side': { name: 'Sponsored Ad', price: 7, dimensions: '320x600px' }
  }
  
  const currentPlacement = placementDetails[selectedPlacement]
  
  // 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])
  
  // Group dates by status for the right panel
  const groupedDates = useMemo(() => {
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    
    const futureDates = availability.filter(item => {
      const [year, month, day] = item.date.split('-').map(Number)
      const date = new Date(year, month - 1, day)
      return date >= today
    })
    
    return {
      free: futureDates.filter(d => d.status === 'free'),
      available: futureDates.filter(d => d.status === 'available'),
      limited: futureDates.filter(d => d.status === 'limited'),
      soldout: futureDates.filter(d => d.status === 'soldout')
    }
  }, [availability])
  
  // Normalize date to YYYY-MM-DD format
  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
  const handleDateSelect = (date: Date | undefined) => {
    if (!date) return
    
    const info = getAvailabilityInfo(date)
    if (info?.status === 'soldout') return
    
    const dateStr = normalizeDate(date)
    const isSelected = selectedDates.some(d => normalizeDate(d) === dateStr)
    
    let newDates: Date[]
    if (isSelected) {
      newDates = selectedDates.filter(d => normalizeDate(d) !== dateStr)
    } else {
      newDates = [...selectedDates, date]
    }
    
    setSelectedDates(newDates)
    onDatesSelected?.(newDates)
  }
  
  // Format date for display
  const formatDate = (dateStr: string) => {
    const [year, month, day] = dateStr.split('-').map(Number)
    const date = new Date(year, month - 1, day)
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
  }
  
  return (
    <div className="bg-white rounded-2xl shadow-xl border border-gray-200/50 overflow-hidden">
      <Tabs value={selectedPlacement} onValueChange={onPlacementChange}>
        <div className="bg-gradient-to-r from-blue-50 via-indigo-50 to-purple-50 px-6 py-4 border-b border-gray-200/50">
          <TabsList className="grid w-full grid-cols-3 bg-white/80 p-1.5 rounded-xl border border-gray-200 shadow-sm">
            <TabsTrigger 
              value="top-banner" 
              className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-blue-600 data-[state=active]:to-indigo-600 data-[state=active]:text-white font-semibold transition-all rounded-lg text-xs md:text-sm"
            >
              Premium
            </TabsTrigger>
            <TabsTrigger 
              value="right-side"
              className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-blue-600 data-[state=active]:to-indigo-600 data-[state=active]:text-white font-semibold transition-all rounded-lg text-xs md:text-sm"
            >
              Featured
            </TabsTrigger>
            <TabsTrigger 
              value="left-side"
              className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-blue-600 data-[state=active]:to-indigo-600 data-[state=active]:text-white font-semibold transition-all rounded-lg text-xs md:text-sm"
            >
              Sponsored
            </TabsTrigger>
          </TabsList>
          
          <div className="mt-4 flex items-center justify-between">
            <div>
              <h3 className="font-bold text-gray-900 text-lg">{currentPlacement.name}</h3>
              <p className="text-sm text-gray-600">${currentPlacement.price}/day • {currentPlacement.dimensions}</p>
            </div>
            <Badge className="bg-green-500 text-white border-0 shadow-md">
              <div className="w-2 h-2 bg-white rounded-full animate-pulse mr-1.5"></div>
              Live
            </Badge>
          </div>
        </div>
        
        <TabsContent value={selectedPlacement} className="mt-0">
          {loading ? (
            <div className="flex items-center justify-center h-[500px] p-6">
              <div className="text-center">
                <div className="animate-spin rounded-full h-12 w-12 border-4 border-blue-200 border-t-blue-600 mx-auto mb-4"></div>
                <p className="text-sm font-medium text-gray-700">Loading availability...</p>
              </div>
            </div>
          ) : (
            <div className="space-y-6 p-6">
              {/* Availability Info Row - Above Calendar */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                {/* Legend */}
                <Card className="shadow-sm">
                  <CardHeader className="pb-3">
                    <CardTitle className="text-sm font-bold text-gray-900">Legend</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-2 text-xs">
                      <div className="flex items-center gap-2">
                        <div className="w-2 h-2 rounded-full bg-blue-500"></div>
                        <span className="text-gray-700">Free</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <div className="w-2 h-2 rounded-full bg-green-500"></div>
                        <span className="text-gray-700">Available</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <div className="w-2 h-2 rounded-full bg-yellow-500"></div>
                        <span className="text-gray-700">Limited</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <div className="w-2 h-2 rounded-full bg-red-500"></div>
                        <span className="text-gray-700">Sold Out</span>
                      </div>
                    </div>
                  </CardContent>
                </Card>
                
                {/* Available Dates */}
                <Card className="shadow-sm">
                  <CardHeader className="pb-3">
                    <CardTitle className="text-sm font-bold text-gray-900 flex items-center justify-between">
                      <span className="flex items-center gap-2">
                        <CheckCircle2 className="w-4 h-4 text-green-600" />
                        Available Dates
                      </span>
                      <Badge variant="secondary" className="text-xs">
                        {groupedDates.free.length + groupedDates.available.length}
                      </Badge>
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="max-h-[120px] overflow-y-auto space-y-1 pr-2">
                      {groupedDates.free.length > 0 || groupedDates.available.length > 0 ? (
                        <>
                          {[...groupedDates.free, ...groupedDates.available].slice(0, 10).map((item) => (
                            <div key={item.date} className="flex items-center justify-between text-xs py-1 px-2 hover:bg-green-50 rounded transition-colors">
                              <span className="text-gray-700 font-medium">{formatDate(item.date)}</span>
                              <Badge variant="outline" className="text-[10px] border-green-300 text-green-700">
                                {item.availableSlots} slots
                              </Badge>
                            </div>
                          ))}
                          {(groupedDates.free.length + groupedDates.available.length) > 10 && (
                            <p className="text-[10px] text-gray-500 text-center pt-1">
                              +{(groupedDates.free.length + groupedDates.available.length) - 10} more
                            </p>
                          )}
                        </>
                      ) : (
                        <p className="text-xs text-gray-500 text-center py-2">No available dates</p>
                      )}
                    </div>
                  </CardContent>
                </Card>
                
                {/* Sold Out Dates */}
                <Card className="shadow-sm border-red-100 bg-red-50/50">
                  <CardHeader className="pb-3">
                    <CardTitle className="text-sm font-bold text-gray-900 flex items-center justify-between">
                      <span className="flex items-center gap-2">
                        <XCircle className="w-4 h-4 text-red-600" />
                        Sold Out
                      </span>
                      <Badge variant="secondary" className="text-xs bg-red-100 text-red-800 border-red-200">
                        {groupedDates.soldout.length}
                      </Badge>
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="flex flex-wrap gap-1.5 max-h-[120px] overflow-y-auto pr-2">
                      {groupedDates.soldout.length > 0 ? (
                        <>
                          {groupedDates.soldout.slice(0, 10).map((item) => (
                            <Badge key={item.date} variant="secondary" className="text-[10px] bg-red-50 text-red-700 border border-red-200">
                              {formatDate(item.date)}
                            </Badge>
                          ))}
                          {groupedDates.soldout.length > 10 && (
                            <Badge variant="secondary" className="text-[10px] bg-gray-100 text-gray-600">
                              +{groupedDates.soldout.length - 10}
                            </Badge>
                          )}
                        </>
                      ) : (
                        <p className="text-xs text-gray-500 py-2">No sold out dates</p>
                      )}
                    </div>
                  </CardContent>
                </Card>
              </div>
              
              {/* Calendar & Selection Section - Same Row */}
              <div className="grid lg:grid-cols-2 gap-6">
                <div className="bg-gradient-to-br from-gray-50 to-white p-6 rounded-xl border border-gray-200">
                  <div className="flex items-center justify-between mb-4">
                    <h4 className="font-bold text-gray-900 flex items-center gap-2">
                      <CalendarIcon className="w-5 h-5 text-blue-600" />
                      Select Dates
                    </h4>
                    {selectedDates.length > 0 && (
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => setSelectedDates([])}
                        className="text-xs text-red-600 hover:text-red-700 hover:bg-red-50"
                      >
                        Clear All
                      </Button>
                    )}
                  </div>
                  
                  <Calendar
                  mode="multiple"
                  selected={selectedDates}
                  onSelect={(dates) => {
                    if (dates) {
                      setSelectedDates(dates)
                      onDatesSelected?.(dates)
                    }
                  }}
                  month={currentMonth}
                  onMonthChange={setCurrentMonth}
                  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'
                  }}
                  className="rounded-lg"
                  classNames={{
                    months: "flex flex-col",
                    month: "space-y-4 w-full",
                    caption: "flex justify-center relative items-center mb-4",
                    caption_label: "text-lg font-bold text-gray-900",
                    nav: "flex items-center gap-1",
                    button_previous: "absolute left-0 hover:bg-gray-100 rounded-md p-2 transition-colors",
                    button_next: "absolute right-0 hover:bg-gray-100 rounded-md p-2 transition-colors",
                    table: "w-full border-collapse",
                    head_row: "flex w-full",
                    head_cell: "text-gray-500 rounded-md flex-1 font-semibold text-xs text-center py-2",
                    row: "flex w-full mt-1 gap-1",
                    cell: "flex-1 text-center text-sm p-0 relative",
                    day: "min-h-[44px] w-full p-1 font-normal hover:opacity-80 rounded-lg transition-all flex items-center justify-center",
                    day_selected: "bg-blue-600 text-white hover:bg-blue-700 font-bold",
                    day_today: "ring-2 ring-gray-400 font-bold",
                    day_outside: "text-gray-300 opacity-50",
                    day_disabled: "!bg-gray-100 !text-gray-300 opacity-50 cursor-not-allowed hover:opacity-50 !border-gray-200",
                  }}
                  components={{
                    DayButton: (props: any) => {
                      const { day, ...buttonProps } = props
                      const date = day.date
                      const info = getAvailabilityInfo(date)
                      const dateStr = normalizeDate(date)
                      const isSelected = selectedDates.some(d => normalizeDate(d) === dateStr)
                      
                      // Determine background color based on status
                      let bgColor = ''
                      let textColor = 'text-gray-900'
                      let dotColor = 'bg-blue-500'
                      let borderColor = ''
                      
                      if (info) {
                        if (info.status === 'soldout') {
                          bgColor = 'bg-red-100'
                          textColor = 'text-red-400'
                          dotColor = 'bg-red-500'
                          borderColor = 'border border-red-300'
                        } else if (info.status === 'limited') {
                          bgColor = isSelected ? '' : 'bg-yellow-50'
                          dotColor = 'bg-yellow-500'
                          borderColor = isSelected ? '' : 'border border-yellow-200'
                        } else if (info.status === 'available') {
                          bgColor = isSelected ? '' : 'bg-green-50'
                          dotColor = 'bg-green-500'
                          borderColor = isSelected ? '' : 'border border-green-200'
                        } else if (info.status === 'free') {
                          bgColor = isSelected ? '' : 'bg-blue-50'
                          dotColor = 'bg-blue-500'
                          borderColor = isSelected ? '' : 'border border-blue-200'
                        }
                      }
                      
                      return (
                        <button
                          {...buttonProps}
                          className={cn(
                            buttonProps.className,
                            "relative min-h-[44px]",
                            bgColor,
                            borderColor,
                            textColor,
                            isSelected && "!bg-blue-600 !text-white ring-2 ring-blue-600 ring-offset-1 !border-blue-600"
                          )}
                          title={info ? `${info.status.toUpperCase()}: ${info.availableSlots} slots available (${info.bookedSlots}/5 booked)` : 'No data'}
                        >
                          <div className="flex flex-col items-center justify-center gap-0.5">
                            <span className={cn("text-sm font-semibold", isSelected && "text-white")}>{day.date.getDate()}</span>
                            {info && (
                              <span className={cn(
                                "w-1.5 h-1.5 rounded-full",
                                isSelected ? "bg-white" : dotColor
                              )}></span>
                            )}
                          </div>
                        </button>
                      )
                    }
                  }}
                />
                </div>
                
                {/* Your Selection - Right side of calendar */}
                <div className="space-y-4">
                  {selectedDates.length > 0 ? (
                    <Card className="bg-gradient-to-br from-blue-50 to-indigo-50 border-blue-200 shadow-md">
                      <CardHeader className="pb-3">
                        <CardTitle className="text-sm font-bold text-gray-900 flex items-center justify-between">
                          Your Selection
                          <Badge className="bg-blue-600 hover:bg-blue-700">{selectedDates.length} {selectedDates.length === 1 ? 'day' : 'days'}</Badge>
                        </CardTitle>
                      </CardHeader>
                      <CardContent>
                        <div className="space-y-3">
                          <div className="max-h-[300px] overflow-y-auto pr-2 space-y-1.5">
                            {selectedDates.sort((a, b) => a.getTime() - b.getTime()).map((date, idx) => (
                              <div key={idx} className="flex items-center justify-between text-xs bg-white/60 px-3 py-2 rounded">
                                <span className="text-gray-700 font-medium">
                                  {date.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' })}
                                </span>
                                <span className="text-gray-600 font-semibold">${currentPlacement.price}</span>
                              </div>
                            ))}
                          </div>
                          <div className="flex items-center justify-between pt-3 border-t border-blue-200">
                            <span className="text-sm font-bold text-gray-900">Total Cost:</span>
                            <span className="text-2xl font-bold text-blue-600">
                              ${selectedDates.length * currentPlacement.price}
                            </span>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  ) : (
                    <Card className="border-dashed border-2 border-gray-300 bg-gray-50/50">
                      <CardContent className="pt-6">
                        <div className="text-center py-8">
                          <CalendarIcon className="w-12 h-12 text-gray-400 mx-auto mb-3" />
                          <p className="text-sm font-medium text-gray-600 mb-1">No dates selected</p>
                          <p className="text-xs text-gray-500">Click on available dates to select</p>
                        </div>
                      </CardContent>
                    </Card>
                  )}
                  
                  {/* Limited Dates Info */}
                  {groupedDates.limited.length > 0 && (
                    <Card className="shadow-sm border-yellow-100 bg-yellow-50/50">
                      <CardHeader className="pb-3">
                        <CardTitle className="text-xs font-bold text-gray-900 flex items-center gap-2">
                          <AlertCircle className="w-3 h-3 text-yellow-600" />
                          Limited Availability
                        </CardTitle>
                      </CardHeader>
                      <CardContent>
                        <div className="space-y-1">
                          {groupedDates.limited.slice(0, 5).map((item) => (
                            <div key={item.date} className="flex items-center justify-between text-[10px] py-1">
                              <span className="text-gray-700 font-medium">{formatDate(item.date)}</span>
                              <Badge variant="outline" className="text-[9px] border-yellow-300 text-yellow-700 h-4">
                                {item.availableSlots} left
                              </Badge>
                            </div>
                          ))}
                        </div>
                      </CardContent>
                    </Card>
                  )}
                </div>
              </div>
              
              {/* Create Campaign Button */}
              {selectedDates.length > 0 && (
                <div className="flex justify-center pt-4">
                  <Button
                    size="lg"
                    disabled={isNavigating}
                    className="bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white font-bold px-12 py-6 text-lg rounded-xl shadow-lg hover:shadow-xl transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                    onClick={(e) => {
                      e.preventDefault()
                      e.stopPropagation()
                      
                      if (isNavigating) return
                      
                      setIsNavigating(true)
                      
                      try {
                        // Sort dates chronologically
                        const sortedDates = [...selectedDates].sort((a, b) => a.getTime() - b.getTime())
                        
                        // Calculate total cost
                        const totalCost = sortedDates.length * currentPlacement.price
                        
                        // Prepare booking data
                        const bookingDataToSave = {
                          selectedDates: sortedDates,
                          placementType: selectedPlacement,
                          totalCost,
                          placementDetails: {
                            name: currentPlacement.name,
                            price: currentPlacement.price,
                            dimensions: currentPlacement.dimensions
                          }
                        }
                        
                        console.log('[ProfessionalBookingCalendar] Saving booking to context:', bookingDataToSave)
                        
                        // Save booking data to context
                        setBookingData(bookingDataToSave)
                        
                        // Small delay to ensure context is saved
                        setTimeout(() => {
                          console.log('[ProfessionalBookingCalendar] Navigating to /advertise/create')
                          router.push('/advertise/create')
                        }, 100)
                        
                      } catch (error) {
                        console.error('[ProfessionalBookingCalendar] Error saving booking:', error)
                        setIsNavigating(false)
                      }
                    }}
                  >
                    {isNavigating ? 'Loading...' : 'Create Campaign'}
                  </Button>
                </div>
              )}
            </div>
          )}
        </TabsContent>
      </Tabs>
    </div>
  )
}

