'use client'

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

interface Vacancy {
  _id: string
  title: string
  description: string
  content: string
  vacancyNumber: string
  department?: string | { _id: string; name: string }
  category: string
  positionType: string
  location: string
  salaryRange: { min?: number; max?: number; currency: string }
  closingDate: string
  documentUrl?: string
  imageUrl?: string
  link?: string
  status: 'draft' | 'open' | 'closed' | 'filled' | 'cancelled'
  isPublished: boolean
  isFeatured: boolean
  requirements: string[]
  responsibilities: string[]
  qualifications: string[]
  order: number
  tags: string[]
  createdBy?: string | { _id: string }
}

interface Department {
  _id: string
  name: string
}

export default function EditVacancyPage() {
  const router = useRouter()
  const params = useParams()
  const vacancyId = 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 [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 managerRole = hasRole(['ADMINISTRATOR', 'COMMUNICATIONS_MANAGER'])
    setIsManager(managerRole)
    setShowFakerButton(isFakerEnabled())
    fetchVacancy()
    fetchDepartments()
  }, [vacancyId, 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 fetchVacancy = async () => {
    try {
      const result = await apiGet<Vacancy>(`/vacancies/${vacancyId}`)
      if (result.success && result.data) {
        const vacancy = result.data
        const closingDate = new Date(vacancy.closingDate).toISOString().slice(0, 16)
        const departmentId = typeof vacancy.department === 'object' 
          ? vacancy.department?._id || ''
          : vacancy.department || ''
        
        setFormData({
          title: vacancy.title,
          description: vacancy.description,
          content: vacancy.content || '',
          vacancyNumber: vacancy.vacancyNumber,
          department: departmentId,
          category: vacancy.category || 'general',
          positionType: vacancy.positionType || 'full-time',
          location: vacancy.location || '',
          salaryRange: {
            min: vacancy.salaryRange?.min?.toString() || '',
            max: vacancy.salaryRange?.max?.toString() || '',
            currency: vacancy.salaryRange?.currency || 'ZAR'
          },
          closingDate,
          documentUrl: vacancy.documentUrl || '',
          imageUrl: normalizeImageUrl(vacancy.imageUrl || ''),
          link: vacancy.link || '',
          isFeatured: vacancy.isFeatured || false,
          isPublished: vacancy.isPublished || false,
          order: vacancy.order || 0,
          requirements: vacancy.requirements?.join('\n') || '',
          responsibilities: vacancy.responsibilities?.join('\n') || '',
          qualifications: vacancy.qualifications?.join('\n') || '',
          tags: vacancy.tags?.join(', ') || '',
        })
        if (vacancy.imageUrl) {
          setImagePreview(normalizeImageUrl(vacancy.imageUrl))
        }
      }
    } catch (error: any) {
      console.error('Error fetching vacancy:', error)
      alert(error.message || 'Failed to load vacancy')
      router.push('/admin/vacancies')
    } finally {
      setLoading(false)
    }
  }

  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()
    setSaving(true)

    try {
      const dataToSend: any = {
        ...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: publish || formData.isPublished,
      }

      const result = await apiPut(`/vacancies/${vacancyId}`, dataToSend)

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

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

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

  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 Vacancy</h1>
            <p className="text-white/70">Update vacancy details</p>
          </div>
        </div>
        <div className="flex items-center gap-3">
          {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>
          )}
          <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>
      </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"
              />
            </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"
              />
            </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"
              />
            </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"
              />
            </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"
              />
            </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"
              />
            </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">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>

              {isManager && (
                <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>
        </div>
      </form>
    </div>
  )
}
