'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { useBooking } from '@/contexts/booking-context'
import { useAdBookings } from '@/hooks/use-ad-bookings'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { cn } from '@/lib/utils'
import { Upload, AlertCircle, ChevronDown, ChevronUp } from 'lucide-react'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { SelectedDatesCard } from '@/components/advertise/selected-dates-card'
import { ProfessionalBookingCalendar } from '@/components/advertise/professional-booking-calendar'

interface AdSubmissionFormProps {
  onSuccess?: () => void
}

// Helper to convert Date to date-only string in local timezone
// This prevents timezone conversion issues where toISOString() would subtract hours
// Example: Dec 30 00:00 PKT would become Dec 29 19:00 UTC with toISOString()
const getLocalDateString = (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}`
}

export function AdSubmissionForm({ onSuccess }: AdSubmissionFormProps) {
  const router = useRouter()
  const { bookingData, setBookingData, clearBookingData, updateDates, isBookingValid, isDatesExpired } = useBooking()
  const { getDateRangeAvailability } = useAdBookings(6)

  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState(false)
  const [showCalendar, setShowCalendar] = useState(false)

  const [formData, setFormData] = useState({
    businessName: '',
    email: '',
    description: '',
    imageUrl: '',
    targetUrl: '',
    location: '',
    category: '',
    placementType: bookingData?.placementType || 'top-banner'
  })

  const [imageFile, setImageFile] = useState<File | null>(null)
  const [imagePreview, setImagePreview] = useState<string>('')

  // Initialize form with booking data
  useEffect(() => {
    if (bookingData) {
      console.log('[AdSubmissionForm] Loaded booking data:', bookingData)
      setFormData(prev => ({
        ...prev,
        placementType: bookingData.placementType
      }))

      // Check if dates expired
      if (isDatesExpired()) {
        setError('Your selected dates have expired. Please select new dates.')
      }
    }
  }, [bookingData, isDatesExpired])

  // Redirect if no booking data
  const hasNoBooking = !bookingData || !isBookingValid()

  const placementTypes = [
    { value: 'top-banner', label: 'Premium Sponsored Ad - $11/day', dimensions: '1200x450px' },
    { value: 'right-side', label: 'Featured Ad - $5/day (Not visible on mobile)', dimensions: '320x600px' },
    { value: 'left-side', label: 'Sponsored Ad - $7/day', dimensions: '320x600px' }
  ]

  const categories = [
    'Assisted Living',
    'Memory Care',
    'Independent Living',
    'Skilled Nursing',
    'Continuing Care',
    'Boarding Home'
  ]

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      setImageFile(file)
      const reader = new FileReader()
      reader.onloadend = () => {
        setImagePreview(reader.result as string)
      }
      reader.readAsDataURL(file)
    }
  }

  const handleChangeDates = () => {
    setShowCalendar(!showCalendar)
  }

  const handleDatesUpdated = (dates: Date[]) => {
    if (dates.length > 0) {
      updateDates(dates)
      setShowCalendar(false)
      setError('')
    }
  }

  const handlePlacementTypeChange = (newPlacementType: string) => {
    // When placement type changes in collapsible calendar, need to update booking context
    if (!bookingData) return

    const placementTypeDetails: 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 newDetails = placementTypeDetails[newPlacementType]
    const newTotalCost = bookingData.selectedDates.length * newDetails.price

    // Update the entire booking with new placement type
    setBookingData({
      selectedDates: bookingData.selectedDates,
      placementType: newPlacementType,
      totalCost: newTotalCost,
      placementDetails: newDetails
    })

    console.log('[AdSubmissionForm] Placement type changed to:', newPlacementType)
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    console.log('Form submission started')
    setError('')
    setIsSubmitting(true)

    try {
      // Validate booking data exists
      if (!bookingData || !isBookingValid()) {
        throw new Error('No dates selected. Please select dates first.')
      }

      // Check if dates expired
      if (isDatesExpired()) {
        throw new Error('Your selected dates have expired. Please select new dates.')
      }

      // Validate all required fields
      if (!formData.businessName) {
        throw new Error('Please enter business name')
      }

      if (!formData.email) {
        throw new Error('Please enter your email')
      }

      if (!formData.targetUrl) {
        throw new Error('Please enter target URL')
      }

      // Normalize URL - add https:// if missing
      let normalizedUrl = formData.targetUrl.trim()
      if (!normalizedUrl.match(/^https?:\/\//i)) {
        normalizedUrl = `https://${normalizedUrl}`
      }

      // Validate image
      if (!imageFile) {
        throw new Error('Please upload an ad image')
      }

      // Get dates from booking context
      const sortedDates = [...bookingData.selectedDates].sort((a, b) => a.getTime() - b.getTime())
      const startDate = sortedDates[0]
      const endDate = sortedDates[sortedDates.length - 1]

      console.log('Uploading image...')
      // Upload image first
      const formDataImg = new FormData()
      formDataImg.append('file', imageFile)

      const uploadRes = await fetch('/api/upload', {
        method: 'POST',
        body: formDataImg
      })

      if (!uploadRes.ok) {
        const uploadError = await uploadRes.json()
        throw new Error(uploadError.error || 'Failed to upload image')
      }

      const uploadData = await uploadRes.json()
      const imageUrl = uploadData.url
      console.log('Image uploaded:', imageUrl)

      console.log('Re-checking availability...')
      // Re-validate dates availability (security check)
      const rangeAvailability = getDateRangeAvailability(startDate, endDate, bookingData.placementType)
      if (!rangeAvailability.isBookable) {
        throw new Error(`Sorry, some dates are no longer available: ${rangeAvailability.soldOutDates.join(', ')}. Please select new dates.`)
      }

      // Verify with API as final check
      const availabilityRes = await fetch('/api/ads/availability', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          placementType: bookingData.placementType,
          startDate: getLocalDateString(startDate),  // Use date-only format
          endDate: getLocalDateString(endDate)
        })
      })

      if (availabilityRes.ok) {
        const availabilityData = await availabilityRes.json()
        if (!availabilityData.isBookable) {
          const soldOutDatesList = availabilityData.soldOutDates || []
          throw new Error(`Sorry, some dates in your selected range are sold out: ${soldOutDatesList.join(', ')}. Please choose different dates.`)
        }
      }

      console.log('Creating ad campaign...')
      // Create ad campaign
      const createRes = await fetch('/api/ads/create', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...formData,
          facilityName: formData.businessName, // Keep for API compatibility
          targetUrl: normalizedUrl,
          imageUrl,
          placementType: bookingData.placementType, // Use booking context placement type
          startDate: getLocalDateString(startDate),  // Use date-only format
          endDate: getLocalDateString(endDate)
        })
      })

      if (!createRes.ok) {
        const errorData = await createRes.json().catch(() => ({ error: 'Server error' }))
        console.error('Create ad error:', errorData)
        throw new Error(errorData.error || 'Failed to create ad campaign')
      }

      const result = await createRes.json()
      console.log('Ad created successfully:', result)

      // Store ad details in session storage for payment page
      sessionStorage.setItem('pendingAdDetails', JSON.stringify({
        facilityName: formData.businessName,
        placementType: formData.placementType,
        duration: result.duration,
        totalCost: result.totalCost
      }))

      // Clear booking data after successful creation
      clearBookingData()

      // Redirect to payment page
      const paymentUrl = `/advertise/payment?adId=${result.adId}&clientSecret=${result.clientSecret}`
      console.log('Redirecting to payment:', paymentUrl)
      router.push(paymentUrl)

    } catch (err: any) {
      setError(err.message || 'Something went wrong. Please try again.')
    } finally {
      setIsSubmitting(false)
    }
  }

  // Show empty state if no booking data
  if (hasNoBooking) {
    return (
      <Card className="w-full max-w-4xl mx-auto">
        <CardHeader>
          <CardTitle className="text-3xl">Create Ad Campaign</CardTitle>
          <CardDescription>
            Select dates first to create your campaign
          </CardDescription>
        </CardHeader>
        <CardContent className="py-12 text-center">
          <div className="flex flex-col items-center gap-4">
            <div className="w-16 h-16 rounded-full bg-blue-100 flex items-center justify-center">
              <AlertCircle className="w-8 h-8 text-blue-600" />
            </div>
            <div>
              <h3 className="text-lg font-bold text-gray-900 mb-2">No Dates Selected</h3>
              <p className="text-gray-600 mb-6">
                Please select your campaign dates first using the booking calendar.
              </p>
              <Button
                size="lg"
                onClick={() => router.push('/advertise')}
                className="bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700"
              >
                Select Dates
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>
    )
  }

  return (
    <Card className="w-full max-w-4xl mx-auto">
      <CardHeader>
        <CardTitle className="text-3xl">Create Ad Campaign</CardTitle>
        <CardDescription>
          Fill in the details below to create your advertising campaign
        </CardDescription>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* Selected Dates Card */}
          <SelectedDatesCard
            selectedDates={bookingData!.selectedDates}
            placementType={bookingData!.placementType}
            placementDetails={bookingData!.placementDetails}
            totalCost={bookingData!.totalCost}
            onChangeDates={handleChangeDates}
            showChangeButton={true}
          />

          {/* Collapsible Calendar Section */}
          {showCalendar && (
            <div className="space-y-4 border rounded-lg p-4 bg-gray-50">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-semibold flex items-center gap-2">
                  Change Dates
                </h3>
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  onClick={() => setShowCalendar(false)}
                >
                  <ChevronUp className="w-4 h-4 mr-1" />
                  Collapse
                </Button>
              </div>
              <ProfessionalBookingCalendar
                selectedPlacement={bookingData!.placementType}
                onPlacementChange={handlePlacementTypeChange}
                onDatesSelected={handleDatesUpdated}
              />
            </div>
          )}

          {/* Error Alert */}
          {error && (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          {/* Success Alert */}
          {success && (
            <Alert className="bg-green-50 border-green-200">
              <AlertDescription className="text-green-800">
                Ad campaign created successfully! Redirecting...
              </AlertDescription>
            </Alert>
          )}

          {/* Business Name */}
          <div className="space-y-2">
            <Label htmlFor="businessName">Business Name *</Label>
            <Input
              id="businessName"
              placeholder="Enter your business or organization name"
              value={formData.businessName}
              onChange={(e) => setFormData({ ...formData, businessName: e.target.value })}
              required
            />
            <p className="text-sm text-gray-500">Your business, organization, or service name</p>
          </div>

          {/* Email */}
          <div className="space-y-2">
            <Label htmlFor="email">Contact Email *</Label>
            <Input
              id="email"
              type="email"
              placeholder="your@email.com"
              value={formData.email}
              onChange={(e) => setFormData({ ...formData, email: e.target.value })}
              required
            />
            <p className="text-sm text-gray-500">We'll contact you at this email about your ad submission</p>
          </div>

          {/* Description */}
          <div className="space-y-2">
            <Label htmlFor="description">Description</Label>
            <Textarea
              id="description"
              placeholder="Describe your business and what makes it special... (optional)"
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              maxLength={500}
              rows={4}
            />
            <p className="text-sm text-gray-500">{formData.description.length}/500 characters</p>
          </div>

          {/* Location */}
          <div className="space-y-2">
            <Label htmlFor="location">Location</Label>
            <Input
              id="location"
              placeholder="City, State (optional)"
              value={formData.location}
              onChange={(e) => setFormData({ ...formData, location: e.target.value })}
            />
          </div>

          {/* Category */}
          <div className="space-y-2">
            <Label htmlFor="category">Category</Label>
            <Select
              value={formData.category}
              onValueChange={(value) => setFormData({ ...formData, category: value })}
            >
              <SelectTrigger>
                <SelectValue placeholder="Select category (optional)" />
              </SelectTrigger>
              <SelectContent>
                {categories.map((cat) => (
                  <SelectItem key={cat} value={cat}>
                    {cat}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {/* Target URL */}
          <div className="space-y-2">
            <Label htmlFor="targetUrl">Target URL *</Label>
            <Input
              id="targetUrl"
              type="text"
              placeholder="https://yourwebsite.com or www.yourwebsite.com"
              value={formData.targetUrl}
              onChange={(e) => setFormData({ ...formData, targetUrl: e.target.value })}
              required
            />
            <p className="text-sm text-gray-500">Where should the ad link to? (http:// or https:// will be added automatically if missing)</p>
          </div>

          {/* Placement Type - Read Only from Context */}
          <div className="space-y-2">
            <Label>Ad Placement Type (From Booking)</Label>
            <div className="p-3 bg-gray-50 border rounded-md">
              <div className="flex flex-col">
                <span className="font-medium text-gray-900">
                  {placementTypes.find(t => t.value === bookingData!.placementType)?.label || 'Unknown Type'}
                </span>
                <span className="text-xs text-gray-500 mt-0.5">
                  {placementTypes.find(t => t.value === bookingData!.placementType)?.dimensions}
                </span>
              </div>
            </div>
            <p className="text-sm text-gray-500">To change placement type, update your booking dates</p>
          </div>

          {/* Image Upload */}
          <div className="space-y-2">
            <Label htmlFor="image">Ad Image *</Label>
            <div className="flex items-center gap-4">
              <Button
                type="button"
                variant="outline"
                onClick={() => document.getElementById('image-input')?.click()}
                className="flex items-center gap-2"
              >
                <Upload className="h-4 w-4" />
                Upload Image
              </Button>
              <input
                id="image-input"
                type="file"
                accept="image/*"
                className="hidden"
                onChange={handleImageChange}
              />
              <span className="text-sm text-gray-500">
                {imageFile ? imageFile.name : 'No file chosen'}
              </span>
            </div>
            {imagePreview && (
              <div className="mt-4">
                <img
                  src={imagePreview}
                  alt="Preview"
                  className="max-w-md rounded-lg border"
                />
              </div>
            )}
            <p className="text-sm text-gray-500">
              Recommended: {placementTypes.find(t => t.value === bookingData!.placementType)?.dimensions}
            </p>
          </div>


          {/* Submit Button */}
          <Button
            type="submit"
            className="w-full bg-[#3F5CEA] hover:bg-[#09183D] text-lg py-6"
            disabled={isSubmitting || success}
          >
            {isSubmitting ? 'Creating Campaign...' : `Create Campaign & Pay $${bookingData!.totalCost}`}
          </Button>

          <p className="text-sm text-gray-500 text-center">
            Payment will be authorized now and captured after admin approval.
            Full refund if rejected.
          </p>
        </form>
      </CardContent>
    </Card>
  )
}


