'use client';

import { useState, useEffect, useCallback } from 'react';
import { Plus, Search, Trash2, Tag, Package, Sliders, ToggleLeft, ToggleRight, Upload, Pencil, Leaf } from 'lucide-react';
import { useAuth } from '@client/contexts/AuthContext';
import { toast } from 'sonner';
import { InlineTableSkeleton } from '@client/components/skeletons/PageSkeletons';
import { listMenuItems, listMenuCategories, deleteMenuItem, updateMenuItem, createMenuCategory, deleteMenuCategory, updateMenuCategory } from '@client/api/menu';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import BulkUploadTab from './BulkUploadTab';
import ItemDrawer from './ItemDrawer';
import ModifiersTab from './ModifiersTab';
import { usePlanFeatures } from '@client/contexts/PlanFeaturesContext';

type Tab = 'items' | 'categories' | 'modifiers' | 'bulk-upload';

export interface ModOption { id: string; name: string; price_delta: number; is_default: boolean; is_available: boolean; display_order: number; }
export interface ModGroup { id: string; name: string; type: 'radio' | 'checkbox'; is_required: boolean; min_selections: number; max_selections: number | null; display_order: number; options: ModOption[]; }

export interface MenuItem {
  id: string; name: string; category: string; categoryId: string;
  price: number; description: string; available: boolean; dietary: string[];
  imageUrl: string; isVeg: boolean; spiceLevel: number; prepTime: number; calories: number;
  modifierGroups: ModGroup[];
}

export interface Category { id: string; name: string; itemCount: number; available: boolean; sortOrder: number; }

const SPICE_DOTS = ['', '🌶', '🌶🌶', '🌶🌶🌶'];

export default function MenuManagementPage() {
  const { t } = useLanguage();
  usePageHeader(t('nav.menuManagement', 'Menu Management'), t('nav.menuManagementSubtitle', 'Manage items, categories, modifiers and bulk uploads'));
  const { restaurantId, branchId } = useAuth();
  const { hasFeature } = usePlanFeatures();
  const canBulkUpload = hasFeature('bulk_upload');

  const [activeTab, setActiveTab] = useState<Tab>('items');
  const [search, setSearch] = useState('');
  const [categoryFilter, setCategoryFilter] = useState('');
  const [items, setItems] = useState<MenuItem[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [drawerItem, setDrawerItem] = useState<MenuItem | null | undefined>(undefined);
  const [showAddCategory, setShowAddCategory] = useState(false);
  const [newCategory, setNewCategory] = useState('');
  const [saving, setSaving] = useState(false);

  const fetchData = useCallback(async () => {
    if (!restaurantId) { setLoading(false); return; }
    setLoading(true);
    try {
      const [catResult, itemResult] = await Promise.all([listMenuCategories(), listMenuItems()]);
      const rawCats = catResult.categories || [];
      const rawItems = (itemResult.data || itemResult.items || []) as Record<string, unknown>[];

      const cats: Category[] = rawCats.map((c: Record<string, unknown>) => ({
        id: c.id as string, name: c.name as string,
        itemCount: rawItems.filter(i => i.category_id === c.id).length,
        available: (c.is_active as boolean) ?? true,
        sortOrder: (c.display_order as number) || 0,
      }));
      setCategories(cats);

      const catMap: Record<string, string> = {};
      rawCats.forEach((c: Record<string, unknown>) => { catMap[c.id as string] = c.name as string; });

      setItems(rawItems.map(i => ({
        id: i.id as string, name: i.name as string,
        category: catMap[i.category_id as string] || 'Uncategorized',
        categoryId: (i.category_id as string) || '',
        price: Number(i.price) || 0,
        description: (i.description as string) || '',
        available: (i.is_available as boolean) ?? true,
        dietary: Array.isArray(i.dietary_tags) ? i.dietary_tags as string[] : [],
        imageUrl: (i.image_url as string) || '',
        isVeg: (i.is_veg as boolean) ?? false,
        spiceLevel: (i.spice_level as number) ?? 0,
        prepTime: (i.prep_time_minutes as number) ?? 0,
        calories: (i.calories as number) ?? 0,
        modifierGroups: Array.isArray(i.modifier_groups) ? (i.modifier_groups as ModGroup[]) : [],
      })));
    } catch (err: unknown) {
      toast.error(t('menuManagement.failedToLoad', 'Failed to load menu') + ': ' + (err instanceof Error ? err.message : ''));
    } finally { setLoading(false); }
  }, [restaurantId]);

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

  const toggleItem = async (id: string, current: boolean) => {
    try {
      await updateMenuItem(id, { is_available: !current });
      setItems(prev => prev.map(i => i.id === id ? { ...i, available: !current } : i));
    } catch (err: unknown) { toast.error(t('common.failedToUpdate', 'Failed to update') + ': ' + (err instanceof Error ? err.message : '')); }
  };

  const toggleCategory = async (id: string, current: boolean) => {
    try {
      await updateMenuCategory(id, { is_active: !current });
      setCategories(prev => prev.map(c => c.id === id ? { ...c, available: !current } : c));
    } catch (err: unknown) { toast.error(t('common.failedToUpdate', 'Failed to update') + ': ' + (err instanceof Error ? err.message : '')); }
  };

  const handleAddCategory = async () => {
    if (!restaurantId || !newCategory.trim()) return;
    setSaving(true);
    try {
      const result = await createMenuCategory({ restaurant_id: restaurantId, branch_id: branchId, name: newCategory, display_order: categories.length + 1 });
      const data = result.category;
      if (data) setCategories(prev => [...prev, { id: data.id, name: data.name, itemCount: 0, available: true, sortOrder: data.display_order || prev.length + 1 }]);
      setNewCategory(''); setShowAddCategory(false);
      toast.success(t('menuManagement.categoryAdded', 'Category added'));
    } catch (err: unknown) { toast.error(t('common.failed', 'Failed') + ': ' + (err instanceof Error ? err.message : '')); }
    finally { setSaving(false); }
  };

  const handleDeleteItem = async (id: string) => {
    try {
      await deleteMenuItem(id);
      setItems(prev => prev.filter(i => i.id !== id));
      toast.success(t('menuManagement.itemDeleted', 'Item deleted'));
    } catch (err: unknown) { toast.error(t('common.failed', 'Failed') + ': ' + (err instanceof Error ? err.message : '')); }
  };

  const handleDeleteCategory = async (id: string) => {
    try {
      await deleteMenuCategory(id);
      setCategories(prev => prev.filter(c => c.id !== id));
      toast.success(t('menuManagement.categoryDeleted', 'Category deleted'));
    } catch (err: unknown) { toast.error(t('common.failed', 'Failed') + ': ' + (err instanceof Error ? err.message : '')); }
  };

  const handleItemSaved = (saved: MenuItem, isNew: boolean) => {
    const catName = categories.find(c => c.id === saved.categoryId)?.name || 'Uncategorized';
    const mapped = { ...saved, category: catName };
    if (isNew) { setItems(prev => [mapped, ...prev]); }
    else { setItems(prev => prev.map(i => i.id === saved.id ? mapped : i)); }
  };

  const filteredItems = items.filter(i => {
    const matchSearch = i.name.toLowerCase().includes(search.toLowerCase()) || i.category.toLowerCase().includes(search.toLowerCase());
    const matchCat = !categoryFilter || i.categoryId === categoryFilter;
    return matchSearch && matchCat;
  });

  const tabs: { key: Tab; label: string; icon: React.ReactNode }[] = [
    { key: 'items', label: 'Menu Items', icon: <Package size={15} /> },
    { key: 'categories', label: 'Categories', icon: <Tag size={15} /> },
    { key: 'modifiers', label: 'Modifiers', icon: <Sliders size={15} /> },
    ...(canBulkUpload ? [{ key: 'bulk-upload' as Tab, label: 'Bulk Upload', icon: <Upload size={15} /> }] : []),
  ];

  return (
    <>
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-6">
        <div className="flex gap-1 p-1 rounded-xl overflow-x-auto" style={{ backgroundColor: 'hsl(var(--muted))' }}>
          {tabs.map(t => (
            <button key={t.key} onClick={() => setActiveTab(t.key)}
              className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all whitespace-nowrap ${activeTab === t.key ? 'bg-white shadow-sm' : ''}`}
              style={{ color: activeTab === t.key ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))' }}>
              {t.icon} {t.label}
            </button>
          ))}
        </div>
        {(activeTab === 'items' || activeTab === 'categories') && (
          <button className="btn-primary" onClick={() => activeTab === 'items' ? setDrawerItem(null) : setShowAddCategory(true)}>
            <Plus size={16} /> Add {activeTab === 'items' ? 'Item' : 'Category'}
          </button>
        )}
      </div>

      {activeTab === 'bulk-upload' ? (
        <BulkUploadTab />
      ) : loading ? (
        <InlineTableSkeleton columns={5} rows={6} />
      ) : (
        <>
          {activeTab === 'items' && (
            <div>
              <div className="flex flex-wrap gap-3 mb-4">
                <div className="relative flex-1 min-w-[200px] max-w-sm">
                  <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
                  <input className="input-base pl-9" placeholder={t('menu.searchItemsPlaceholder', 'Search items…')} value={search} onChange={e => setSearch(e.target.value)} />
                </div>
                <select className="input-base max-w-xs" value={categoryFilter} onChange={e => setCategoryFilter(e.target.value)}>
                  <option value="">{t('menu.allCategories', 'All categories')}</option>
                  {categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                </select>
                <span className="text-sm self-center" style={{ color: 'hsl(var(--muted-foreground))' }}>{filteredItems.length} {t('menu.items', 'items')}</span>
              </div>

              {filteredItems.length === 0 ? (
                <div className="text-center py-16 card" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  <Package size={32} className="mx-auto mb-3 opacity-30" />
                  <p className="font-medium">{t('menu.noMenuItemsFound', 'No menu items found')}</p>
                  <p className="text-xs mt-1">{t('menu.addFirstMenuItemOrAdjustSearch', 'Add your first menu item or adjust your search')}</p>
                </div>
              ) : (
                <div className="card overflow-hidden">
                  <table className="w-full">
                    <thead>
                      <tr style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                        {[t('menu.colItem', 'Item'), t('menu.colCategory', 'Category'), t('menu.colPrice', 'Price'), t('menu.colDetails', 'Details'), t('menu.colAvailable', 'Available'), ''].map(h => (
                          <th key={h} className="text-left px-4 py-3 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>{h}</th>
                        ))}
                      </tr>
                    </thead>
                    <tbody>
                      {filteredItems.map((item, idx) => (
                        <tr key={item.id} className="table-row-hover" style={{ borderBottom: idx < filteredItems.length - 1 ? '1px solid hsl(var(--border))' : 'none' }}>
                          <td className="px-4 py-3">
                            <div className="flex items-center gap-3">
                              <div className="w-12 h-12 rounded-xl overflow-hidden shrink-0 flex items-center justify-center" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                                {item.imageUrl ? (
                                  <img src={item.imageUrl} alt={item.name} className="w-full h-full object-cover" onError={e => { (e.target as HTMLImageElement).style.display = 'none'; }} />
                                ) : (
                                  <span className="text-xl">🍽️</span>
                                )}
                              </div>
                              <div>
                                <div className="flex items-center gap-1.5 flex-wrap">
                                  <p className="font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>{item.name}</p>
                                  {item.isVeg ? (
                                    <span title={t('menu.vegetarian', 'Vegetarian')}><Leaf size={12} style={{ color: 'hsl(var(--success))' }} /></span>
                                  ) : (
                                    <span className="w-3 h-3 rounded-full bg-red-500 inline-block shrink-0" title={t('menu.nonVeg', 'Non-Veg')} />
                                  )}
                                  {item.modifierGroups.length > 0 && (
                                    <span className="badge badge-neutral text-xs" title={`${item.modifierGroups.length} modifier group${item.modifierGroups.length > 1 ? 's' : ''}`}>
                                      <Sliders size={9} className="inline mr-0.5" />{item.modifierGroups.length}
                                    </span>
                                  )}
                                </div>
                                <p className="text-xs truncate max-w-[200px]" style={{ color: 'hsl(var(--muted-foreground))' }}>{item.description}</p>
                              </div>
                            </div>
                          </td>
                          <td className="px-4 py-3"><span className="badge badge-neutral">{item.category}</span></td>
                          <td className="px-4 py-3 font-semibold tabular-nums" style={{ color: 'hsl(var(--foreground))' }}>₹{item.price.toFixed(0)}</td>
                          <td className="px-4 py-3">
                            <div className="flex flex-col gap-0.5">
                              {item.spiceLevel > 0 && <span className="text-xs">{SPICE_DOTS[item.spiceLevel] || ''}</span>}
                              {item.prepTime > 0 && <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>⏱ {item.prepTime}m</span>}
                              {item.calories > 0 && <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>🔥 {item.calories} kcal</span>}
                            </div>
                          </td>
                          <td className="px-4 py-3">
                            <button onClick={() => toggleItem(item.id, item.available)} className="flex items-center gap-2 transition-colors">
                              {item.available
                                ? <ToggleRight size={22} style={{ color: 'hsl(var(--success))' }} />
                                : <ToggleLeft size={22} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                              <span className="text-xs font-medium" style={{ color: item.available ? 'hsl(var(--success))' : 'hsl(var(--muted-foreground))' }}>
                                {item.available ? t('menu.available', 'Available') : t('menu.hidden', 'Hidden')}
                              </span>
                            </button>
                          </td>
                          <td className="px-4 py-3">
                            <div className="flex items-center gap-1">
                              <button className="btn-ghost p-1.5" style={{ color: 'hsl(var(--primary))' }} onClick={() => setDrawerItem(item)} title={t('common.edit', 'Edit')}><Pencil size={14} /></button>
                              <button className="btn-ghost p-1.5" style={{ color: 'hsl(var(--danger))' }} onClick={() => handleDeleteItem(item.id)} title={t('common.delete', 'Delete')}><Trash2 size={14} /></button>
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          )}

          {activeTab === 'categories' && (
            <div className="space-y-3">
              {showAddCategory && (
                <div className="card p-5">
                  <h3 className="font-semibold mb-3" style={{ color: 'hsl(var(--foreground))' }}>{t('menu.addCategory', 'Add Category')}</h3>
                  <div className="flex gap-3">
                    <input className="input-base flex-1" placeholder={t('menu.categoryNamePlaceholder', 'Category name *')} value={newCategory} onChange={e => setNewCategory(e.target.value)} onKeyDown={e => e.key === 'Enter' && handleAddCategory()} autoFocus />
                    <button className="btn-primary" onClick={handleAddCategory} disabled={saving}>{t('common.save', 'Save')}</button>
                    <button className="btn-secondary" onClick={() => setShowAddCategory(false)}>{t('common.cancel', 'Cancel')}</button>
                  </div>
                </div>
              )}
              {categories.length === 0 ? (
                <div className="text-center py-16 card" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  <Tag size={32} className="mx-auto mb-3 opacity-30" />
                  <p className="font-medium">{t('menu.noCategoriesYet', 'No categories yet')}</p>
                </div>
              ) : (
                categories.map(cat => (
                  <div key={cat.id} className="card p-4 flex items-center justify-between">
                    <div className="flex items-center gap-4">
                      <div className="w-8 h-8 rounded-lg flex items-center justify-center font-bold text-sm" style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}>
                        {cat.sortOrder}
                      </div>
                      <div>
                        <p className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{cat.name}</p>
                        <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{cat.itemCount} {t('menu.items', 'items')}</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-3">
                      <button onClick={() => toggleCategory(cat.id, cat.available)} className="flex items-center gap-2">
                        {cat.available ? <ToggleRight size={22} style={{ color: 'hsl(var(--success))' }} /> : <ToggleLeft size={22} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                        <span className="text-xs font-medium" style={{ color: cat.available ? 'hsl(var(--success))' : 'hsl(var(--muted-foreground))' }}>
                          {cat.available ? t('menu.visible', 'Visible') : t('menu.hidden', 'Hidden')}
                        </span>
                      </button>
                      <button className="btn-ghost p-1.5" style={{ color: 'hsl(var(--danger))' }} onClick={() => handleDeleteCategory(cat.id)}><Trash2 size={14} /></button>
                    </div>
                  </div>
                ))
              )}
            </div>
          )}

          {activeTab === 'modifiers' && (
            <ModifiersTab items={items.map(i => ({ id: i.id, name: i.name }))} categories={categories} />
          )}
        </>
      )}

      {drawerItem !== undefined && (
        <ItemDrawer
          item={drawerItem}
          categories={categories}
          onClose={() => setDrawerItem(undefined)}
          onSaved={(saved, isNew) => { handleItemSaved(saved, isNew); }}
        />
      )}
    </>
  );
}
