'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { ArrowLeft, Save, Eye, Upload, X, Sparkles } from 'lucide-react'
import { isAuthenticated, hasRole } from '@/lib/auth'
import { apiPost, apiGet } from '@/lib/apiClient'
import { normalizeImageUrl } from '@/lib/media'
import { useToast } from '@/components/admin/Toast'
import { formatFileSize } from '@/lib/imageUtils'
import { isFakerEnabled } from '@/lib/settings'
import { generateFakeVacancy } from '@/lib/fakerUtils'

interface Department {
  _id: string
  name: string
}

export default function NewVacancyPage() {
  const router = useRouter()
  const { showToast, updateToast, dismissToast } = useToast()
  const [loading, setLoading] = useState(false)
  const [uploading, setUploading] = useState(false)
  const [imagePreview, setImagePreview] = useState<string>('')
  const [departments, setDepartments] = useState<Department[]>([])
  const [isManager, setIsManager] = useState(false)
  const [showFakerButton, setShowFakerButton] = useState(false)
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    content: '',
    vacancyNumber: '',
    department: '',
    category: 'general',
    positionType: 'full-time',
    location: '',
    salaryRange: { min: '', max: '', currency: 'ZAR' },
    closingDate: '',
    documentUrl: '',
    imageUrl: '',
    link: '',
    isFeatured: false,
    isPublished: false,
    order: 0,
    requirements: '',
    responsibilities: '',
    qualifications: '',
    tags: '',
  })

  useEffect(() => {
    if (!isAuthenticated()) {
      router.push('/admin')
      return
    }
    const canCreate = hasRole(['ADMINISTRATOR', 'COMMUNICATIONS_MANAGER', 'SENIOR_COMMUNICATIONS_OFFICER', 'COMMUNICATIONS_OFFICER'])
    const managerRole = hasRole(['ADMINISTRATOR', 'COMMUNICATIONS_MANAGER'])
    setIsManager(managerRole)
    if (!canCreate) {
      alert('You do not have permission to create vacancies')
      router.push('/admin/vacancies')
    }
    setShowFakerButton(isFakerEnabled())
    fetchDepartments()
  }, [router])

  const fetchDepartments = async () => {
    try {
      const result = await apiGet<Department[]>('/departments')
      if (result.success && result.data) {
        setDepartments(result.data)
      }
    } catch (error) {
      console.error('Error fetching departments:', error)
    }
  }

  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)
      return
    }

    if (name.startsWith('salaryRange.')) {
      const field = name.split('.')[1] as 'min' | 'max' | 'currency'
      setFormData(prev => ({
        ...prev,
        salaryRange: { ...prev.salaryRange, [field]: value }
      }))
      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

    const reader = new FileReader()
    reader.onloadend = () => {
      setImagePreview(reader.result as string)
    }
    reader.readAsDataURL(file)

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

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

      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 handleFillFaker = () => {
    const fakeData = generateFakeVacancy(departments)
    setFormData(prev => ({
      ...prev,
      ...fakeData,
    }))
    if (fakeData.imageUrl) {
      setImagePreview(fakeData.imageUrl)
    }
  }

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

    try {
      const canPublish = isManager && (publish || formData.isPublished)
      
      const dataToSend = {
        ...formData,
        department: formData.department || null,
        salaryRange: {
          min: formData.salaryRange.min ? parseFloat(formData.salaryRange.min) : null,
          max: formData.salaryRange.max ? parseFloat(formData.salaryRange.max) : null,
          currency: formData.salaryRange.currency
        },
        requirements: formData.requirements.split('\n').filter(Boolean),
        responsibilities: formData.responsibilities.split('\n').filter(Boolean),
        qualifications: formData.qualifications.split('\n').filter(Boolean),
        tags: formData.tags.split(',').map(tag => tag.trim()).filter(Boolean),
        isPublished: canPublish,
      }

      const result = await apiPost('/vacancies', dataToSend)

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

  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">New Vacancy</h1>
            <p className="text-white/70">Create a new job vacancy</p>
          </div>
        </div>
        {showFakerButton && (
          <button
            type="button"
            onClick={handleFillFaker}
            className="flex items-center gap-2 px-4 py-2 bg-purple-500/20 hover:bg-purple-500/30 text-purple-300 rounded-lg transition-all border border-purple-500/30"
            title="Fill form with fake data for testing"
          >
            <Sparkles className="w-4 h-4" />
            Fill with Faker
          </button>
        )}
      </div>

      <form onSubmit={(e) => handleSubmit(e, false)} className="space-y-6">
        <div 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="Enter job 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">
                Vacancy Number <span className="text-red-400">*</span>
              </label>
              <input
                type="text"
                name="vacancyNumber"
                value={formData.vacancyNumber}
                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 font-mono"
                placeholder="VAC-2024-001"
              />
            </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">Content</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="Full job 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">Requirements</label>
              <textarea
                name="requirements"
                value={formData.requirements}
                onChange={handleChange}
                rows={4}
                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="One requirement per line..."
              />
            </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">Responsibilities</label>
              <textarea
                name="responsibilities"
                value={formData.responsibilities}
                onChange={handleChange}
                rows={4}
                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="One responsibility per line..."
              />
            </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">Qualifications</label>
              <textarea
                name="qualifications"
                value={formData.qualifications}
                onChange={handleChange}
                rows={4}
                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="One qualification per line..."
              />
            </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">Featured Image</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">
                      <img
                        src={imagePreview}
                        alt="Preview"
                        className="w-full h-full object-cover"
                      />
                    </div>
                    <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 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>
                </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>
                  <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>

            <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">Department</label>
              <select
                name="department"
                value={formData.department}
                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="">Select Department</option>
                {departments.map(dept => (
                  <option key={dept._id} value={dept._id}>{dept.name}</option>
                ))}
              </select>
            </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="administrative">Administrative</option>
                <option value="technical">Technical</option>
                <option value="management">Management</option>
              </select>
            </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">Position Type</label>
              <select
                name="positionType"
                value={formData.positionType}
                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="full-time">Full-time</option>
                <option value="part-time">Part-time</option>
                <option value="contract">Contract</option>
                <option value="temporary">Temporary</option>
                <option value="internship">Internship</option>
              </select>
            </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">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="City, Province"
              />
            </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">Salary Range</label>
              <div className="grid grid-cols-2 gap-2 mb-2">
                <input
                  type="number"
                  name="salaryRange.min"
                  value={formData.salaryRange.min}
                  onChange={handleChange}
                  placeholder="Min"
                  className="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"
                />
                <input
                  type="number"
                  name="salaryRange.max"
                  value={formData.salaryRange.max}
                  onChange={handleChange}
                  placeholder="Max"
                  className="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"
                />
              </div>
              <select
                name="salaryRange.currency"
                value={formData.salaryRange.currency}
                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 appearance-none"
              >
                <option value="ZAR">ZAR</option>
                <option value="USD">USD</option>
              </select>
            </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">
                Closing Date <span className="text-red-400">*</span>
              </label>
              <input
                type="datetime-local"
                name="closingDate"
                value={formData.closingDate}
                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">Document URL</label>
              <input
                type="url"
                name="documentUrl"
                value={formData.documentUrl}
                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/job-doc.pdf"
              />
            </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 Vacancy</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>

            <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>
  )
}
