'use client'

import { useState, useEffect } from 'react'
import { useRouter, useParams } from 'next/navigation'
import { ArrowLeft, Save, User, Mail, Phone, Shield, Trash2 } from 'lucide-react'
import { isAuthenticated } from '@/lib/auth'
import { apiGet, apiPut, apiDelete } from '@/lib/apiClient'
import LoadingSpinner from '@/components/LoadingSpinner'

interface Role {
  _id: string
  name: string
  displayName: string
}

interface Department {
  _id: string
  name: string
  description: string
}

export default function EditUserPage() {
  const router = useRouter()
  const params = useParams()
  const userId = params.id as string

  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [roles, setRoles] = useState<Role[]>([])
  const [departments, setDepartments] = useState<Department[]>([])
  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    email: '',
    cellphone: '',
    role: 'STAFF',
    department: '',
    isActive: true,
  })

  useEffect(() => {
    // Check authentication
    if (!isAuthenticated()) {
      router.push('/admin')
      return
    }
    fetchUser()
    fetchRoles()
    fetchDepartments()
  }, [userId, router])

  const fetchUser = async () => {
    try {
      const result = await apiGet(`/users/${userId}`)
      if (result.success && result.data) {
        const data = result.data
        setFormData({
          firstName: data.firstName || '',
          lastName: data.lastName || '',
          email: data.email || '',
          cellphone: data.cellphone || '',
          role: data.role || 'STAFF',
          department: data.department?._id || '',
          isActive: data.isActive !== false,
        })
      }
    } catch (error: any) {
      console.error('Error fetching user:', error)
      if (error.message?.includes('Authentication required')) {
        router.push('/admin')
      }
    } finally {
      setLoading(false)
    }
  }

  const fetchRoles = async () => {
    try {
      const result = await apiGet<Role[]>('/roles')
      if (result.success && result.data) {
        setRoles(result.data)
      }
    } catch (error: any) {
      console.error('Error fetching roles:', error)
    }
  }

  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)
    }
  }

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value, type } = e.target
    const checked = (e.target as HTMLInputElement).checked
    setFormData(prev => ({ ...prev, [name]: type === 'checkbox' ? checked : value }))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setSaving(true)

    try {
      const result = await apiPut(`/users/${userId}`, formData)

      if (result.success) {
        alert('User updated successfully!')
        router.push('/admin/users')
      } else {
        alert(result.message || 'Failed to update user')
      }
    } catch (error: any) {
      console.error('Error updating user:', error)
      alert(error.message || 'An error occurred')
    } finally {
      setSaving(false)
    }
  }

  const handleDelete = async () => {
    if (!confirm('Are you sure you want to delete this user? This action cannot be undone!')) return

    try {
      const result = await apiDelete(`/users/${userId}`)

      if (result.success) {
        alert('User deleted successfully')
        router.push('/admin/users')
      } else {
        alert(result.message || 'Failed to delete user')
      }
    } catch (error: any) {
      console.error('Error deleting user:', error)
      alert(error.message || 'Failed to delete user')
    }
  }

  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 User</h1>
            <p className="text-white/70">Update user information and permissions</p>
          </div>
        </div>
        <button
          onClick={handleDelete}
          className="flex items-center gap-2 px-4 py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg transition-all"
        >
          <Trash2 className="w-5 h-5" />
          Delete User
        </button>
      </div>

      <form onSubmit={handleSubmit} className="max-w-3xl">
        <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20 space-y-6">
          {/* Personal Information */}
          <div>
            <h2 className="text-xl font-bold text-white mb-4 flex items-center gap-2">
              <User className="w-5 h-5" /> Personal Information
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-white/90 text-sm font-medium mb-2">
                  First Name <span className="text-red-400">*</span>
                </label>
                <input type="text" name="firstName" value={formData.firstName} 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>
                <label className="block text-white/90 text-sm font-medium mb-2">
                  Last Name <span className="text-red-400">*</span>
                </label>
                <input type="text" name="lastName" value={formData.lastName} 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>
          </div>

          {/* Contact Information */}
          <div>
            <h2 className="text-xl font-bold text-white mb-4 flex items-center gap-2">
              <Mail className="w-5 h-5" /> Contact Information
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-white/90 text-sm font-medium mb-2">
                  Email Address <span className="text-red-400">*</span>
                </label>
                <input type="email" name="email" value={formData.email} 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>
                <label className="block text-white/90 text-sm font-medium mb-2">
                  <Phone className="w-4 h-4 inline mr-1" /> Cellphone <span className="text-red-400">*</span>
                </label>
                <input type="tel" name="cellphone" value={formData.cellphone} 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>
          </div>

          {/* Role & Department */}
          <div>
            <h2 className="text-xl font-bold text-white mb-4 flex items-center gap-2">
              <Shield className="w-5 h-5" /> Role & Department
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-white/90 text-sm font-medium mb-2">
                  Role <span className="text-red-400">*</span>
                </label>
                <select name="role" value={formData.role} 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 appearance-none">
                  {roles.map(role => (
                    <option key={role._id} value={role.name}>{role.displayName || role.name}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-white/90 text-sm 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="">No Department</option>
                  {departments.map(dept => (
                    <option key={dept._id} value={dept._id}>{dept.name}</option>
                  ))}
                </select>
              </div>
            </div>
          </div>

          {/* Account Status */}
          <div>
            <h2 className="text-xl font-bold text-white mb-4">Account Status</h2>
            <label className="flex items-center gap-3 cursor-pointer">
              <input type="checkbox" name="isActive" checked={formData.isActive} onChange={handleChange}
                className="w-5 h-5 rounded border-white/20 bg-white/10 text-primary focus:ring-primary" />
              <div>
                <span className="text-white font-medium block">Active Account</span>
                <span className="text-white/50 text-sm">User can log in and access the system</span>
              </div>
            </label>
          </div>

          {/* Password Reset */}
          <div className="pt-6 border-t border-white/10">
            <button type="button" onClick={() => alert('Password reset email sent! (Feature to be implemented)')}
              className="text-primary hover:text-primary-light transition-colors text-sm font-medium">
              Send Password Reset Email
            </button>
          </div>

          {/* Actions */}
          <div className="flex gap-4 pt-4 border-t border-white/10">
            <button type="submit" disabled={saving}
              className="flex-1 flex items-center justify-center gap-2 px-6 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 Changes...' : 'Save Changes'}
            </button>
            <button type="button" onClick={() => router.back()}
              className="px-6 py-3 bg-white/10 hover:bg-white/20 text-white rounded-lg transition-all">
              Cancel
            </button>
          </div>
        </div>
      </form>
    </div>
  )
}
