'use client'

import { useState, useEffect } from 'react'
import { ChefHat, Edit2, Trash2, Plus, Save, X } from 'lucide-react'

type Menu = {
  id: string
  title: string
  description: string
  courses: string[]
  sides: string[]
  tags: string[]
  image: string
  baseIngredientsPerCover: number
  ingredientsCostIndex: number
  baseLabourHours: number
  incrementalLabourPerCover: number
  minCovers: number
  leadTimeDays: number
  basePricePerCover: number
  ingredients?: Array<{
    name: string
    quantity: string
    perCover: boolean
  }>
}

export default function MenusManagementPage() {
  const [menus, setMenus] = useState<Menu[]>([])
  const [loading, setLoading] = useState(true)
  const [editingId, setEditingId] = useState<string | null>(null)

  useEffect(() => {
    fetchMenus()
  }, [])

  async function fetchMenus() {
    try {
      const response = await fetch('/api/menus')
      const data = await response.json()
      setMenus(data)
    } catch (error) {
      console.error('Error fetching menus:', error)
    } finally {
      setLoading(false)
    }
  }

  async function deleteMenu(id: string) {
    if (!confirm('Er du sikker på du vil slette denne menu?')) return

    try {
      const response = await fetch('/api/menus', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id })
      })

      if (response.ok) {
        setMenus(menus.filter(m => m.id !== id))
        alert('Menu slettet!')
      }
    } catch (error) {
      console.error('Error deleting menu:', error)
      alert('Kunne ikke slette menu')
    }
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 p-8">
        <div className="max-w-7xl mx-auto">
          <div className="text-center py-12">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-accent mx-auto"></div>
            <p className="mt-4 text-gray-600">Henter menuer...</p>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50 p-8">
      <div className="max-w-7xl mx-auto">
        <div className="flex items-center justify-between mb-8">
          <div>
            <h1 className="text-3xl font-bold flex items-center gap-3">
              <ChefHat className="w-8 h-8 text-accent" />
              Menu Administration
            </h1>
            <p className="text-gray-600 mt-2">
              Administrer alle menuer og ingredienser
            </p>
          </div>
          <a
            href="/admin/menu-generator"
            className="flex items-center gap-2 px-4 py-2 bg-accent text-white rounded-lg hover:bg-accent-600 transition-colors"
          >
            <Plus className="w-4 h-4" />
            Opret ny menu
          </a>
        </div>

        <div className="bg-white rounded-lg shadow-sm overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-gray-50 border-b border-gray-200">
                <tr>
                  <th className="text-left py-3 px-4 font-semibold text-gray-700">Menu</th>
                  <th className="text-left py-3 px-4 font-semibold text-gray-700">Pris/person</th>
                  <th className="text-left py-3 px-4 font-semibold text-gray-700">Min. personer</th>
                  <th className="text-left py-3 px-4 font-semibold text-gray-700">Ingredienser</th>
                  <th className="text-left py-3 px-4 font-semibold text-gray-700">Tags</th>
                  <th className="text-right py-3 px-4 font-semibold text-gray-700">Handlinger</th>
                </tr>
              </thead>
              <tbody>
                {menus.map((menu) => (
                  <tr key={menu.id} className="border-b border-gray-100 hover:bg-gray-50">
                    <td className="py-4 px-4">
                      <div className="flex items-center gap-3">
                        {menu.image && (
                          <img
                            src={menu.image}
                            alt={menu.title}
                            className="w-12 h-12 object-cover rounded"
                          />
                        )}
                        <div>
                          <div className="font-medium text-gray-900">{menu.title}</div>
                          <div className="text-sm text-gray-500">{menu.description}</div>
                        </div>
                      </div>
                    </td>
                    <td className="py-4 px-4 text-gray-700">
                      {menu.basePricePerCover} kr
                    </td>
                    <td className="py-4 px-4 text-gray-700">
                      {menu.minCovers} personer
                    </td>
                    <td className="py-4 px-4 text-gray-700">
                      {menu.ingredients?.length || 0} stk
                    </td>
                    <td className="py-4 px-4">
                      <div className="flex flex-wrap gap-1">
                        {menu.tags?.slice(0, 3).map((tag, i) => (
                          <span
                            key={i}
                            className="px-2 py-1 bg-primary-100 text-primary-700 text-xs rounded"
                          >
                            {tag}
                          </span>
                        ))}
                      </div>
                    </td>
                    <td className="py-4 px-4">
                      <div className="flex items-center justify-end gap-2">
                        <button
                          onClick={() => setEditingId(menu.id)}
                          className="p-2 text-primary-600 hover:bg-primary-50 rounded transition-colors"
                          title="Rediger"
                        >
                          <Edit2 className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => deleteMenu(menu.id)}
                          className="p-2 text-red-600 hover:bg-red-50 rounded transition-colors"
                          title="Slet"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {menus.length === 0 && (
          <div className="text-center py-12 text-gray-400">
            <ChefHat className="w-16 h-16 mx-auto mb-4 opacity-20" />
            <p>Ingen menuer fundet</p>
            <p className="text-sm mt-2">Opret din første menu med AI generator</p>
          </div>
        )}

        <div className="mt-6 text-sm text-gray-500">
          Total: {menus.length} menuer i databasen
        </div>
      </div>

      {/* Edit Modal - Simple version for now */}
      {editingId && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-lg p-6 max-w-2xl w-full max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-xl font-bold">Rediger Menu</h2>
              <button
                onClick={() => setEditingId(null)}
                className="p-2 hover:bg-gray-100 rounded"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            <p className="text-gray-600 mb-4">
              Menu ID: {editingId}
            </p>
            <p className="text-sm text-gray-500">
              Brug Menu Generator for at redigere menuer i detaljer, eller kontakt udvikler for avanceret redigering.
            </p>
            <div className="mt-6 flex gap-2">
              <button
                onClick={() => setEditingId(null)}
                className="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
              >
                Luk
              </button>
              <a
                href="/admin/menu-generator"
                className="flex-1 px-4 py-2 bg-accent text-white text-center rounded-lg hover:bg-accent-600"
              >
                Åbn Generator
              </a>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
