'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { ArrowLeft, Save, Shield } from 'lucide-react'
import { isAuthenticated } from '@/lib/auth'
import { apiGet, apiPost } from '@/lib/apiClient'

interface Permission {
  _id: string
  name: string
  displayName: string
  category: string
}

interface Department {
  _id: string
  name: string
  code: string
}

export default function NewRolePage() {
  const router = useRouter()
  const [loading, setLoading] = useState(false)
  const [permissions, setPermissions] = useState<Permission[]>([])
  const [departments, setDepartments] = useState<Department[]>([])
  const [formData, setFormData] = useState({
    name: '',
    displayName: '',
    description: '',
    department: '',
    level: 50,
    permissions: [] as string[],
    canManageContent: false,
    canManageUsers: false,
    canPublishContent: false,
    canApproveContent: false,
    canViewAnalytics: false,
    canManageSettings: false,
  })

  useEffect(() => {
    if (!isAuthenticated()) {
      router.push('/admin')
      return
    }
    fetchPermissions()
    fetchDepartments()
  }, [router])

  const fetchPermissions = async () => {
    try {
      const result = await apiGet<Permission[]>('/roles/meta/permissions')
      if (result.success && result.data) {
        setPermissions(result.data)
      }
    } catch (error) {
      console.error('Error fetching permissions:', error)
    }
  }

  const fetchDepartments = async () => {
    try {
      const result = await apiGet<Department[]>('/departments')
      if (result.success && result.data) {
        setDepartments(result.data)
      }
    } 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

    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value,
    }))
  }

  const handlePermissionToggle = (permissionId: string) => {
    setFormData(prev => {
      const current = prev.permissions
      const index = current.indexOf(permissionId)
      const updated = index >= 0
        ? current.filter(id => id !== permissionId)
        : [...current, permissionId]
      return { ...prev, permissions: updated }
    })
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)

    try {
      const result = await apiPost('/roles', {
        name: formData.name,
        displayName: formData.displayName,
        description: formData.description,
        department: formData.department || null,
        level: parseInt(formData.level.toString()),
        permissions: formData.permissions,
        canManageContent: formData.canManageContent,
        canManageUsers: formData.canManageUsers,
        canPublishContent: formData.canPublishContent,
        canApproveContent: formData.canApproveContent,
        canViewAnalytics: formData.canViewAnalytics,
        canManageSettings: formData.canManageSettings,
      })

      if (result.success) {
        router.push('/admin/roles')
      }
    } catch (error: any) {
      console.error('Error creating role:', error)
      alert(error.message || 'Failed to create role')
    } finally {
      setLoading(false)
    }
  }

  const permissionsByCategory = permissions.reduce((acc, perm) => {
    const category = perm.category || 'Other'
    if (!acc[category]) acc[category] = []
    acc[category].push(perm)
    return acc
  }, {} as Record<string, Permission[]>)

  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 Role</h1>
          <p className="text-white/70">Create a new user role</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">
              Role 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 uppercase"
              placeholder="ROLE_NAME"
            />
            <p className="text-white/50 text-sm mt-1">Use uppercase with underscores (e.g., CONTENT_WRITER)</p>
          </div>

          <div>
            <label htmlFor="displayName" className="block text-white font-medium mb-2">
              Display Name <span className="text-red-400">*</span>
            </label>
            <input
              type="text"
              id="displayName"
              name="displayName"
              value={formData.displayName}
              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="Content Writer"
            />
          </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={3}
            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="Role description and responsibilities..."
          />
        </div>

        {/* Department and Level */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label htmlFor="department" className="block text-white font-medium mb-2">
              Department
            </label>
            <select
              id="department"
              name="department"
              value={formData.department}
              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="">No Specific Department</option>
              {departments.map(dept => (
                <option key={dept._id} value={dept._id}>{dept.name}</option>
              ))}
            </select>
          </div>

          <div>
            <label htmlFor="level" className="block text-white font-medium mb-2">
              Access Level <span className="text-red-400">*</span>
            </label>
            <input
              type="number"
              id="level"
              name="level"
              value={formData.level}
              onChange={handleChange}
              required
              min="0"
              max="100"
              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"
            />
            <p className="text-white/50 text-sm mt-1">0-100 (higher = more access)</p>
          </div>
        </div>

        {/* Capabilities */}
        <div className="border-t border-white/10 pt-6">
          <h3 className="text-white font-semibold mb-4 flex items-center gap-2">
            <Shield className="w-5 h-5" />
            Capabilities
          </h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <label className="flex items-center gap-3 cursor-pointer">
              <input
                type="checkbox"
                name="canManageContent"
                checked={formData.canManageContent}
                onChange={handleChange}
                className="w-5 h-5 rounded border-white/20 bg-white/10 text-primary focus:ring-primary"
              />
              <span className="text-white">Manage Content</span>
            </label>

            <label className="flex items-center gap-3 cursor-pointer">
              <input
                type="checkbox"
                name="canManageUsers"
                checked={formData.canManageUsers}
                onChange={handleChange}
                className="w-5 h-5 rounded border-white/20 bg-white/10 text-primary focus:ring-primary"
              />
              <span className="text-white">Manage Users</span>
            </label>

            <label className="flex items-center gap-3 cursor-pointer">
              <input
                type="checkbox"
                name="canPublishContent"
                checked={formData.canPublishContent}
                onChange={handleChange}
                className="w-5 h-5 rounded border-white/20 bg-white/10 text-primary focus:ring-primary"
              />
              <span className="text-white">Publish Content</span>
            </label>

            <label className="flex items-center gap-3 cursor-pointer">
              <input
                type="checkbox"
                name="canApproveContent"
                checked={formData.canApproveContent}
                onChange={handleChange}
                className="w-5 h-5 rounded border-white/20 bg-white/10 text-primary focus:ring-primary"
              />
              <span className="text-white">Approve Content</span>
            </label>

            <label className="flex items-center gap-3 cursor-pointer">
              <input
                type="checkbox"
                name="canViewAnalytics"
                checked={formData.canViewAnalytics}
                onChange={handleChange}
                className="w-5 h-5 rounded border-white/20 bg-white/10 text-primary focus:ring-primary"
              />
              <span className="text-white">View Analytics</span>
            </label>

            <label className="flex items-center gap-3 cursor-pointer">
              <input
                type="checkbox"
                name="canManageSettings"
                checked={formData.canManageSettings}
                onChange={handleChange}
                className="w-5 h-5 rounded border-white/20 bg-white/10 text-primary focus:ring-primary"
              />
              <span className="text-white">Manage Settings</span>
            </label>
          </div>
        </div>

        {/* Permissions */}
        {permissions.length > 0 && (
          <div className="border-t border-white/10 pt-6">
            <h3 className="text-white font-semibold mb-4">Permissions</h3>
            <div className="space-y-4 max-h-96 overflow-y-auto">
              {Object.entries(permissionsByCategory).map(([category, perms]) => (
                <div key={category}>
                  <h4 className="text-white/70 font-medium mb-2">{category}</h4>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
                    {perms.map(perm => (
                      <label key={perm._id} className="flex items-center gap-2 cursor-pointer p-2 hover:bg-white/5 rounded">
                        <input
                          type="checkbox"
                          checked={formData.permissions.includes(perm._id)}
                          onChange={() => handlePermissionToggle(perm._id)}
                          className="w-4 h-4 rounded border-white/20 bg-white/10 text-primary focus:ring-primary"
                        />
                        <span className="text-white text-sm">{perm.displayName || perm.name}</span>
                      </label>
                    ))}
                  </div>
                </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 Role'}
          </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>
  )
}
