'use client'

import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { Calendar, Briefcase, Filter, Search, Clock, MapPin, DollarSign, Tag, ExternalLink } from 'lucide-react'
import Link from 'next/link'
import { vacanciesApi, Vacancy } from '@/lib/api'

const formatDate = (dateString: string | undefined) => {
  if (!dateString) return 'Date TBA'
  const date = new Date(dateString)
  const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  return `${date.getDate()} ${months[date.getMonth()]} ${date.getFullYear()}`
}

const getDaysUntil = (dateString: string) => {
  const closingDate = new Date(dateString)
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  closingDate.setHours(0, 0, 0, 0)
  
  const diffTime = closingDate.getTime() - today.getTime()
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  return diffDays
}

const getStatusColor = (status: string, closingDate: string) => {
  const daysUntil = getDaysUntil(closingDate)
  
  if (status === 'filled') return 'bg-green-500/20 text-green-300 border-green-500/30'
  if (status === 'closed') return 'bg-gray-500/20 text-gray-300 border-gray-500/30'
  if (daysUntil <= 7) return 'bg-red-500/20 text-red-300 border-red-500/30'
  if (daysUntil <= 30) return 'bg-orange-500/20 text-orange-300 border-orange-500/30'
  return 'bg-blue-500/20 text-blue-300 border-blue-500/30'
}

const formatSalary = (salaryRange: any) => {
  if (!salaryRange) return 'Salary negotiable'
  const { min, max, currency = 'ZAR' } = salaryRange
  if (min && max) {
    return `R ${min.toLocaleString()} - R ${max.toLocaleString()}`
  }
  if (min) {
    return `R ${min.toLocaleString()}+`
  }
  return 'Salary negotiable'
}

export default function VacanciesPage() {
  const [vacancies, setVacancies] = useState<Vacancy[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null)
  const [selectedPositionType, setSelectedPositionType] = useState<string | null>(null)
  const [selectedStatus, setSelectedStatus] = useState<'all' | 'open' | 'closed'>('all')

  useEffect(() => {
    const fetchVacancies = async () => {
      try {
        const params: any = { limit: 50 }
        if (selectedStatus === 'open') params.open = 'true'
        if (selectedStatus === 'closed') params.closed = 'true'
        if (selectedCategory) params.category = selectedCategory
        if (selectedPositionType) params.positionType = selectedPositionType
        
        const result = await vacanciesApi.getAll(params)
        setVacancies(result.data)
      } catch (error) {
        console.error('Error fetching vacancies:', error)
        setVacancies([])
      } finally {
        setIsLoading(false)
      }
    }

    fetchVacancies()
  }, [selectedCategory, selectedPositionType, selectedStatus])

  const filteredVacancies = vacancies.filter(vacancy => {
    const matchesSearch = 
      vacancy.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
      vacancy.vacancyNumber.toLowerCase().includes(searchTerm.toLowerCase()) ||
      vacancy.description.toLowerCase().includes(searchTerm.toLowerCase())
    return matchesSearch
  })

  const categories = Array.from(new Set(vacancies.map(v => v.category).filter(Boolean)))
  const positionTypes = Array.from(new Set(vacancies.map(v => v.positionType).filter(Boolean)))

  return (
    <div className="min-h-screen py-12 px-4">
      <div className="max-w-[1200px] mx-auto">
        <div className="glass-page rounded-2xl p-8 md:p-12 shadow-2xl">
          {/* Header Section */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6 }}
            className="text-center mb-12"
          >
            <div className="flex items-center justify-center gap-3 mb-4">
              <Briefcase className="w-8 h-8 text-primary-light" />
              <h1 className="text-4xl md:text-5xl font-bold text-white">Vacancies</h1>
            </div>
            <p className="text-white/70 text-lg mb-6">
              Explore career opportunities with Madibeng Local Municipality
            </p>
            <div className="w-24 h-1 bg-primary mx-auto"></div>
          </motion.div>

          {/* Filters and Search */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.2 }}
            className="mb-8 space-y-4"
          >
            {/* Search */}
            <div className="relative">
              <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-white/50" />
              <input
                type="text"
                placeholder="Search vacancies by title, number, or description..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full pl-12 pr-4 py-3 glass rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary"
              />
            </div>

            {/* Filters */}
            <div className="flex flex-wrap gap-4">
              <div className="flex items-center gap-2">
                <Filter className="w-5 h-5 text-white/70" />
                <span className="text-white/90 font-semibold">Status:</span>
              </div>
              <div className="flex flex-wrap gap-3">
                <button
                  onClick={() => setSelectedStatus('all')}
                  className={`px-4 py-2 rounded-full text-sm font-semibold transition-all ${
                    selectedStatus === 'all'
                      ? 'bg-primary text-white'
                      : 'glass text-white/80 hover:bg-white/10'
                  }`}
                >
                  All
                </button>
                <button
                  onClick={() => setSelectedStatus('open')}
                  className={`px-4 py-2 rounded-full text-sm font-semibold transition-all ${
                    selectedStatus === 'open'
                      ? 'bg-primary text-white'
                      : 'glass text-white/80 hover:bg-white/10'
                  }`}
                >
                  Open
                </button>
                <button
                  onClick={() => setSelectedStatus('closed')}
                  className={`px-4 py-2 rounded-full text-sm font-semibold transition-all ${
                    selectedStatus === 'closed'
                      ? 'bg-primary text-white'
                      : 'glass text-white/80 hover:bg-white/10'
                  }`}
                >
                  Closed
                </button>
              </div>
            </div>

            {/* Category and Position Type Filters */}
            <div className="flex flex-wrap gap-4">
              {categories.length > 0 && (
                <div className="flex flex-wrap gap-3">
                  <button
                    onClick={() => setSelectedCategory(null)}
                    className={`px-4 py-2 rounded-full text-sm font-semibold transition-all ${
                      selectedCategory === null
                        ? 'bg-primary text-white'
                        : 'glass text-white/80 hover:bg-white/10'
                    }`}
                  >
                    All Categories
                  </button>
                  {categories.map((category) => (
                    <button
                      key={category}
                      onClick={() => setSelectedCategory(category)}
                      className={`px-4 py-2 rounded-full text-sm font-semibold transition-all ${
                        selectedCategory === category
                          ? 'bg-primary text-white'
                          : 'glass text-white/80 hover:bg-white/10'
                      }`}
                    >
                      {category}
                    </button>
                  ))}
                </div>
              )}
              {positionTypes.length > 0 && (
                <div className="flex flex-wrap gap-3">
                  <button
                    onClick={() => setSelectedPositionType(null)}
                    className={`px-4 py-2 rounded-full text-sm font-semibold transition-all ${
                      selectedPositionType === null
                        ? 'bg-primary text-white'
                        : 'glass text-white/80 hover:bg-white/10'
                    }`}
                  >
                    All Types
                  </button>
                  {positionTypes.map((type) => (
                    <button
                      key={type}
                      onClick={() => setSelectedPositionType(type)}
                      className={`px-4 py-2 rounded-full text-sm font-semibold transition-all ${
                        selectedPositionType === type
                          ? 'bg-primary text-white'
                          : 'glass text-white/80 hover:bg-white/10'
                      }`}
                    >
                      {type}
                    </button>
                  ))}
                </div>
              )}
            </div>
          </motion.div>

          {/* Vacancies List */}
          {isLoading ? (
            <div className="text-center py-12">
              <div className="text-white/70">Loading vacancies...</div>
            </div>
          ) : filteredVacancies.length === 0 ? (
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              className="text-center py-12"
            >
              <Briefcase className="w-16 h-16 text-white/30 mx-auto mb-4" />
              <p className="text-white/60 text-lg">No vacancies found</p>
              <p className="text-white/40 text-sm mt-2">
                {searchTerm || selectedCategory || selectedPositionType || selectedStatus !== 'all'
                  ? 'Try adjusting your filters or search terms.'
                  : 'Check back soon for new vacancies.'}
              </p>
            </motion.div>
          ) : (
            <div className="grid grid-cols-1 gap-6">
              {filteredVacancies.map((vacancy, index) => {
                const daysUntil = getDaysUntil(vacancy.closingDate)
                const isUrgent = daysUntil >= 0 && daysUntil <= 7 && vacancy.status === 'open'
                
                return (
                  <motion.div
                    key={vacancy._id}
                    initial={{ opacity: 0, y: 30 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.5, delay: index * 0.1 }}
                    whileHover={{ y: -8, scale: 1.02 }}
                    className="glass rounded-xl p-6 shadow-xl glass-hover border-2 border-white/10 hover:border-primary/30 transition-all duration-300"
                  >
                    <div className="flex flex-col md:flex-row md:items-start md:justify-between gap-4">
                      <div className="flex-1">
                        {/* Urgent Badge */}
                        {isUrgent && (
                          <motion.div
                            animate={{ scale: [1, 1.05, 1] }}
                            transition={{ duration: 2, repeat: Infinity }}
                            className="inline-block bg-red-500 text-white px-3 py-1 rounded-full text-xs font-bold mb-3"
                          >
                            URGENT - {daysUntil === 0 ? 'CLOSES TODAY' : `${daysUntil} DAYS LEFT`}
                          </motion.div>
                        )}

                        {/* Vacancy Number */}
                        <div className="flex items-center gap-2 mb-2">
                          <Tag className="w-4 h-4 text-primary-light" />
                          <span className="text-primary-light font-semibold text-sm">
                            {vacancy.vacancyNumber}
                          </span>
                          <span className={`px-3 py-1 rounded-full text-xs font-semibold border ${getStatusColor(vacancy.status, vacancy.closingDate)}`}>
                            {vacancy.status.toUpperCase()}
                          </span>
                        </div>

                        {/* Title */}
                        <h3 className="text-2xl font-bold text-white mb-3 hover:text-primary-light transition-colors">
                          {vacancy.title}
                        </h3>

                        {/* Description */}
                        <p className="text-white/70 text-sm mb-4 line-clamp-2">
                          {vacancy.description}
                        </p>

                        {/* Details */}
                        <div className="flex flex-wrap gap-4 text-sm text-white/70">
                          <div className="flex items-center gap-2">
                            <Calendar className="w-4 h-4 text-primary-light" />
                            <span>Closes: {formatDate(vacancy.closingDate)}</span>
                            {vacancy.status === 'open' && daysUntil >= 0 && (
                              <span className="text-primary-light font-semibold">
                                ({daysUntil} {daysUntil === 1 ? 'day' : 'days'} left)
                              </span>
                            )}
                          </div>
                          {vacancy.location && (
                            <div className="flex items-center gap-2">
                              <MapPin className="w-4 h-4 text-primary-light" />
                              <span>{vacancy.location}</span>
                            </div>
                          )}
                          {vacancy.positionType && (
                            <div className="flex items-center gap-2">
                              <Briefcase className="w-4 h-4 text-primary-light" />
                              <span>{vacancy.positionType}</span>
                            </div>
                          )}
                          {vacancy.salaryRange && (
                            <div className="flex items-center gap-2">
                              <DollarSign className="w-4 h-4 text-primary-light" />
                              <span>{formatSalary(vacancy.salaryRange)}</span>
                            </div>
                          )}
                          {vacancy.category && (
                            <div className="flex items-center gap-2">
                              <Tag className="w-4 h-4 text-primary-light" />
                              <span>{vacancy.category}</span>
                            </div>
                          )}
                        </div>
                      </div>

                      {/* Actions */}
                      <div className="flex flex-col gap-2 md:min-w-[200px]">
                        {vacancy.documentUrl && (
                          <a
                            href={vacancy.documentUrl}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="flex items-center justify-center gap-2 bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg font-semibold transition-all hover:scale-105"
                          >
                            <ExternalLink className="w-4 h-4" />
                            View Details
                          </a>
                        )}
                        {vacancy.link && (
                          <a
                            href={vacancy.link}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="flex items-center justify-center gap-2 glass text-white px-4 py-2 rounded-lg font-semibold transition-all hover:bg-white/10"
                          >
                            <ExternalLink className="w-4 h-4" />
                            Apply Now
                          </a>
                        )}
                      </div>
                    </div>
                  </motion.div>
                )
              })}
            </div>
          )}

          {/* Quick Links */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.4 }}
            className="mt-12 pt-8 border-t border-white/10"
          >
            <Link
              href="/vacancies/forms"
              className="block glass rounded-lg p-4 hover:bg-white/10 transition-all text-center"
            >
              <h3 className="text-white font-semibold mb-2">Vacancy Forms</h3>
              <p className="text-white/70 text-sm">Download application forms and documents</p>
            </Link>
          </motion.div>
        </div>
      </div>
    </div>
  )
}
