'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { ArrowLeft, Save, Eye, Upload, X } from 'lucide-react'
import { isAuthenticated, hasRole } from '@/lib/auth'
import { apiPost } from '@/lib/apiClient'
import { API_BASE_URL } from '@/config/api'
import { normalizeImageUrl } from '@/lib/media'
import { useToast } from '@/components/admin/Toast'
import { formatFileSize } from '@/lib/imageUtils'

export default function NewArticlePage() {
  const router = useRouter()
  const { showToast, updateToast, dismissToast } = useToast()
  const [loading, setLoading] = useState(false)
  const [uploading, setUploading] = useState(false)
  const [imagePreview, setImagePreview] = useState<string>('')
  const [imageError, setImageError] = useState(false)
  const [isManager, setIsManager] = useState(false)
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    content: '',
    imageUrl: '',
    link: '',
    category: 'general',
    tags: '',
    isFeatured: false,
    isPublished: false,
    order: 0,
  })

  useEffect(() => {
    // Check authentication and permissions
    if (!isAuthenticated()) {
      router.push('/admin')
      return
    }
    
    // Check if user can create articles
    const canCreate = hasRole(['ADMINISTRATOR', 'COMMUNICATIONS_MANAGER', 'SENIOR_COMMUNICATIONS_OFFICER', 'COMMUNICATIONS_OFFICER'])
    if (!canCreate) {
      alert('You do not have permission to create articles')
      router.push('/admin/news-articles')
    }

    setIsManager(hasRole(['ADMINISTRATOR', 'COMMUNICATIONS_MANAGER']))
  }, [router])

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

    if (name === 'imageUrl') {
      const normalizedValue = normalizeImageUrl(value)
      setFormData(prev => ({
        ...prev,
        imageUrl: normalizedValue,
      }))
      setImagePreview(normalizedValue)
      setImageError(false)
      return
    }

    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', 'news')
      uploadFormData.append('image', result.file)

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

      if (uploadResult.success && uploadResult.data) {
        const fullUrl = normalizeImageUrl(uploadResult.data.fullUrl || uploadResult.data.url)
        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()
    setLoading(true)

    try {
      // Only managers can publish directly
      const canPublish = isManager && (publish || formData.isPublished)
      
      const dataToSend = {
        ...formData,
        tags: formData.tags.split(',').map(tag => tag.trim()).filter(Boolean),
        isPublished: canPublish,
      }

      const result = await apiPost('/news-articles', dataToSend)

      if (result.success) {
        router.push('/admin/news-articles')
      } else {
        alert(result.message || 'Failed to create article')
      }
    } catch (error: any) {
      console.error('Error creating article:', error)
      alert(error.message || 'An error occurred')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <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">New Article</h1>
            <p className="text-white/70">Create a new news article</p>
          </div>
        </div>
      </div>

      {/* Form */}
      <form onSubmit={(e) => handleSubmit(e, false)} className="space-y-6">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Main Content */}
          <div className="lg:col-span-2 space-y-6">
            {/* Title */}
            <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="Enter article title..."
              />
            </div>

            {/* Description */}
            <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 (shown in previews)..."
              />
            </div>

            {/* Content */}
            <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">
                Content
              </label>
              <textarea
                name="content"
                value={formData.content}
                onChange={handleChange}
                rows={12}
                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="Full article content..."
              />
              <p className="text-white/50 text-sm mt-2">
                Tip: Use markdown formatting for rich text
              </p>
            </div>

            {/* External Link */}
            <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">
                External Link (Optional)
              </label>
              <input
                type="url"
                name="link"
                value={formData.link}
                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="https://example.com/full-article"
              />
            </div>
          </div>

          {/* Sidebar */}
          <div className="space-y-6">
            {/* Image Upload */}
            <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">
                Featured Image <span className="text-red-400">*</span>
              </label>

              {imagePreview ? (
                <div className="space-y-3">
                  <div className="relative">
                    <div className="w-full h-48 bg-white/5 rounded-lg overflow-hidden flex items-center justify-center">
                      {imageError ? (
                        <div className="text-white/50 text-sm">Image failed to load</div>
                      ) : (
                        <img
                          src={imagePreview}
                          alt="Preview"
                          className="w-full h-full object-cover"
                          onError={() => setImageError(true)}
                        />
                      )}
                    </div>
                    <button
                      type="button"
                      onClick={() => {
                        setImagePreview('')
                        setImageError(false)
                        setFormData(prev => ({ ...prev, imageUrl: '' }))
                      }}
                      className="absolute top-2 right-2 p-2 bg-red-500 hover:bg-red-600 rounded-full transition-all z-10"
                    >
                      <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">Click to upload image</span>
                  <span className="text-white/50 text-xs mt-1">PNG, JPG, WebP (max 5MB)</span>
                  <input
                    type="file"
                    accept="image/*"
                    onChange={handleImageUpload}
                    className="hidden"
                    disabled={uploading}
                  />
                </label>
              )}

              <input
                type="url"
                name="imageUrl"
                value={formData.imageUrl}
                onChange={handleChange}
                placeholder="Or paste image URL"
                className="w-full px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:ring-2 focus:ring-primary mt-3 text-sm"
              />
            </div>

            {/* Category */}
            <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="announcement">Announcement</option>
                <option value="event">Event</option>
                <option value="update">Update</option>
                <option value="community">Community</option>
                <option value="infrastructure">Infrastructure</option>
              </select>
            </div>

            {/* Tags */}
            <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">
                Tags
              </label>
              <input
                type="text"
                name="tags"
                value={formData.tags}
                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="tag1, tag2, tag3"
              />
              <p className="text-white/50 text-xs mt-2">
                Separate tags with commas
              </p>
            </div>

            {/* Options */}
            <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 Article</span>
              </label>

              {isManager ? (
                <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">Publish immediately</span>
                </label>
              ) : (
                <div className="text-white/70 text-sm">
                  <p>Articles are saved as drafts. Submit for review after editing.</p>
                </div>
              )}

              <div>
                <label className="block text-white/70 text-sm mb-2">
                  Display Order
                </label>
                <input
                  type="number"
                  name="order"
                  value={formData.order}
                  onChange={handleChange}
                  className="w-full px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary"
                  min="0"
                />
              </div>
            </div>

            {/* Action Buttons */}
            <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20 space-y-3">
              <button
                type="submit"
                disabled={loading}
                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" />
                {loading ? 'Saving...' : 'Save as Draft'}
              </button>

              {isManager && (
                <button
                  type="button"
                  onClick={(e) => handleSubmit(e as any, true)}
                  disabled={loading}
                  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" />
                  {loading ? '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>
        </div>
      </form>
    </div>
  )
}
