'use client';

import { useState, useEffect, useCallback } from 'react';
import { Plus, Trash2, ChevronDown, ChevronRight, Sliders, Check, X, Loader2, Pencil } from 'lucide-react';
import { toast } from 'sonner';
import { listModifierGroups, createModifierGroup, updateModifierGroup, deleteModifierGroup, createModifierOption, updateModifierOption, deleteModifierOption } from '@client/api/menu';
import { useLanguage } from '@client/contexts/LanguageContext';
import type { Category, ModGroup, ModOption } from './page';

interface SimpleItem { id: string; name: string; }

interface Props {
  items: SimpleItem[];
  categories: Category[];
}

export default function ModifiersTab({ items }: Props) {
  const { t } = useLanguage();
  const [groups, setGroups] = useState<ModGroup[]>([]);
  const [loading, setLoading] = useState(true);
  const [filterItem, setFilterItem] = useState('');
  const [expanded, setExpanded] = useState<Set<string>>(new Set());
  const [addingGroup, setAddingGroup] = useState(false);
  const [newGroup, setNewGroup] = useState({ menu_item_id: '', name: '', type: 'checkbox' as 'radio' | 'checkbox', isRequired: false, minSelections: '0', maxSelections: '' });
  const [editingGroup, setEditingGroup] = useState<string | null>(null);
  const [editGroupForm, setEditGroupForm] = useState({ name: '', type: 'checkbox' as 'radio' | 'checkbox', isRequired: false, minSelections: '0', maxSelections: '' });
  const [addingOption, setAddingOption] = useState<string | null>(null);
  const [newOption, setNewOption] = useState({ name: '', priceDelta: '', isDefault: false });
  const [editingOption, setEditingOption] = useState<{ groupId: string; optId: string } | null>(null);
  const [editOptionForm, setEditOptionForm] = useState({ name: '', priceDelta: '', isDefault: false });

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const params: Record<string, string> = {};
      if (filterItem) params.item_id = filterItem;
      const res = await listModifierGroups(params);
      setGroups((res as { groups: ModGroup[] }).groups ?? []);
    } catch (e: unknown) {
      toast.error(e instanceof Error ? e.message : t('menuManagement.failedToLoadModifierGroups', 'Failed to load modifier groups'));
    } finally { setLoading(false); }
  }, [filterItem, t]);

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

  const handleAddGroup = async () => {
    if (!newGroup.name.trim() || !newGroup.menu_item_id) { toast.error(t('menuManagement.selectItemAndEnterName', 'Select an item and enter a group name')); return; }
    try {
      const res = await createModifierGroup({
        menu_item_id: newGroup.menu_item_id, name: newGroup.name, type: newGroup.type,
        is_required: newGroup.isRequired,
        min_selections: parseInt(newGroup.minSelections, 10) || 0,
        max_selections: newGroup.maxSelections ? parseInt(newGroup.maxSelections, 10) : null,
      });
      const g = (res as { group: Record<string, unknown> }).group as Record<string, unknown>;
      const itemName = items.find(i => i.id === newGroup.menu_item_id)?.name ?? 'Unknown';
      setGroups(prev => [...prev, { id: g.id as string, name: g.name as string, type: g.type as 'radio' | 'checkbox', is_required: g.is_required as boolean, min_selections: (g.min_selections as number) ?? 0, max_selections: (g.max_selections as number | null) ?? null, options: [], display_order: (g.display_order as number) ?? 0, item_name: itemName, menu_item_id: newGroup.menu_item_id } as ModGroup & { item_name: string; menu_item_id: string }]);
      setExpanded(prev => new Set([...prev, g.id as string]));
      setNewGroup({ menu_item_id: '', name: '', type: 'checkbox', isRequired: false, minSelections: '0', maxSelections: '' });
      setAddingGroup(false);
    } catch (e: unknown) { toast.error(e instanceof Error ? e.message : 'Failed to create group'); }
  };

  const startEditGroup = (g: ModGroup & { item_name?: string }) => {
    setEditingGroup(g.id);
    setEditGroupForm({ name: g.name, type: g.type, isRequired: g.is_required, minSelections: g.min_selections?.toString() ?? '0', maxSelections: g.max_selections?.toString() ?? '' });
  };

  const handleUpdateGroup = async (groupId: string) => {
    try {
      const res = await updateModifierGroup(groupId, {
        name: editGroupForm.name, type: editGroupForm.type,
        is_required: editGroupForm.isRequired,
        min_selections: parseInt(editGroupForm.minSelections, 10) || 0,
        max_selections: editGroupForm.maxSelections ? parseInt(editGroupForm.maxSelections, 10) : null,
      });
      const g = (res as { group: Record<string, unknown> }).group as Record<string, unknown>;
      setGroups(prev => prev.map(grp => grp.id === groupId ? { ...grp, name: g.name as string, type: g.type as 'radio' | 'checkbox', is_required: g.is_required as boolean, min_selections: (g.min_selections as number) ?? 0, max_selections: (g.max_selections as number | null) ?? null } : grp));
      setEditingGroup(null);
      toast.success(t('menuManagement.groupUpdated', 'Group updated'));
    } catch (e: unknown) { toast.error(e instanceof Error ? e.message : t('menuManagement.failedToUpdateGroup', 'Failed to update group')); }
  };

  const handleDeleteGroup = async (groupId: string) => {
    try { await deleteModifierGroup(groupId); setGroups(prev => prev.filter(g => g.id !== groupId)); toast.success(t('menuManagement.groupDeleted', 'Group deleted')); }
    catch (e: unknown) { toast.error(e instanceof Error ? e.message : t('menuManagement.failedToDeleteGroup', 'Failed to delete group')); }
  };

  const handleAddOption = async (groupId: string) => {
    if (!newOption.name.trim()) return;
    try {
      const res = await createModifierOption(groupId, { name: newOption.name, price_delta: parseFloat(newOption.priceDelta) || 0, is_default: newOption.isDefault });
      const o = (res as { option: Record<string, unknown> }).option as Record<string, unknown>;
      setGroups(prev => prev.map(g => g.id === groupId ? { ...g, options: [...g.options, { id: o.id as string, name: o.name as string, price_delta: Number(o.price_delta), is_default: o.is_default as boolean, is_available: true, display_order: 0 }] } : g));
      setNewOption({ name: '', priceDelta: '', isDefault: false }); setAddingOption(null);
    } catch (e: unknown) { toast.error(e instanceof Error ? e.message : t('menuManagement.failedToAddOption', 'Failed to add option')); }
  };

  const startEditOption = (groupId: string, opt: ModOption) => {
    setEditingOption({ groupId, optId: opt.id });
    setEditOptionForm({ name: opt.name, priceDelta: opt.price_delta !== 0 ? opt.price_delta.toString() : '', isDefault: opt.is_default });
  };

  const handleUpdateOption = async () => {
    if (!editingOption) return;
    try {
      const res = await updateModifierOption(editingOption.groupId, editingOption.optId, { name: editOptionForm.name, price_delta: parseFloat(editOptionForm.priceDelta) || 0, is_default: editOptionForm.isDefault });
      const o = (res as { option: Record<string, unknown> }).option as Record<string, unknown>;
      setGroups(prev => prev.map(g => g.id === editingOption.groupId ? { ...g, options: g.options.map(opt => opt.id === editingOption.optId ? { ...opt, name: o.name as string, price_delta: Number(o.price_delta), is_default: o.is_default as boolean } : opt) } : g));
      setEditingOption(null);
      toast.success(t('menuManagement.optionUpdated', 'Option updated'));
    } catch (e: unknown) { toast.error(e instanceof Error ? e.message : t('menuManagement.failedToUpdateOption', 'Failed to update option')); }
  };

  const handleDeleteOption = async (groupId: string, optId: string) => {
    try { await deleteModifierOption(groupId, optId); setGroups(prev => prev.map(g => g.id === groupId ? { ...g, options: g.options.filter(o => o.id !== optId) } : g)); }
    catch (e: unknown) { toast.error(e instanceof Error ? e.message : t('menuManagement.failedToDeleteOption', 'Failed to delete option')); }
  };

  const toggleExpand = (id: string) => setExpanded(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });

  if (loading) return (
    <div className="flex items-center justify-center py-16 gap-3" style={{ color: 'hsl(var(--muted-foreground))' }}>
      <Loader2 size={20} className="animate-spin" /> {t('menuManagement.loadingModifierGroups', 'Loading modifier groups…')}
    </div>
  );

  const typedGroups = groups as Array<ModGroup & { item_name?: string }>;

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center gap-3">
        <select className="input-base max-w-xs" value={filterItem} onChange={e => setFilterItem(e.target.value)}>
          <option value="">{t('menuManagement.allItems', 'All items')}</option>
          {items.map(i => <option key={i.id} value={i.id}>{i.name}</option>)}
        </select>
        <button className="btn-primary ml-auto" onClick={() => setAddingGroup(true)}><Plus size={15} /> {t('menuManagement.addModifierGroup', 'Add Modifier Group')}</button>
      </div>

      {addingGroup && (
        <div className="card p-4 space-y-3 border-2" style={{ borderColor: 'hsl(var(--primary))' }}>
          <h4 className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{t('menuManagement.newModifierGroup', 'New Modifier Group')}</h4>
          <select className="input-base" value={newGroup.menu_item_id} onChange={e => setNewGroup(g => ({ ...g, menu_item_id: e.target.value }))}>
            <option value="">{t('menuManagement.selectItemPlaceholder', 'Select item…')}</option>
            {items.map(i => <option key={i.id} value={i.id}>{i.name}</option>)}
          </select>
          <input className="input-base" placeholder={t('menuManagement.modifierGroupNamePlaceholder', 'Group name (e.g. Choose Size, Add-ons, Sides)')} value={newGroup.name} onChange={e => setNewGroup(g => ({ ...g, name: e.target.value }))} />
          <div className="flex gap-2">
            {(['radio', 'checkbox'] as const).map(t_grp => (
              <button key={t_grp} onClick={() => setNewGroup(g => ({ ...g, type: t_grp }))} className="flex-1 py-2 rounded-lg text-sm font-medium border transition-all"
                style={{ borderColor: newGroup.type === t_grp ? 'hsl(var(--primary))' : 'hsl(var(--border))', backgroundColor: newGroup.type === t_grp ? 'hsl(var(--primary-light))' : 'transparent', color: newGroup.type === t_grp ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))' }}>
                {t_grp === 'radio' ? t('menuManagement.radioPickOneLong', '⦿ Radio — pick one') : t('menuManagement.checkboxPickManyLong', '☑ Checkbox — pick many')}
              </button>
            ))}
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div><label className="label-base">{t('menuManagement.minSelections', 'Min selections')}</label><input type="number" min="0" className="input-base" value={newGroup.minSelections} onChange={e => setNewGroup(g => ({ ...g, minSelections: e.target.value }))} /></div>
            <div><label className="label-base">{t('menuManagement.maxSelections', 'Max selections')}</label><input type="number" min="1" className="input-base" placeholder={t('menuManagement.noLimit', 'No limit')} value={newGroup.maxSelections} onChange={e => setNewGroup(g => ({ ...g, maxSelections: e.target.value }))} /></div>
          </div>
          <label className="flex items-center gap-2 text-sm cursor-pointer" style={{ color: 'hsl(var(--foreground))' }}>
            <input type="checkbox" checked={newGroup.isRequired} onChange={e => setNewGroup(g => ({ ...g, isRequired: e.target.checked }))} /> {t('menuManagement.required', 'Required')}
          </label>
          <div className="flex gap-2">
            <button className="btn-primary flex-1" onClick={handleAddGroup}><Check size={14} /> {t('menuManagement.createGroup', 'Create Group')}</button>
            <button className="btn-secondary" onClick={() => setAddingGroup(false)}><X size={14} /></button>
          </div>
        </div>
      )}

      {typedGroups.length === 0 ? (
        <div className="text-center py-16 card" style={{ color: 'hsl(var(--muted-foreground))' }}>
          <Sliders size={32} className="mx-auto mb-3 opacity-30" />
          <p className="font-medium">{t('menuManagement.noModifierGroupsYet', 'No modifier groups yet')}</p>
          <p className="text-xs mt-1">{t('menuManagement.noModifierGroupsDesc', 'Add sizes, add-ons, or side options for your menu items')}</p>
        </div>
      ) : (
        <div className="space-y-3">
          {typedGroups.map(group => (
            <div key={group.id} className="card overflow-hidden">
              {editingGroup === group.id ? (
                <div className="p-4 space-y-3" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                  <input className="input-base" value={editGroupForm.name} onChange={e => setEditGroupForm(f => ({ ...f, name: e.target.value }))} autoFocus />
                  <div className="flex gap-2">
                    {(['radio', 'checkbox'] as const).map(gtype => (
                      <button key={gtype} onClick={() => setEditGroupForm(f => ({ ...f, type: gtype }))} className="flex-1 py-2 rounded-lg text-sm font-medium border transition-all"
                        style={{ borderColor: editGroupForm.type === gtype ? 'hsl(var(--primary))' : 'hsl(var(--border))', backgroundColor: editGroupForm.type === gtype ? 'hsl(var(--primary-light))' : 'transparent', color: editGroupForm.type === gtype ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))' }}>
                        {gtype === 'radio' ? t('menuManagement.radio', 'Radio') : t('menuManagement.checkbox', 'Checkbox')}
                      </button>
                    ))}
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    <div><label className="label-base">{t('menuManagement.minSelections', 'Min selections')}</label><input type="number" min="0" className="input-base" value={editGroupForm.minSelections} onChange={e => setEditGroupForm(f => ({ ...f, minSelections: e.target.value }))} /></div>
                    <div><label className="label-base">{t('menuManagement.maxSelections', 'Max selections')}</label><input type="number" min="1" className="input-base" placeholder={t('menuManagement.noLimit', 'No limit')} value={editGroupForm.maxSelections} onChange={e => setEditGroupForm(f => ({ ...f, maxSelections: e.target.value }))} /></div>
                  </div>
                  <label className="flex items-center gap-2 text-sm cursor-pointer"><input type="checkbox" checked={editGroupForm.isRequired} onChange={e => setEditGroupForm(f => ({ ...f, isRequired: e.target.checked }))} /> {t('menuManagement.required', 'Required')}</label>
                  <div className="flex gap-2">
                    <button className="btn-primary flex-1" onClick={() => handleUpdateGroup(group.id)}><Check size={14} /> {t('common.saveChanges', 'Save Changes')}</button>
                    <button className="btn-secondary" onClick={() => setEditingGroup(null)}><X size={14} /></button>
                  </div>
                </div>
              ) : (
                <div className="flex items-center gap-3 px-4 py-3 cursor-pointer" style={{ backgroundColor: 'hsl(var(--muted))' }} onClick={() => toggleExpand(group.id)}>
                  {expanded.has(group.id) ? <ChevronDown size={15} /> : <ChevronRight size={15} />}
                  <div className="flex-1 min-w-0">
                    <p className="font-semibold text-sm truncate" style={{ color: 'hsl(var(--foreground))' }}>{group.name}</p>
                    <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('menuManagement.forItem', 'for: {{item}}', { item: group.item_name ?? '—' })}</p>
                  </div>
                  <span className="badge badge-neutral capitalize">{group.type === 'radio' ? t('menuManagement.radio', 'radio') : t('menuManagement.checkbox', 'checkbox')}</span>
                  {group.is_required && <span className="badge badge-danger">{t('menuManagement.required', 'Required')}</span>}
                  <span className="text-xs px-2" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('menuManagement.optionsCount', '{{count}} opts', { count: group.options.length })}</span>
                  <button className="btn-ghost p-1.5" style={{ color: 'hsl(var(--primary))' }} onClick={e => { e.stopPropagation(); startEditGroup(group); }}><Pencil size={14} /></button>
                  <button className="btn-ghost p-1.5" style={{ color: 'hsl(var(--danger))' }} onClick={e => { e.stopPropagation(); handleDeleteGroup(group.id); }}><Trash2 size={14} /></button>
                </div>
              )}
              {expanded.has(group.id) && editingGroup !== group.id && (
                <div className="px-4 py-3 space-y-2">
                  {group.options.map(opt => (
                    editingOption?.groupId === group.id && editingOption.optId === opt.id ? (
                      <div key={opt.id} className="flex gap-2 py-1">
                        <input className="input-base text-sm flex-1 py-2" value={editOptionForm.name} onChange={e => setEditOptionForm(f => ({ ...f, name: e.target.value }))} autoFocus />
                        <input type="number" className="input-base text-sm w-24 py-2" placeholder={t('menuManagement.priceDeltaPlaceholder', '₹ delta')} value={editOptionForm.priceDelta} onChange={e => setEditOptionForm(f => ({ ...f, priceDelta: e.target.value }))} />
                        <label className="flex items-center gap-1 text-xs cursor-pointer shrink-0"><input type="checkbox" checked={editOptionForm.isDefault} onChange={e => setEditOptionForm(f => ({ ...f, isDefault: e.target.checked }))} /> {t('menuManagement.def', 'Def')}</label>
                        <button className="btn-ghost p-2" style={{ color: 'hsl(var(--success))' }} onClick={handleUpdateOption}><Check size={14} /></button>
                        <button className="btn-ghost p-2" onClick={() => setEditingOption(null)}><X size={14} /></button>
                      </div>
                    ) : (
                      <div key={opt.id} className="flex items-center gap-3 py-2 px-3 rounded-lg" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                        <span className="flex-1 text-sm" style={{ color: 'hsl(var(--foreground))' }}>{opt.name}</span>
                        {opt.is_default && <span className="badge badge-success text-xs">{t('menuManagement.defaultBadge', 'Default')}</span>}
                        <span className="text-xs font-semibold tabular-nums" style={{ color: opt.price_delta > 0 ? 'hsl(var(--success))' : opt.price_delta < 0 ? 'hsl(var(--danger))' : 'hsl(var(--muted-foreground))' }}>
                          {opt.price_delta === 0 ? t('menuManagement.free', 'Free') : (opt.price_delta > 0 ? '+' : '') + `₹${Math.abs(opt.price_delta).toFixed(0)}`}
                        </span>
                        <button className="btn-ghost p-1" onClick={() => startEditOption(group.id, opt)} style={{ color: 'hsl(var(--primary))' }}><Pencil size={12} /></button>
                        <button className="btn-ghost p-1" onClick={() => handleDeleteOption(group.id, opt.id)} style={{ color: 'hsl(var(--danger))' }}><Trash2 size={12} /></button>
                      </div>
                    )
                  ))}
                  {addingOption === group.id ? (
                    <div className="flex gap-2 pt-1">
                      <input className="input-base text-sm flex-1 py-2" placeholder={t('menuManagement.optionNamePlaceholder', 'Option name (e.g. Large)')} value={newOption.name} onChange={e => setNewOption(o => ({ ...o, name: e.target.value }))} onKeyDown={e => e.key === 'Enter' && handleAddOption(group.id)} autoFocus />
                      <input type="number" className="input-base text-sm w-24 py-2" placeholder={t('menuManagement.extraPricePlaceholder', '₹ extra')} value={newOption.priceDelta} onChange={e => setNewOption(o => ({ ...o, priceDelta: e.target.value }))} />
                      <label className="flex items-center gap-1 text-xs cursor-pointer shrink-0"><input type="checkbox" checked={newOption.isDefault} onChange={e => setNewOption(o => ({ ...o, isDefault: e.target.checked }))} /> {t('menuManagement.def', 'Def')}</label>
                      <button className="btn-ghost p-2" style={{ color: 'hsl(var(--success))' }} onClick={() => handleAddOption(group.id)}><Check size={14} /></button>
                      <button className="btn-ghost p-2" onClick={() => { setAddingOption(null); setNewOption({ name: '', priceDelta: '', isDefault: false }); }}><X size={14} /></button>
                    </div>
                  ) : (
                    <button className="text-xs flex items-center gap-1 py-1.5 px-2 rounded-lg w-full" style={{ color: 'hsl(var(--primary))' }} onClick={() => { setAddingOption(group.id); setNewOption({ name: '', priceDelta: '', isDefault: false }); }}>
                      <Plus size={12} /> {t('menuManagement.addOption', 'Add Option')}
                    </button>
                  )}
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
