'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { ArrowLeft, Save } from 'lucide-react'
import { isAuthenticated } from '@/lib/auth'
import { apiGet, apiPost } from '@/lib/apiClient'

interface MenuItem {
  _id: string
  title: string
  slug: string
}

export default function NewMenuItemPage() {
  const router = useRouter()
  const [loading, setLoading] = useState(false)
  const [parentItems, setParentItems] = useState<MenuItem[]>([])
  const [formData, setFormData] = useState({
    title: '',
    slug: '',
    url: '',
    order: 0,
    parentId: '',
    isActive: true,
  })

  useEffect(() => {
    if (!isAuthenticated()) {
      router.push('/admin')
      return
    }
    fetchParentItems()
  }, [router])

  const fetchParentItems = async () => {
    try {
      const result = await apiGet<MenuItem[]>('/menu')
      if (result.success !== false && result.data) {
        setParentItems(result.data)
      } else if (Array.isArray(result)) {
        setParentItems(result)
      }
    } catch (error) {
      console.error('Error fetching parent items:', 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 generateSlug = (title: string) => {
    return title
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/(^-|-$)/g, '')
  }

  const handleTitleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const title = e.target.value
    setFormData(prev => ({
      ...prev,
      title,
      slug: prev.slug || generateSlug(title),
    }))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)

    try {
      const result = await apiPost('/menu', {
        title: formData.title,
        slug: formData.slug,
        url: formData.url || undefined,
        order: parseInt(formData.order.toString()) || 0,
        parentId: formData.parentId || undefined,
        isActive: formData.isActive,
      })

      if (result.success !== false) {
        router.push('/admin/menu')
      }
    } catch (error: any) {
      console.error('Error creating menu item:', error)
      alert(error.message || 'Failed to create menu item')
    } 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 Menu Item</h1>
          <p className="text-white/70">Create a new navigation menu item</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">
        {/* Title */}
        <div>
          <label htmlFor="title" className="block text-white font-medium mb-2">
            Title <span className="text-red-400">*</span>
          </label>
          <input
            type="text"
            id="title"
            name="title"
            value={formData.title}
            onChange={handleTitleChange}
            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="Menu item title"
          />
        </div>

        {/* Slug */}
        <div>
          <label htmlFor="slug" className="block text-white font-medium mb-2">
            Slug <span className="text-red-400">*</span>
          </label>
          <input
            type="text"
            id="slug"
            name="slug"
            value={formData.slug}
            onChange={handleChange}
            required
            pattern="[a-z0-9-]+"
            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="menu-item-slug"
          />
        </div>

        {/* URL */}
        <div>
          <label htmlFor="url" className="block text-white font-medium mb-2">
            URL
          </label>
          <input
            type="text"
            id="url"
            name="url"
            value={formData.url}
            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="/page-url or https://example.com"
          />
        </div>

        {/* Parent Item */}
        <div>
          <label htmlFor="parentId" className="block text-white font-medium mb-2">
            Parent Menu Item
          </label>
          <select
            id="parentId"
            name="parentId"
            value={formData.parentId}
            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)</option>
            {parentItems.map(item => (
              <option key={item._id} value={item._id}>{item.title}</option>
            ))}
          </select>
        </div>

        {/* Order */}
        <div>
          <label htmlFor="order" className="block text-white font-medium mb-2">
            Display Order
          </label>
          <input
            type="number"
            id="order"
            name="order"
            value={formData.order}
            onChange={handleChange}
            min="0"
            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>

        {/* 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 (visible in menu)
          </label>
        </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 Menu Item'}
          </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>
  )
}
