'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { Building2, Users, Search, Plus, Edit, Trash2, Eye } from 'lucide-react'
import { isAuthenticated } from '@/lib/auth'
import { apiGet, apiPut, apiDelete } from '@/lib/apiClient'
import LoadingSpinner from '@/components/LoadingSpinner'

interface Department {
  _id: string
  name: string
  description: string
  isActive: boolean
  createdAt: string
}

export default function DepartmentsPage() {
  const router = useRouter()
  const [departments, setDepartments] = useState<Department[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedDept, setSelectedDept] = useState<Department | null>(null)

  useEffect(() => {
    // Check authentication
    if (!isAuthenticated()) {
      router.push('/admin')
      return
    }
    fetchDepartments()
  }, [router])

  const fetchDepartments = async () => {
    try {
      const result = await apiGet<Department[]>('/departments')
      if (result.success && result.data) {
        setDepartments(result.data)
      }
    } catch (error: any) {
      console.error('Error fetching departments:', error)
      if (error.message?.includes('Authentication required')) {
        router.push('/admin')
      }
    } finally {
      setLoading(false)
    }
  }

  const handleToggleStatus = async (id: string, currentStatus: boolean) => {
    try {
      const result = await apiPut(`/departments/${id}`, {
        isActive: !currentStatus
      })
      if (result.success) {
        fetchDepartments()
      }
    } catch (error: any) {
      console.error('Error toggling department status:', error)
      alert(error.message || 'Failed to update department status')
    }
  }

  const handleDelete = async (id: string) => {
    if (!confirm('Are you sure you want to delete this department?')) return

    try {
      const result = await apiDelete(`/departments/${id}`)
      if (result.success) {
        fetchDepartments()
      }
    } catch (error: any) {
      console.error('Error deleting department:', error)
      alert(error.message || 'Failed to delete department')
    }
  }

  const filteredDepartments = departments.filter(dept =>
    dept.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    dept.description.toLowerCase().includes(searchTerm.toLowerCase())
  )

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <LoadingSpinner />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-white mb-2">Departments</h1>
          <p className="text-white/70">Manage organizational departments</p>
        </div>
        <button
          onClick={() => router.push('/admin/departments/new')}
          className="flex items-center gap-2 px-4 py-2 bg-primary hover:bg-primary-dark text-white rounded-lg transition-all"
        >
          <Plus className="w-5 h-5" />
          New Department
        </button>
      </div>

      {/* Search */}
      <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-white/50" />
          <input
            type="text"
            placeholder="Search departments..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-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>
      </div>

      {/* Departments Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {filteredDepartments.map((dept) => (
          <div
            key={dept._id}
            className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20 hover:border-white/40 transition-all"
          >
            {/* Department Header */}
            <div className="flex items-start justify-between mb-4">
              <div className="p-3 bg-gradient-to-br from-blue-500 to-blue-600 rounded-lg">
                <Building2 className="w-6 h-6 text-white" />
              </div>
              <div className="flex items-center gap-2">
                {dept.isActive ? (
                  <span className="px-2 py-1 bg-green-500/20 text-green-400 text-xs font-medium rounded">
                    Active
                  </span>
                ) : (
                  <span className="px-2 py-1 bg-gray-500/20 text-gray-400 text-xs font-medium rounded">
                    Inactive
                  </span>
                )}
              </div>
            </div>

            {/* Department Info */}
            <h3 className="text-white font-bold text-xl mb-2">{dept.name}</h3>
            <p className="text-white/70 text-sm mb-4 line-clamp-3">
              {dept.description}
            </p>

            {/* Actions */}
            <div className="flex items-center gap-2 pt-4 border-t border-white/10">
              <button
                onClick={() => router.push(`/admin/departments/${dept._id}`)}
                className="flex-1 flex items-center justify-center gap-2 px-3 py-2 bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 rounded-lg transition-all"
              >
                <Edit className="w-4 h-4" />
                Edit
              </button>
              <button
                onClick={() => handleToggleStatus(dept._id, dept.isActive)}
                className={`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg transition-all ${
                  dept.isActive
                    ? 'bg-gray-500/20 text-gray-400 hover:bg-gray-500/30'
                    : 'bg-green-500/20 text-green-400 hover:bg-green-500/30'
                }`}
              >
                {dept.isActive ? 'Deactivate' : 'Activate'}
              </button>
              <button
                onClick={() => handleDelete(dept._id)}
                className="p-2 bg-red-500/20 text-red-400 hover:bg-red-500/30 rounded-lg transition-all"
              >
                <Trash2 className="w-4 h-4" />
              </button>
            </div>
          </div>
        ))}
      </div>

      {filteredDepartments.length === 0 && (
        <div className="bg-white/10 backdrop-blur-xl rounded-xl p-12 text-center border border-white/20">
          <Building2 className="w-16 h-16 text-white/30 mx-auto mb-4" />
          <p className="text-white/50">No departments found</p>
        </div>
      )}

      {/* Department Details Modal */}
      {selectedDept && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4" onClick={() => setSelectedDept(null)}>
          <div className="bg-white/10 backdrop-blur-xl rounded-xl border border-white/20 max-w-2xl w-full" onClick={e => e.stopPropagation()}>
            <div className="p-6">
              <div className="flex items-start justify-between mb-6">
                <div className="flex items-center gap-4">
                  <div className="p-3 bg-gradient-to-br from-blue-500 to-blue-600 rounded-lg">
                    <Building2 className="w-8 h-8 text-white" />
                  </div>
                  <div>
                    <h2 className="text-2xl font-bold text-white mb-1">{selectedDept.name}</h2>
                    <span className={`px-2 py-1 text-xs font-medium rounded ${
                      selectedDept.isActive
                        ? 'bg-green-500/20 text-green-400'
                        : 'bg-gray-500/20 text-gray-400'
                    }`}>
                      {selectedDept.isActive ? 'Active' : 'Inactive'}
                    </span>
                  </div>
                </div>
                <button onClick={() => setSelectedDept(null)} className="text-white/70 hover:text-white">
                  ✕
                </button>
              </div>

              <div className="space-y-4">
                <div>
                  <h3 className="text-white/70 text-sm mb-2">Description</h3>
                  <p className="text-white">{selectedDept.description}</p>
                </div>

                <div>
                  <h3 className="text-white/70 text-sm mb-2">Created</h3>
                  <p className="text-white">{new Date(selectedDept.createdAt).toLocaleDateString('en-US', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                  })}</p>
                </div>

                <div className="bg-blue-500/10 border border-blue-500/30 rounded-lg p-4">
                  <div className="flex items-start gap-3">
                    <Users className="w-5 h-5 text-blue-400 mt-0.5" />
                    <div>
                      <h4 className="text-white font-medium mb-1">Department Members</h4>
                      <p className="text-white/70 text-sm">
                        User count feature to be implemented via backend API
                      </p>
                    </div>
                  </div>
                </div>
              </div>

              <div className="mt-6 pt-6 border-t border-white/10 flex gap-3">
                <button
                  onClick={() => {
                    setSelectedDept(null)
                    router.push(`/admin/departments/${selectedDept._id}`)
                  }}
                  className="flex-1 px-4 py-2 bg-primary hover:bg-primary-dark text-white rounded-lg transition-all"
                >
                  Edit Department
                </button>
                <button
                  onClick={() => setSelectedDept(null)}
                  className="px-4 py-2 bg-white/10 hover:bg-white/20 text-white rounded-lg transition-all"
                >
                  Close
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
