'use client';

import { useState, useEffect, useCallback } from 'react';
import {
  Plus, Save, Trash2, Edit2, GripVertical, X, ChevronDown,
  Palette, Package, DollarSign, Tag, Search,
  Monitor, AlertTriangle, Ban, RotateCcw
} from 'lucide-react';

interface Category {
  id: string;
  name: string;
  displayName: string;
  color: string;
  icon: string;
  sortOrder: number;
  isActive: boolean;
  items: MenuItem[];
}

interface MenuItem {
  id: string;
  name: string;
  shortName: string;
  description: string;
  categoryId: string;
  price: number;
  costPrice: number;
  taxRate: number;
  sku: string;
  barcode: string;
  color: string;
  sortOrder: number;
  isActive: boolean;
  modifierGroups: any[];
}

const COLORS = [
  '#ef4444', '#f59e0b', '#22c55e', '#3b82f6', '#a855f7',
  '#ec4899', '#14b8a6', '#f97316', '#6366f1', '#d97706',
  '#dc2626', '#84cc16', '#0EA5E9', '#FDBA74', '#e11d48',
];

const ICONS = ['Soup', 'Beef', 'Salad', 'Coffee', 'Cake', 'Wine', 'Pizza', 'Fish', 'Sandwich', 'IceCream'];

export default function POSAdminPage() {
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<'categories' | 'items'>('categories');
  const [editingCategory, setEditingCategory] = useState<Partial<Category> | null>(null);
  const [editingItem, setEditingItem] = useState<Partial<MenuItem> | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [notification, setNotification] = useState<{ message: string; type: 'success' | 'error' } | null>(null);

  const showNotification = (message: string, type: 'success' | 'error' = 'success') => {
    setNotification({ message, type });
    setTimeout(() => setNotification(null), 3000);
  };

  const fetchData = useCallback(async () => {
    try {
      const res = await fetch('/api/pos/menu');
      const data = await res.json();
      if (data.categories) setCategories(data.categories);
    } catch {
      showNotification('Failed to load menu data', 'error');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { fetchData(); }, [fetchData]);

  const saveCategory = async () => {
    if (!editingCategory?.displayName) return;
    try {
      const res = await fetch('/api/pos/menu', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          type: 'category',
          action: editingCategory.id ? 'update' : 'create',
          data: editingCategory,
        }),
      });
      if (res.ok) {
        showNotification(editingCategory.id ? 'Category updated' : 'Category created');
        setEditingCategory(null);
        fetchData();
      } else {
        const err = await res.json();
        showNotification(err.error || 'Failed to save', 'error');
      }
    } catch {
      showNotification('Failed to save category', 'error');
    }
  };

  const saveItem = async () => {
    if (!editingItem?.name || !editingItem?.categoryId || !editingItem?.price) return;
    try {
      const res = await fetch('/api/pos/menu', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          type: 'item',
          action: editingItem.id ? 'update' : 'create',
          data: editingItem,
        }),
      });
      if (res.ok) {
        showNotification(editingItem.id ? 'Item updated' : 'Item created');
        setEditingItem(null);
        fetchData();
      } else {
        const err = await res.json();
        showNotification(err.error || 'Failed to save', 'error');
      }
    } catch {
      showNotification('Failed to save item', 'error');
    }
  };

  const toggleItemActive = async (item: MenuItem) => {
    try {
      await fetch('/api/pos/menu', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          type: 'item',
          action: 'update',
          data: { id: item.id, isActive: !item.isActive },
        }),
      });
      showNotification(item.isActive ? 'Item deactivated (§13 — soft-delete)' : 'Item reactivated');
      fetchData();
    } catch {
      showNotification('Failed to update item', 'error');
    }
  };

  const toggleCategoryActive = async (cat: Category) => {
    try {
      await fetch('/api/pos/menu', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          type: 'category',
          action: 'update',
          data: { id: cat.id, isActive: !cat.isActive },
        }),
      });
      showNotification(cat.isActive ? 'Category deactivated' : 'Category reactivated');
      fetchData();
    } catch {
      showNotification('Failed to update category', 'error');
    }
  };

  const allItems = categories.flatMap(c => c.items.map(i => ({ ...i, categoryName: c.displayName })));
  const filteredItems = searchTerm
    ? allItems.filter(i => i.name.toLowerCase().includes(searchTerm.toLowerCase()) || i.sku?.toLowerCase().includes(searchTerm.toLowerCase()))
    : allItems;

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500" />
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      {/* Notification */}
      {notification && (
        <div className={`fixed top-4 right-4 z-50 px-4 py-3 rounded-lg shadow-lg text-white text-sm font-medium ${
          notification.type === 'success' ? 'bg-green-600' : 'bg-red-600'
        }`}>
          {notification.message}
        </div>
      )}

      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white flex items-center gap-3">
            <Monitor className="w-7 h-7 text-blue-400" />
            POS Menu Management
          </h1>
          <p className="text-gray-400 mt-1">Manage categories, menu items, modifiers, and pricing</p>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-2 border-b border-white/10 pb-2">
        {(['categories', 'items'] as const).map(tab => (
          <button
            key={tab}
            onClick={() => setActiveTab(tab)}
            className={`px-4 py-2 rounded-t-lg text-sm font-medium transition-colors ${
              activeTab === tab
                ? 'bg-white/10 text-white border-b-2 border-blue-500'
                : 'text-gray-400 hover:text-white'
            }`}
          >
            {tab === 'categories' ? `Categories (${categories.length})` : `Menu Items (${allItems.length})`}
          </button>
        ))}
      </div>

      {/* CATEGORIES TAB */}
      {activeTab === 'categories' && (
        <div className="space-y-4">
          <button
            onClick={() => setEditingCategory({ displayName: '', name: '', color: '#3b82f6', icon: 'Soup', sortOrder: categories.length + 1 })}
            className="flex items-center gap-2 px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors"
          >
            <Plus className="w-4 h-4" /> Add Category
          </button>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {categories.map(cat => (
              <div
                key={cat.id}
                className={`bg-black/40 border rounded-xl p-4 transition-all ${
                  cat.isActive ? 'border-white/10' : 'border-red-500/30 opacity-60'
                }`}
              >
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-lg flex items-center justify-center text-white font-bold" style={{ backgroundColor: cat.color }}>
                      {cat.displayName.charAt(0)}
                    </div>
                    <div>
                      <h3 className="font-semibold text-white">{cat.displayName}</h3>
                      <p className="text-xs text-gray-400">{cat.items.length} items · Order #{cat.sortOrder}</p>
                    </div>
                  </div>
                  <div className="flex items-center gap-1">
                    <button
                      onClick={() => setEditingCategory(cat)}
                      className="p-1.5 hover:bg-white/10 rounded-lg transition-colors text-gray-400 hover:text-white"
                    >
                      <Edit2 className="w-4 h-4" />
                    </button>
                    <button
                      onClick={() => toggleCategoryActive(cat)}
                      className={`p-1.5 hover:bg-white/10 rounded-lg transition-colors ${
                        cat.isActive ? 'text-gray-400 hover:text-red-400' : 'text-red-400 hover:text-green-400'
                      }`}
                      title={cat.isActive ? 'Deactivate' : 'Reactivate'}
                    >
                      {cat.isActive ? <Ban className="w-4 h-4" /> : <RotateCcw className="w-4 h-4" />}
                    </button>
                  </div>
                </div>
                {!cat.isActive && (
                  <div className="flex items-center gap-1 text-xs text-red-400 mb-2">
                    <AlertTriangle className="w-3 h-3" /> Inactive
                  </div>
                )}
                <div className="flex flex-wrap gap-1">
                  {cat.items.slice(0, 5).map(item => (
                    <span key={item.id} className="text-xs px-2 py-0.5 rounded-full bg-white/5 text-gray-400">{item.shortName || item.name}</span>
                  ))}
                  {cat.items.length > 5 && (
                    <span className="text-xs px-2 py-0.5 rounded-full bg-white/5 text-gray-500">+{cat.items.length - 5}</span>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ITEMS TAB */}
      {activeTab === 'items' && (
        <div className="space-y-4">
          <div className="flex items-center gap-3">
            <button
              onClick={() => setEditingItem({
                name: '', shortName: '', categoryId: categories[0]?.id || '',
                price: 0, costPrice: 0, taxRate: 0.0825, color: '#3b82f6',
                sortOrder: 0, modifierGroups: [],
              })}
              className="flex items-center gap-2 px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors"
            >
              <Plus className="w-4 h-4" /> Add Item
            </button>
            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
              <input
                type="text"
                placeholder="Search items by name or SKU..."
                value={searchTerm}
                onChange={e => setSearchTerm(e.target.value)}
                className="w-full pl-10 pr-4 py-2.5 bg-black/40 border border-white/10 rounded-lg text-sm text-white placeholder:text-gray-500 focus:outline-none focus:border-blue-500"
              />
            </div>
          </div>

          {/* Items Table */}
          <div className="bg-black/40 border border-white/10 rounded-xl overflow-hidden">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-white/10">
                  <th className="text-left px-4 py-3 text-gray-400 font-medium">Item</th>
                  <th className="text-left px-4 py-3 text-gray-400 font-medium">Category</th>
                  <th className="text-right px-4 py-3 text-gray-400 font-medium">Price</th>
                  <th className="text-right px-4 py-3 text-gray-400 font-medium">Cost</th>
                  <th className="text-right px-4 py-3 text-gray-400 font-medium">Margin</th>
                  <th className="text-right px-4 py-3 text-gray-400 font-medium">Tax</th>
                  <th className="text-center px-4 py-3 text-gray-400 font-medium">Status</th>
                  <th className="text-right px-4 py-3 text-gray-400 font-medium">Actions</th>
                </tr>
              </thead>
              <tbody>
                {filteredItems.map(item => {
                  const margin = item.price > 0 ? ((item.price - item.costPrice) / item.price * 100).toFixed(1) : '—';
                  return (
                    <tr key={item.id} className={`border-b border-white/5 hover:bg-white/5 transition-colors ${
                      !item.isActive ? 'opacity-50' : ''
                    }`}>
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-3">
                          <div className="w-8 h-8 rounded-lg flex items-center justify-center text-white text-xs font-bold" style={{ backgroundColor: item.color }}>
                            {(item.shortName || item.name).charAt(0)}
                          </div>
                          <div>
                            <p className="text-white font-medium">{item.name}</p>
                            {item.shortName && <p className="text-xs text-gray-500">{item.shortName}</p>}
                          </div>
                        </div>
                      </td>
                      <td className="px-4 py-3 text-gray-400">{(item as any).categoryName}</td>
                      <td className="px-4 py-3 text-right text-white font-mono">${item.price.toFixed(2)}</td>
                      <td className="px-4 py-3 text-right text-gray-400 font-mono">${item.costPrice.toFixed(2)}</td>
                      <td className="px-4 py-3 text-right">
                        <span className={`font-mono ${parseFloat(margin as string) > 60 ? 'text-green-400' : parseFloat(margin as string) > 30 ? 'text-yellow-400' : 'text-red-400'}`}>
                          {margin}%
                        </span>
                      </td>
                      <td className="px-4 py-3 text-right text-gray-400 font-mono">{(item.taxRate * 100).toFixed(2)}%</td>
                      <td className="px-4 py-3 text-center">
                        <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${
                          item.isActive ? 'bg-green-500/20 text-green-400' : 'bg-red-500/20 text-red-400'
                        }`}>
                          {item.isActive ? 'Active' : 'Inactive'}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-right">
                        <div className="flex items-center justify-end gap-1">
                          <button
                            onClick={() => setEditingItem(item)}
                            className="p-1.5 hover:bg-white/10 rounded-lg transition-colors text-gray-400 hover:text-white"
                          >
                            <Edit2 className="w-4 h-4" />
                          </button>
                          <button
                            onClick={() => toggleItemActive(item)}
                            className={`p-1.5 hover:bg-white/10 rounded-lg transition-colors ${
                              item.isActive ? 'text-gray-400 hover:text-red-400' : 'text-red-400 hover:text-green-400'
                            }`}
                            title={item.isActive ? 'Deactivate (§13)' : 'Reactivate'}
                          >
                            {item.isActive ? <Ban className="w-4 h-4" /> : <RotateCcw className="w-4 h-4" />}
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
            {filteredItems.length === 0 && (
              <div className="text-center py-12 text-gray-500">
                <Package className="w-8 h-8 mx-auto mb-2 opacity-50" />
                <p>No items found</p>
              </div>
            )}
          </div>
        </div>
      )}

      {/* CATEGORY EDITOR MODAL */}
      {editingCategory && (
        <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50" onClick={() => setEditingCategory(null)}>
          <div className="bg-gray-900 border border-white/10 rounded-2xl p-6 w-full max-w-md" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-bold text-white">{editingCategory.id ? 'Edit Category' : 'New Category'}</h2>
              <button onClick={() => setEditingCategory(null)} className="text-gray-400 hover:text-white"><X className="w-5 h-5" /></button>
            </div>
            <div className="space-y-4">
              <div>
                <label className="block text-sm text-gray-400 mb-1">Display Name</label>
                <input
                  type="text"
                  value={editingCategory.displayName || ''}
                  onChange={e => setEditingCategory({ ...editingCategory, displayName: e.target.value, name: e.target.value.toLowerCase().replace(/[^a-z0-9]+/g, '_') })}
                  className="w-full px-3 py-2.5 bg-black/40 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:border-blue-500"
                  placeholder="e.g. Appetizers"
                />
              </div>
              <div>
                <label className="block text-sm text-gray-400 mb-1">Color</label>
                <div className="flex flex-wrap gap-2">
                  {COLORS.map(c => (
                    <button
                      key={c}
                      onClick={() => setEditingCategory({ ...editingCategory, color: c })}
                      className={`w-8 h-8 rounded-lg border-2 transition-all ${
                        editingCategory.color === c ? 'border-white scale-110' : 'border-transparent'
                      }`}
                      style={{ backgroundColor: c }}
                    />
                  ))}
                </div>
              </div>
              <div>
                <label className="block text-sm text-gray-400 mb-1">Sort Order</label>
                <input
                  type="number"
                  value={editingCategory.sortOrder || 0}
                  onChange={e => setEditingCategory({ ...editingCategory, sortOrder: parseInt(e.target.value) || 0 })}
                  className="w-full px-3 py-2.5 bg-black/40 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:border-blue-500"
                />
              </div>
              <button
                onClick={saveCategory}
                className="w-full py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors flex items-center justify-center gap-2"
              >
                <Save className="w-4 h-4" /> {editingCategory.id ? 'Update Category' : 'Create Category'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ITEM EDITOR MODAL */}
      {editingItem && (
        <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 overflow-y-auto" onClick={() => setEditingItem(null)}>
          <div className="bg-gray-900 border border-white/10 rounded-2xl p-6 w-full max-w-lg my-8" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-bold text-white">{editingItem.id ? 'Edit Item' : 'New Menu Item'}</h2>
              <button onClick={() => setEditingItem(null)} className="text-gray-400 hover:text-white"><X className="w-5 h-5" /></button>
            </div>
            <div className="space-y-4 max-h-[70vh] overflow-y-auto pr-2">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm text-gray-400 mb-1">Name *</label>
                  <input
                    type="text"
                    value={editingItem.name || ''}
                    onChange={e => setEditingItem({ ...editingItem, name: e.target.value })}
                    className="w-full px-3 py-2.5 bg-black/40 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:border-blue-500"
                    placeholder="Classic Burger"
                  />
                </div>
                <div>
                  <label className="block text-sm text-gray-400 mb-1">Short Name</label>
                  <input
                    type="text"
                    value={editingItem.shortName || ''}
                    onChange={e => setEditingItem({ ...editingItem, shortName: e.target.value })}
                    className="w-full px-3 py-2.5 bg-black/40 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:border-blue-500"
                    placeholder="Burger"
                  />
                </div>
              </div>
              <div>
                <label className="block text-sm text-gray-400 mb-1">Category *</label>
                <select
                  value={editingItem.categoryId || ''}
                  onChange={e => setEditingItem({ ...editingItem, categoryId: e.target.value })}
                  className="w-full px-3 py-2.5 bg-black/40 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:border-blue-500"
                >
                  <option value="" className="bg-gray-900">Select category</option>
                  {categories.filter(c => c.isActive).map(c => (
                    <option key={c.id} value={c.id} className="bg-gray-900">{c.displayName}</option>
                  ))}
                </select>
              </div>
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm text-gray-400 mb-1">Price *</label>
                  <div className="relative">
                    <DollarSign className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                    <input
                      type="number"
                      step="0.01"
                      value={editingItem.price || ''}
                      onChange={e => setEditingItem({ ...editingItem, price: parseFloat(e.target.value) || 0 })}
                      className="w-full pl-9 pr-3 py-2.5 bg-black/40 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:border-blue-500"
                    />
                  </div>
                </div>
                <div>
                  <label className="block text-sm text-gray-400 mb-1">Cost</label>
                  <div className="relative">
                    <DollarSign className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                    <input
                      type="number"
                      step="0.01"
                      value={editingItem.costPrice || ''}
                      onChange={e => setEditingItem({ ...editingItem, costPrice: parseFloat(e.target.value) || 0 })}
                      className="w-full pl-9 pr-3 py-2.5 bg-black/40 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:border-blue-500"
                    />
                  </div>
                </div>
                <div>
                  <label className="block text-sm text-gray-400 mb-1">Tax Rate</label>
                  <input
                    type="number"
                    step="0.0025"
                    value={editingItem.taxRate || ''}
                    onChange={e => setEditingItem({ ...editingItem, taxRate: parseFloat(e.target.value) || 0 })}
                    className="w-full px-3 py-2.5 bg-black/40 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:border-blue-500"
                    placeholder="0.0825"
                  />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm text-gray-400 mb-1">SKU</label>
                  <input
                    type="text"
                    value={editingItem.sku || ''}
                    onChange={e => setEditingItem({ ...editingItem, sku: e.target.value })}
                    className="w-full px-3 py-2.5 bg-black/40 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:border-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm text-gray-400 mb-1">Barcode</label>
                  <input
                    type="text"
                    value={editingItem.barcode || ''}
                    onChange={e => setEditingItem({ ...editingItem, barcode: e.target.value })}
                    className="w-full px-3 py-2.5 bg-black/40 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:border-blue-500"
                  />
                </div>
              </div>
              <div>
                <label className="block text-sm text-gray-400 mb-1">Color</label>
                <div className="flex flex-wrap gap-2">
                  {COLORS.map(c => (
                    <button
                      key={c}
                      onClick={() => setEditingItem({ ...editingItem, color: c })}
                      className={`w-7 h-7 rounded-lg border-2 transition-all ${
                        editingItem.color === c ? 'border-white scale-110' : 'border-transparent'
                      }`}
                      style={{ backgroundColor: c }}
                    />
                  ))}
                </div>
              </div>
              <div>
                <label className="block text-sm text-gray-400 mb-1">Description</label>
                <textarea
                  value={editingItem.description || ''}
                  onChange={e => setEditingItem({ ...editingItem, description: e.target.value })}
                  className="w-full px-3 py-2.5 bg-black/40 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:border-blue-500 h-20 resize-none"
                />
              </div>
              <button
                onClick={saveItem}
                className="w-full py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors flex items-center justify-center gap-2"
              >
                <Save className="w-4 h-4" /> {editingItem.id ? 'Update Item' : 'Create Item'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
