'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { ArrowLeft, Save, User, Mail, Phone, Shield } from 'lucide-react'
import { isAuthenticated } from '@/lib/auth'
import { apiGet, apiPost } from '@/lib/apiClient'

interface Role {
  _id: string
  name: string
  displayName: string
}

export default function NewUserPage() {
  const router = useRouter()
  const [loading, setLoading] = useState(false)
  const [roles, setRoles] = useState<Role[]>([])
  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    email: '',
    cellphone: '',
    password: '',
    confirmPassword: '',
    role: 'STAFF',
    isActive: true,
  })

  useEffect(() => {
    // Check authentication
    if (!isAuthenticated()) {
      router.push('/admin')
      return
    }
    fetchRoles()
  }, [router])

  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)
      if (error.message?.includes('Authentication required')) {
        router.push('/admin')
      }
    }
  }

  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()
    
    if (formData.password !== formData.confirmPassword) {
      alert('Passwords do not match!')
      return
    }

    if (formData.password.length < 8) {
      alert('Password must be at least 8 characters long')
      return
    }

    setLoading(true)

    try {
      const { confirmPassword, ...dataToSend } = formData

      const result = await apiPost('/users', dataToSend)

      if (result.success) {
        router.push('/admin/users')
      } else {
        alert(result.message || 'Failed to create user')
      }
    } catch (error: any) {
      console.error('Error creating user:', error)
      alert(error.message || 'An error occurred')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="space-y-6">
      <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">New User</h1>
          <p className="text-white/70">Create a new user account</p>
        </div>
      </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"
                  placeholder="John" />
              </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"
                  placeholder="Doe" />
              </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"
                  placeholder="john.doe@madibeng.gov.za" />
              </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"
                  placeholder="0821234567" />
              </div>
            </div>
          </div>

          {/* Security */}
          <div>
            <h2 className="text-xl font-bold text-white mb-4 flex items-center gap-2">
              <Shield className="w-5 h-5" /> Security
            </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">
                  Password <span className="text-red-400">*</span>
                </label>
                <input type="password" name="password" value={formData.password} onChange={handleChange} required minLength={8}
                  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"
                  placeholder="Min. 8 characters" />
              </div>
              <div>
                <label className="block text-white/90 text-sm font-medium mb-2">
                  Confirm Password <span className="text-red-400">*</span>
                </label>
                <input type="password" name="confirmPassword" value={formData.confirmPassword} onChange={handleChange} required minLength={8}
                  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"
                  placeholder="Re-enter password" />
              </div>
            </div>
            <p className="text-white/50 text-xs mt-2">
              Password must be at least 8 characters with uppercase, lowercase, and numbers
            </p>
          </div>

          {/* Role & Status */}
          <div>
            <h2 className="text-xl font-bold text-white mb-4">Role & Permissions</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}</option>
                  ))}
                </select>
              </div>
              <div className="flex items-end">
                <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" />
                  <span className="text-white">Active Account</span>
                </label>
              </div>
            </div>
          </div>

          {/* Actions */}
          <div className="flex gap-4 pt-4 border-t border-white/10">
            <button type="submit" disabled={loading}
              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" />
              {loading ? 'Creating User...' : 'Create User'}
            </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>
  )
}
