'use client'

import { useState, useEffect } from 'react'
import { useRouter, useParams } from 'next/navigation'
import { ArrowLeft, Save, Eye, Upload, X, Trash2, Calendar, MapPin } from 'lucide-react'
import Image from 'next/image'
import { isAuthenticated } from '@/lib/auth'
import { apiGet, apiPut, apiDelete } from '@/lib/apiClient'
import { API_BASE_URL } from '@/config/api'
import { useToast } from '@/components/admin/Toast'
import LoadingSpinner from '@/components/LoadingSpinner'
import { formatFileSize } from '@/lib/imageUtils'

interface Event {
  _id: string
  title: string
  description: string
  content: string
  startDate: string
  endDate?: string
  location: string
  imageUrl?: string
  link?: string
  category: string
  tags: string[]
  isFeatured: boolean
  isPublished: boolean
  order: number
}

export default function EditEventPage() {
  const router = useRouter()
  const params = useParams()
  const eventId = params.id as string

  const { showToast, updateToast, dismissToast } = useToast()
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [uploading, setUploading] = useState(false)
  const [imagePreview, setImagePreview] = useState<string>('')
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    content: '',
    startDate: '',
    endDate: '',
    location: '',
    imageUrl: '',
    link: '',
    category: 'general',
    tags: '',
    isFeatured: false,
    isPublished: false,
    order: 0,
  })

  useEffect(() => {
    if (!isAuthenticated()) {
      router.push('/admin')
      return
    }
    fetchEvent()
  }, [eventId, router])

  const fetchEvent = async () => {
    try {
      const result = await apiGet<Event>(`/events/${eventId}`)
      if (result.success && result.data) {
        const event = result.data
        // Format dates for datetime-local input
        const formatDateForInput = (dateString: string) => {
          if (!dateString) return ''
          const date = new Date(dateString)
          const year = date.getFullYear()
          const month = String(date.getMonth() + 1).padStart(2, '0')
          const day = String(date.getDate()).padStart(2, '0')
          const hours = String(date.getHours()).padStart(2, '0')
          const minutes = String(date.getMinutes()).padStart(2, '0')
          return `${year}-${month}-${day}T${hours}:${minutes}`
        }

        setFormData({
          title: event.title,
          description: event.description,
          content: event.content || '',
          startDate: formatDateForInput(event.startDate),
          endDate: event.endDate ? formatDateForInput(event.endDate) : '',
          location: event.location || '',
          imageUrl: event.imageUrl || '',
          link: event.link || '',
          category: event.category || 'general',
          tags: event.tags?.join(', ') || '',
          isFeatured: event.isFeatured || false,
          isPublished: event.isPublished || false,
          order: event.order || 0,
        })
        if (event.imageUrl) {
          setImagePreview(event.imageUrl)
        }
      }
    } catch (error: any) {
      console.error('Error fetching event:', error)
      alert(error.message || 'Failed to load event')
      router.push('/admin/events')
    } finally {
      setLoading(false)
    }
  }

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value, type } = e.target
    const checked = (e.target as HTMLInputElement).checked

    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value,
    }))
  }

  const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return

    // Show local preview immediately
    const reader = new FileReader()
    reader.onloadend = () => {
      setImagePreview(reader.result as string)
    }
    reader.readAsDataURL(file)

    // Upload to backend
    let toastId = ''
    try {
      setUploading(true)

      const { prepareImageForUpload } = await import('@/lib/imageUtils')
      if (file.size > 5 * 1024 * 1024) {
        toastId = showToast({ type: 'compressing', title: 'Optimizing image...', message: `Compressing ${formatFileSize(file.size)} image for upload`, duration: 0 })
      }

      const result = await prepareImageForUpload(file)

      if (result.wasCompressed && toastId) {
        updateToast(toastId, { type: 'info', title: 'Image compressed', message: `${formatFileSize(result.originalSize)} → ${formatFileSize(result.finalSize)}`, duration: 3000 })
      } else if (toastId) { dismissToast(toastId) }

      toastId = showToast({ type: 'info', title: 'Uploading image...', message: `Sending ${formatFileSize(result.finalSize)} to server`, duration: 0 })

      const uploadFormData = new FormData()
      uploadFormData.append('type', 'events')
      uploadFormData.append('image', result.file)

      const { apiUpload } = await import('@/lib/apiClient')
      
      const uploadResult = await apiUpload('/upload/image?type=events', uploadFormData, {
        headers: { 'x-upload-type': 'events' }
      })

      if (uploadResult.success && uploadResult.data) {
        const fullUrl = uploadResult.data.fullUrl
        setFormData(prev => ({ ...prev, imageUrl: fullUrl }))
        updateToast(toastId, { type: 'success', title: 'Image uploaded successfully', duration: 3000 })
      } else {
        dismissToast(toastId)
        showToast({ type: 'error', title: 'Upload failed', message: uploadResult.message || 'The server could not process the image. Please try again.' })
        setImagePreview('')
      }
    } catch (error: any) {
      console.error('Upload error:', error)
      if (toastId) dismissToast(toastId)
      showToast({ type: 'error', title: 'Image upload failed', message: error.message || 'Something went wrong. Please try a different image.' })
      setImagePreview('')
    } finally {
      setUploading(false)
    }
  }

  const handleSubmit = async (e: React.FormEvent, publish = false) => {
    e.preventDefault()
    setSaving(true)

    try {
      const dataToSend = {
        ...formData,
        tags: formData.tags.split(',').map(tag => tag.trim()).filter(Boolean),
        isPublished: publish || formData.isPublished,
      }

      const result = await apiPut(`/events/${eventId}`, dataToSend)

      if (result.success) {
        router.push('/admin/events')
      } else {
        alert(result.message || 'Failed to update event')
      }
    } catch (error: any) {
      console.error('Error updating event:', error)
      alert(error.message || 'An error occurred')
    } finally {
      setSaving(false)
    }
  }

  const handleDelete = async () => {
    if (!confirm('Are you sure you want to delete this event?')) return

    try {
      const result = await apiDelete(`/events/${eventId}`)
      if (result.success) {
        router.push('/admin/events')
      }
    } catch (error: any) {
      console.error('Error deleting event:', error)
      alert(error.message || 'Failed to delete event')
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <LoadingSpinner />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <button onClick={() => router.back()} className="p-2 hover:bg-white/10 rounded-lg transition-all">
            <ArrowLeft className="w-5 h-5 text-white" />
          </button>
          <div>
            <h1 className="text-3xl font-bold text-white">Edit Event</h1>
            <p className="text-white/70">Update event details</p>
          </div>
        </div>
        <button
          onClick={handleDelete}
          className="flex items-center gap-2 px-4 py-2 bg-red-500/20 hover:bg-red-500/30 text-red-400 rounded-lg transition-all"
        >
          <Trash2 className="w-5 h-5" />
          Delete
        </button>
      </div>

      <form onSubmit={(e) => handleSubmit(e, false)} className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2 space-y-6">
          <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
            <label className="block text-white font-medium mb-2">Title <span className="text-red-400">*</span></label>
            <input type="text" name="title" value={formData.title} onChange={handleChange} required
              className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:ring-2 focus:ring-primary"
              placeholder="Event title..." />
          </div>

          <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
            <label className="block text-white font-medium mb-2">Description <span className="text-red-400">*</span></label>
            <textarea name="description" value={formData.description} onChange={handleChange} required rows={3}
              className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:ring-2 focus:ring-primary resize-none"
              placeholder="Brief description..." />
          </div>

          <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
            <label className="block text-white font-medium mb-2">Full Details</label>
            <textarea name="content" value={formData.content} onChange={handleChange} rows={8}
              className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:ring-2 focus:ring-primary resize-none"
              placeholder="Detailed event information..." />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
              <label className="block text-white font-medium mb-2 flex items-center gap-2">
                <Calendar className="w-4 h-4" /> Start Date <span className="text-red-400">*</span>
              </label>
              <input type="datetime-local" name="startDate" value={formData.startDate} onChange={handleChange} required
                className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary" />
            </div>

            <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
              <label className="block text-white font-medium mb-2 flex items-center gap-2">
                <Calendar className="w-4 h-4" /> End Date
              </label>
              <input type="datetime-local" name="endDate" value={formData.endDate} onChange={handleChange}
                className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary" />
            </div>
          </div>

          <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
            <label className="block text-white font-medium mb-2 flex items-center gap-2">
              <MapPin className="w-4 h-4" /> Location
            </label>
            <input type="text" name="location" value={formData.location} onChange={handleChange}
              className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:ring-2 focus:ring-primary"
              placeholder="Event location or venue..." />
          </div>
        </div>

        <div className="space-y-6">
          <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
            <label className="block text-white font-medium mb-4">Event Image</label>
            {imagePreview ? (
              <div className="space-y-3">
                <div className="relative">
                  <Image src={imagePreview} alt="Preview" width={400} height={200} className="w-full h-48 object-cover rounded-lg" />
                  <button type="button" onClick={() => { setImagePreview(''); setFormData(prev => ({ ...prev, imageUrl: '' })) }}
                    className="absolute top-2 right-2 p-2 bg-red-500 hover:bg-red-600 rounded-full transition-all">
                    <X className="w-4 h-4 text-white" />
                  </button>
                  {uploading && (
                    <div className="absolute inset-0 bg-black/50 backdrop-blur-sm rounded-lg flex items-center justify-center">
                      <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-white"></div>
                    </div>
                  )}
                </div>
                {formData.imageUrl && (
                  <div className="p-2 bg-white/5 rounded border border-white/10">
                    <p className="text-white/50 text-xs mb-1">Image URL:</p>
                    <p className="text-white/90 text-xs break-all font-mono">{formData.imageUrl}</p>
                  </div>
                )}
              </div>
            ) : (
              <label className="flex flex-col items-center justify-center w-full h-48 border-2 border-dashed border-white/30 rounded-lg cursor-pointer hover:border-white/50 transition-all">
                <Upload className="w-12 h-12 text-white/50 mb-2" />
                <span className="text-white/70 text-sm">Upload event image</span>
                <input type="file" accept="image/*" onChange={handleImageUpload} className="hidden" disabled={uploading} />
              </label>
            )}
          </div>

          <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
            <label className="block text-white font-medium mb-2">Category</label>
            <select name="category" value={formData.category} onChange={handleChange}
              className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary appearance-none">
              <option value="general">General</option>
              <option value="meeting">Meeting</option>
              <option value="workshop">Workshop</option>
              <option value="community">Community</option>
              <option value="sports">Sports</option>
              <option value="cultural">Cultural</option>
            </select>
          </div>

          <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20 space-y-4">
            <label className="flex items-center gap-3 cursor-pointer">
              <input type="checkbox" name="isFeatured" checked={formData.isFeatured} onChange={handleChange}
                className="w-5 h-5 rounded border-white/20 bg-white/10 text-primary focus:ring-primary" />
              <span className="text-white">Featured Event</span>
            </label>
            <label className="flex items-center gap-3 cursor-pointer">
              <input type="checkbox" name="isPublished" checked={formData.isPublished} onChange={handleChange}
                className="w-5 h-5 rounded border-white/20 bg-white/10 text-primary focus:ring-primary" />
              <span className="text-white">Published</span>
            </label>
          </div>

          <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20 space-y-3">
            <button type="submit" disabled={saving}
              className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-primary hover:bg-primary-dark text-white rounded-lg transition-all disabled:opacity-50">
              <Save className="w-5 h-5" />
              {saving ? 'Saving...' : 'Save Changes'}
            </button>
            <button type="button" onClick={(e) => handleSubmit(e as any, true)} disabled={saving}
              className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-green-600 hover:bg-green-700 text-white rounded-lg transition-all disabled:opacity-50">
              <Eye className="w-5 h-5" />
              {saving ? 'Publishing...' : 'Publish Now'}
            </button>
            <button type="button" onClick={() => router.back()}
              className="w-full px-4 py-3 bg-white/10 hover:bg-white/20 text-white rounded-lg transition-all">
              Cancel
            </button>
          </div>
        </div>
      </form>
    </div>
  )
}
