'use client'

import { useState, useEffect } from 'react'
import { useRouter, useParams } from 'next/navigation'
import { ArrowLeft, Save, Trash2, Building2 } from 'lucide-react'
import { isAuthenticated } from '@/lib/auth'
import { apiGet, apiPut, apiDelete } from '@/lib/apiClient'
import LoadingSpinner from '@/components/LoadingSpinner'

interface User {
  _id: string
  firstName: string
  lastName: string
  email: string
}

interface Department {
  _id: string
  name: string
  code: string
}

interface DepartmentData {
  _id: string
  name: string
  code: string
  description: string
  parentDepartment?: string | { _id: string }
  manager?: string | { _id: string }
  contact: {
    email?: string
    phone?: string
  }
  location: {
    building?: string
    floor?: string
  }
  isActive: boolean
}

export default function EditDepartmentPage() {
  const router = useRouter()
  const params = useParams()
  const departmentId = params.id as string

  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [users, setUsers] = useState<User[]>([])
  const [parentDepartments, setParentDepartments] = useState<Department[]>([])
  const [formData, setFormData] = useState({
    name: '',
    code: '',
    description: '',
    parentDepartment: '',
    manager: '',
    contact: {
      email: '',
      phone: '',
    },
    location: {
      building: '',
      floor: '',
    },
    isActive: true,
  })

  useEffect(() => {
    if (!isAuthenticated()) {
      router.push('/admin')
      return
    }
    fetchDepartment()
    fetchUsers()
    fetchDepartments()
  }, [departmentId, router])

  const fetchDepartment = async () => {
    try {
      const result = await apiGet<DepartmentData>(`/departments/${departmentId}`)
      if (result.success && result.data) {
        const dept = result.data
        const parentId = typeof dept.parentDepartment === 'object' 
          ? dept.parentDepartment._id 
          : dept.parentDepartment || ''
        const managerId = typeof dept.manager === 'object' 
          ? dept.manager._id 
          : dept.manager || ''
        
        setFormData({
          name: dept.name,
          code: dept.code,
          description: dept.description || '',
          parentDepartment: parentId,
          manager: managerId,
          contact: {
            email: dept.contact?.email || '',
            phone: dept.contact?.phone || '',
          },
          location: {
            building: dept.location?.building || '',
            floor: dept.location?.floor || '',
          },
          isActive: dept.isActive !== undefined ? dept.isActive : true,
        })
      }
    } catch (error: any) {
      console.error('Error fetching department:', error)
      alert(error.message || 'Failed to load department')
      router.push('/admin/departments')
    } finally {
      setLoading(false)
    }
  }

  const fetchUsers = async () => {
    try {
      const result = await apiGet<User[]>('/users')
      if (result.success && result.data) {
        setUsers(result.data)
      }
    } catch (error) {
      console.error('Error fetching users:', error)
    }
  }

  const fetchDepartments = async () => {
    try {
      const result = await apiGet<Department[]>('/departments')
      if (result.success && result.data) {
        setParentDepartments(result.data.filter(d => d._id !== departmentId))
      }
    } 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.startsWith('contact.')) {
      const field = name.split('.')[1]
      setFormData(prev => ({
        ...prev,
        contact: { ...prev.contact, [field]: value }
      }))
    } else if (name.startsWith('location.')) {
      const field = name.split('.')[1]
      setFormData(prev => ({
        ...prev,
        location: { ...prev.location, [field]: value }
      }))
    } else {
      setFormData(prev => ({
        ...prev,
        [name]: type === 'checkbox' ? checked : value,
      }))
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setSaving(true)

    try {
      const result = await apiPut(`/departments/${departmentId}`, {
        name: formData.name,
        code: formData.code,
        description: formData.description,
        parentDepartment: formData.parentDepartment || null,
        manager: formData.manager || null,
        contact: formData.contact,
        location: formData.location,
        isActive: formData.isActive,
      })

      if (result.success) {
        router.push('/admin/departments')
      }
    } catch (error: any) {
      console.error('Error updating department:', error)
      alert(error.message || 'Failed to update department')
    } finally {
      setSaving(false)
    }
  }

  const handleDelete = async () => {
    if (!confirm('Are you sure you want to delete this department?')) return

    try {
      const result = await apiDelete(`/departments/${departmentId}`)
      if (result.success) {
        router.push('/admin/departments')
      }
    } catch (error: any) {
      console.error('Error deleting department:', error)
      alert(error.message || 'Failed to delete department')
    }
  }

  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 gap-4">
        <button
          onClick={() => router.back()}
          className="p-2 text-white/70 hover:text-white hover:bg-white/10 rounded-lg transition-all"
        >
          <ArrowLeft className="w-5 h-5" />
        </button>
        <div className="flex-1">
          <h1 className="text-3xl font-bold text-white mb-2">Edit Department</h1>
          <p className="text-white/70">Update department details</p>
        </div>
        <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>

      {/* Form */}
      <form onSubmit={handleSubmit} className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20 space-y-6">
        {/* Basic Information */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label htmlFor="name" className="block text-white font-medium mb-2">
              Department Name <span className="text-red-400">*</span>
            </label>
            <input
              type="text"
              id="name"
              name="name"
              value={formData.name}
              onChange={handleChange}
              required
              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"
            />
          </div>

          <div>
            <label htmlFor="code" className="block text-white font-medium mb-2">
              Department Code <span className="text-red-400">*</span>
            </label>
            <input
              type="text"
              id="code"
              name="code"
              value={formData.code}
              onChange={handleChange}
              required
              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 uppercase"
            />
          </div>
        </div>

        {/* Description */}
        <div>
          <label htmlFor="description" className="block text-white font-medium mb-2">
            Description
          </label>
          <textarea
            id="description"
            name="description"
            value={formData.description}
            onChange={handleChange}
            rows={4}
            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"
          />
        </div>

        {/* Parent Department */}
        <div>
          <label htmlFor="parentDepartment" className="block text-white font-medium mb-2">
            Parent Department
          </label>
          <select
            id="parentDepartment"
            name="parentDepartment"
            value={formData.parentDepartment}
            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="">None (Top Level Department)</option>
            {parentDepartments.map(dept => (
              <option key={dept._id} value={dept._id}>{dept.name}</option>
            ))}
          </select>
        </div>

        {/* Manager */}
        <div>
          <label htmlFor="manager" className="block text-white font-medium mb-2">
            Department Manager
          </label>
          <select
            id="manager"
            name="manager"
            value={formData.manager}
            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="">Select Manager</option>
            {users.map(user => (
              <option key={user._id} value={user._id}>
                {user.firstName} {user.lastName} ({user.email})
              </option>
            ))}
          </select>
        </div>

        {/* Contact Information */}
        <div className="border-t border-white/10 pt-6">
          <h3 className="text-white font-semibold mb-4 flex items-center gap-2">
            <Building2 className="w-5 h-5" />
            Contact Information
          </h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label htmlFor="contact.email" className="block text-white font-medium mb-2">
                Email
              </label>
              <input
                type="email"
                id="contact.email"
                name="contact.email"
                value={formData.contact.email}
                onChange={handleChange}
                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"
              />
            </div>

            <div>
              <label htmlFor="contact.phone" className="block text-white font-medium mb-2">
                Phone
              </label>
              <input
                type="tel"
                id="contact.phone"
                name="contact.phone"
                value={formData.contact.phone}
                onChange={handleChange}
                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"
              />
            </div>
          </div>
        </div>

        {/* Location Information */}
        <div className="border-t border-white/10 pt-6">
          <h3 className="text-white font-semibold mb-4">Location Information</h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label htmlFor="location.building" className="block text-white font-medium mb-2">
                Building
              </label>
              <input
                type="text"
                id="location.building"
                name="location.building"
                value={formData.location.building}
                onChange={handleChange}
                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"
              />
            </div>

            <div>
              <label htmlFor="location.floor" className="block text-white font-medium mb-2">
                Floor
              </label>
              <input
                type="text"
                id="location.floor"
                name="location.floor"
                value={formData.location.floor}
                onChange={handleChange}
                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"
              />
            </div>
          </div>
        </div>

        {/* Active Status */}
        <div className="flex items-center gap-3">
          <input
            type="checkbox"
            id="isActive"
            name="isActive"
            checked={formData.isActive}
            onChange={handleChange}
            className="w-5 h-5 rounded border-white/20 bg-white/10 text-primary focus:ring-primary"
          />
          <label htmlFor="isActive" className="text-white font-medium">
            Active
          </label>
        </div>

        {/* Actions */}
        <div className="flex items-center gap-3 pt-4 border-t border-white/10">
          <button
            type="submit"
            disabled={saving}
            className="flex items-center gap-2 px-6 py-2 bg-primary hover:bg-primary-dark text-white rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <Save className="w-5 h-5" />
            {saving ? 'Saving...' : 'Save Changes'}
          </button>
          <button
            type="button"
            onClick={() => router.back()}
            className="px-6 py-2 bg-white/10 hover:bg-white/20 text-white rounded-lg transition-all"
          >
            Cancel
          </button>
        </div>
      </form>
    </div>
  )
}
