'use client';

import { useState } from 'react';
import Link from 'next/link';
import { ArrowLeft, Save, Plus, Trash2, ToggleLeft, ToggleRight, DollarSign } from 'lucide-react';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';

interface ModifierOption {
  id: string;
  label: string;
  price: number;
}

export default function ModifierFormPage({ params }: { params: { id?: string } }) {
  const { t } = useLanguage();
  const isEdit = params?.id && params.id !== 'new';
  usePageHeader(isEdit ? t('menuManagement.editModifierGroup', "Edit Modifier Group") : t('menuManagement.addModifierGroup', "Add Modifier Group"), t('menuManagement.modifierGroupDescription', "Configure modifier options for menu items"));
  
  const [form, setForm] = useState({
    name: isEdit ? 'Cooking Preference' : '',
    type: isEdit ? 'single' : 'single',
    required: isEdit ? true : false,
    minSelect: '1',
    maxSelect: '1',
  });
  const [options, setOptions] = useState<ModifierOption[]>(
    isEdit
      ? [
          { id: '1', label: 'Rare', price: 0 },
          { id: '2', label: 'Medium', price: 0 },
          { id: '3', label: 'Well Done', price: 0 },
        ]
      : [{ id: '1', label: '', price: 0 }]
  );

  const addOption = () => {
    setOptions(o => [...o, { id: String(Date.now()), label: '', price: 0 }]);
  };

  const removeOption = (id: string) => {
    setOptions(o => o.filter(opt => opt.id !== id));
  };

  const updateOption = (id: string, field: keyof ModifierOption, value: string | number) => {
    setOptions(o => o.map(opt => opt.id === id ? { ...opt, [field]: value } : opt));
  };

  return (
    <>
      <div className="flex items-center gap-3 mb-6">
        <Link href="/menu-management" className="btn-ghost p-1.5"><ArrowLeft size={16} /></Link>
        <h2 className="font-bold text-lg" style={{ color: 'hsl(var(--foreground))' }}>{isEdit ? t('menuManagement.editModifierGroup', 'Edit Modifier Group') : t('menuManagement.addModifierGroup', 'Add Modifier Group')}</h2>
        <div className="ml-auto flex gap-2">
          <Link href="/menu-management" className="btn-secondary">{t('common.cancel', 'Cancel')}</Link>
          <button className="btn-primary"><Save size={15} /> {isEdit ? t('menuManagement.saveChanges', 'Save Changes') : t('menuManagement.addModifier', 'Add Modifier')}</button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
        <div className="lg:col-span-2 space-y-5">
          {/* Group settings */}
          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('menuManagement.modifierGroupSettings', 'Modifier Group Settings')}</h3>
            <div className="space-y-4">
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('menuManagement.groupName', 'Group Name')} *</label>
                <input className="input-base" placeholder={t('menuManagement.groupNamePlaceholder', "e.g. Cooking Preference, Add-ons, Sauce Choice")} value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} required />
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('menuManagement.selectionType', 'Selection Type')}</label>
                <div className="grid grid-cols-2 gap-3">
                  {[
                    { value: 'single', label: t('menuManagement.singleSelect', 'Single Select'), desc: t('menuManagement.singleSelectDesc', 'Customer picks one option') },
                    { value: 'multi', label: t('menuManagement.multiSelect', 'Multi Select'), desc: t('menuManagement.multiSelectDesc', 'Customer picks multiple options') },
                  ].map(opt => (
                    <button
                      key={opt.value}
                      type="button"
                      onClick={() => setForm(f => ({ ...f, type: opt.value }))}
                      className="text-left p-3 rounded-xl border-2 transition-all"
                      style={{
                        borderColor: form.type === opt.value ? 'hsl(var(--primary))' : 'hsl(var(--border))',
                        backgroundColor: form.type === opt.value ? 'hsl(var(--primary-light))' : 'hsl(var(--surface))',
                      }}
                    >
                      <p className="font-semibold text-sm" style={{ color: form.type === opt.value ? 'hsl(var(--primary))' : 'hsl(var(--foreground))' }}>{opt.label}</p>
                      <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{opt.desc}</p>
                    </button>
                  ))}
                </div>
              </div>
              {form.type === 'multi' && (
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('menuManagement.minSelections', 'Min Selections')}</label>
                    <input type="number" min="0" className="input-base" value={form.minSelect} onChange={e => setForm(f => ({ ...f, minSelect: e.target.value }))} />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('menuManagement.maxSelections', 'Max Selections')}</label>
                    <input type="number" min="1" className="input-base" value={form.maxSelect} onChange={e => setForm(f => ({ ...f, maxSelect: e.target.value }))} />
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Options */}
          <div className="card p-5">
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('menuManagement.optionsCount', 'Options ({{count}})', { count: options.length })}</h3>
              <button className="btn-secondary text-xs py-1.5" onClick={addOption}><Plus size={13} /> {t('menuManagement.addOption', 'Add Option')}</button>
            </div>
            <div className="space-y-3">
              {options.map((opt, idx) => (
                <div key={opt.id} className="flex items-center gap-3">
                  <span className="text-xs font-semibold w-5 text-center" style={{ color: 'hsl(var(--muted-foreground))' }}>{idx + 1}</span>
                  <input
                    className="input-base flex-1"
                    placeholder={t('menuManagement.optionNamePlaceholder', "Option name (e.g. Rare, Extra Cheese)")}
                    value={opt.label}
                    onChange={e => updateOption(opt.id, 'label', e.target.value)}
                  />
                  <div className="relative w-28">
                    <DollarSign size={13} className="absolute left-2.5 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
                    <input
                      type="number"
                      step="0.50"
                      min="0"
                      className="input-base pl-7 text-sm"
                      placeholder="0.00"
                      value={opt.price}
                      onChange={e => updateOption(opt.id, 'price', parseFloat(e.target.value) || 0)}
                    />
                  </div>
                  <button
                    className="btn-ghost p-1.5"
                    style={{ color: 'hsl(var(--danger))' }}
                    onClick={() => removeOption(opt.id)}
                    disabled={options.length === 1}
                  >
                    <Trash2 size={14} />
                  </button>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Right: Required toggle */}
        <div className="space-y-5">
          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('menuManagement.required', 'Required')}</h3>
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('menuManagement.requiredSelection', 'Required Selection')}</p>
                <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('menuManagement.requiredSelectionDesc', 'Customer must choose before adding to cart')}</p>
              </div>
              <button onClick={() => setForm(f => ({ ...f, required: !f.required }))}>
                {form.required ? <ToggleRight size={28} style={{ color: 'hsl(var(--success))' }} /> : <ToggleLeft size={28} style={{ color: 'hsl(var(--muted-foreground))' }} />}
              </button>
            </div>
          </div>

          {form.name && options.some(o => o.label) && (
            <div className="card p-5">
              <h3 className="font-semibold mb-3" style={{ color: 'hsl(var(--foreground))' }}>{t('menuManagement.preview', 'Preview')}</h3>
              <div className="p-3 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                <div className="flex items-center gap-2 mb-2">
                  <p className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{form.name}</p>
                  {form.required && <span className="badge badge-danger text-xs">{t('menuManagement.requiredLabel', 'Required')}</span>}
                  <span className={`badge text-xs ${form.type === 'single' ? 'badge-info' : 'badge-primary'}`}>{form.type === 'single' ? t('menuManagement.single', 'Single') : t('menuManagement.multi', 'Multi')}</span>
                </div>
                <div className="flex flex-wrap gap-1.5">
                  {options.filter(o => o.label).map(o => (
                    <span key={o.id} className="text-xs px-2 py-1 rounded-lg" style={{ backgroundColor: 'hsl(var(--surface))', color: 'hsl(var(--foreground))' }}>
                      {o.label}{o.price > 0 ? ` +$${o.price.toFixed(2)}` : ''}
                    </span>
                  ))}
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </>
  );
}
