'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { ArrowLeft, Save, Building2 } from 'lucide-react'
import { isAuthenticated } from '@/lib/auth'
import { apiGet, apiPost } from '@/lib/apiClient'

interface User {
  _id: string
  firstName: string
  lastName: string
  email: string
}

interface Department {
  _id: string
  name: string
  code: string
}

export default function NewDepartmentPage() {
  const router = useRouter()
  const [loading, setLoading] = 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: '',
    },
  })

  useEffect(() => {
    if (!isAuthenticated()) {
      router.push('/admin')
      return
    }
    fetchUsers()
    fetchDepartments()
  }, [router])

  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)
      }
    } catch (error) {
      console.error('Error fetching departments:', error)
    }
  }

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target

    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]: value,
      }))
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)

    try {
      const result = await apiPost('/departments', {
        name: formData.name,
        code: formData.code,
        description: formData.description,
        parentDepartment: formData.parentDepartment || null,
        manager: formData.manager || null,
        contact: formData.contact,
        location: formData.location,
      })

      if (result.success) {
        router.push('/admin/departments')
      }
    } catch (error: any) {
      console.error('Error creating department:', error)
      alert(error.message || 'Failed to create department')
    } finally {
      setLoading(false)
    }
  }

  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>
          <h1 className="text-3xl font-bold text-white mb-2">New Department</h1>
          <p className="text-white/70">Create a new organizational department</p>
        </div>
      </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"
              placeholder="e.g., Information Technology"
            />
          </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"
              placeholder="IT"
            />
            <p className="text-white/50 text-sm mt-1">Short code identifier (uppercase)</p>
          </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"
            placeholder="Department description and purpose..."
          />
        </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"
                placeholder="dept@madibeng.gov.za"
              />
            </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"
                placeholder="+27 14 590 4700"
              />
            </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"
                placeholder="Main Building"
              />
            </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"
                placeholder="3rd Floor"
              />
            </div>
          </div>
        </div>

        {/* Actions */}
        <div className="flex items-center gap-3 pt-4 border-t border-white/10">
          <button
            type="submit"
            disabled={loading}
            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" />
            {loading ? 'Creating...' : 'Create Department'}
          </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>
  )
}
