'use client';

import { useState } from 'react';
import Link from 'next/link';
import { ArrowLeft, Save, Upload, ToggleLeft, ToggleRight, DollarSign, Tag, Image as ImageIcon, AlertCircle } from 'lucide-react';
import { usePageHeader } from '@client/contexts/PageHeaderContext';

import { useLanguage } from '@client/contexts/LanguageContext';

const categories = ['Starters', 'Mains', 'Sides', 'Desserts', 'Drinks', 'Specials'];
const dietaryOptions = ['Vegetarian', 'Vegan', 'Gluten-Free', 'Dairy-Free', 'Nut-Free', 'Halal', 'Kosher', 'Spicy'];

interface FormErrors {
  name?: string;
  price?: string;
  category?: string;
}

function FieldError({ message }: { message?: string }) {
  if (!message) return null;
  return (
    <p className="flex items-center gap-1 text-xs mt-1.5 font-medium" style={{ color: 'hsl(0, 84%, 44%)' }}>
      <AlertCircle size={12} />
      {message}
    </p>
  );
}

export default function MenuItemFormPage({ params }: { params: { id?: string } }) {
  const { t } = useLanguage();
  const isEdit = params?.id && params.id !== 'new';
  usePageHeader(isEdit ? t('menuManagement.editMenuItem', 'Edit Menu Item') : t('menuManagement.addMenuItem', 'Add Menu Item'), t('menuManagement.manageMenuItemDetails', 'Manage menu item details, pricing, and availability'));
  const [form, setForm] = useState({
    name: isEdit ? 'Grilled Salmon' : '',
    description: isEdit ? 'Atlantic salmon with lemon butter sauce, seasonal vegetables' : '',
    price: isEdit ? '28.50' : '',
    category: isEdit ? 'Mains' : '',
    sortOrder: isEdit ? '1' : '',
    available: true,
    dietary: isEdit ? ['GF'] : [] as string[],
  });
  const [errors, setErrors] = useState<FormErrors>({});
  const [touched, setTouched] = useState<Record<string, boolean>>({});
  const [saving, setSaving] = useState(false);

  const validators: Record<string, (val: string) => string | undefined> = {
    name: (v) => !v.trim() ? t('menuManagement.itemNameIsRequired', 'Item name is required') : v.trim().length < 2 ? t('menuManagement.nameMinLength', 'Name must be at least 2 characters') : undefined,
    price: (v) => !v ? t('menuManagement.priceIsRequired', 'Price is required') : isNaN(parseFloat(v)) || parseFloat(v) <= 0 ? t('menuManagement.priceGreaterThanZero', 'Please enter a valid price greater than 0') : undefined,
    category: (v) => !v ? t('menuManagement.selectCategory', 'Please select a category') : undefined,
  };

  const handleBlur = (field: string) => {
    setTouched(prev => ({ ...prev, [field]: true }));
    setErrors(prev => ({ ...prev, [field]: validators[field]?.(form[field as keyof typeof form] as string) }));
  };

  const handleChange = (field: string, value: string) => {
    setForm(f => ({ ...f, [field]: value }));
    if (touched[field]) setErrors(prev => ({ ...prev, [field]: validators[field]?.(value) }));
  };

  const validate = (): boolean => {
    const newErrors: FormErrors = {};
    const newTouched: Record<string, boolean> = {};
    ['name', 'price', 'category'].forEach(field => {
      newTouched[field] = true;
      const err = validators[field]?.(form[field as keyof typeof form] as string);
      if (err) newErrors[field as keyof FormErrors] = err;
    });
    setErrors(newErrors);
    setTouched(prev => ({ ...prev, ...newTouched }));
    return Object.keys(newErrors).length === 0;
  };

  const handleSave = () => {
    if (!validate()) return;
    setSaving(true);
    setTimeout(() => {
      setSaving(false);
    }, 1200);
  };

  const toggleDietary = (tag: string) => {
    setForm(f => ({
      ...f,
      dietary: f.dietary.includes(tag) ? f.dietary.filter(d => d !== tag) : [...f.dietary, tag],
    }));
  };

  const inputStyle = (field: string) => ({
    borderColor: touched[field] && errors[field as keyof FormErrors] ? 'hsl(0, 84%, 44%)' : undefined,
    boxShadow: touched[field] && errors[field as keyof FormErrors] ? '0 0 0 2px hsl(0, 84%, 44%, 0.15)' : undefined,
  });

  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.editMenuItem', 'Edit Menu Item') : t('menuManagement.addNewItem', 'Add New Item')}</h2>
        <div className="ml-auto flex gap-2">
          <Link href="/menu-management" className="btn-secondary">{t('common.cancel', 'Cancel')}</Link>
          <button className="btn-primary inline-flex items-center gap-2" onClick={handleSave} disabled={saving}>
            {saving ? (
              <>
                <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                {t('common.saving', 'Saving...')}
              </>
            ) : (
              <><Save size={15} /> {isEdit ? t('common.saveChanges', 'Save Changes') : t('menuManagement.addItem', 'Add Item')}</>
            )}
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
        <div className="lg:col-span-2 space-y-5">
          {/* Basic info */}
          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('menuManagement.itemDetails', 'Item Details')}</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.itemNameLabel', 'Item Name *')}</label>
                <input
                  className="input-base"
                  placeholder={t('menuManagement.itemNamePlaceholder', 'e.g. Grilled Salmon')}
                  value={form.name}
                  onChange={e => handleChange('name', e.target.value)}
                  onBlur={() => handleBlur('name')}
                  style={inputStyle('name')}
                />
                <FieldError message={touched.name ? errors.name : undefined} />
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('menuManagement.description', 'Description')}</label>
                <textarea className="input-base resize-none" rows={3} placeholder={t('menuManagement.descriptionPlaceholder', 'Describe the dish — ingredients, cooking style, flavors...')} value={form.description} onChange={e => setForm(f => ({ ...f, description: e.target.value }))} />
              </div>
              <div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('menuManagement.priceLabel', 'Price *')}</label>
                  <div className="relative">
                    <DollarSign size={14} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: touched.price && errors.price ? 'hsl(0, 84%, 44%)' : 'hsl(var(--muted-foreground))' }} />
                    <input
                      type="number"
                      step="0.01"
                      className="input-base pl-9"
                      placeholder="0.00"
                      value={form.price}
                      onChange={e => handleChange('price', e.target.value)}
                      onBlur={() => handleBlur('price')}
                      style={inputStyle('price')}
                    />
                  </div>
                  <FieldError message={touched.price ? errors.price : undefined} />
                </div>
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('menuManagement.categoryLabel', 'Category *')}</label>
                  <div className="relative">
                    <Tag size={14} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: touched.category && errors.category ? 'hsl(0, 84%, 44%)' : 'hsl(var(--muted-foreground))' }} />
                    <select
                      className="input-base pl-9"
                      value={form.category}
                      onChange={e => handleChange('category', e.target.value)}
                      onBlur={() => handleBlur('category')}
                      style={inputStyle('category')}
                    >
                      <option value="">{t('menuManagement.selectCategoryPlaceholder', 'Select category')}</option>
                      {categories.map(c => <option key={c}>{c}</option>)}
                    </select>
                  </div>
                  <FieldError message={touched.category ? errors.category : undefined} />
                </div>
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('menuManagement.sortOrder', 'Sort Order')}</label>
                  <input type="number" className="input-base" placeholder="1" value={form.sortOrder} onChange={e => setForm(f => ({ ...f, sortOrder: e.target.value }))} />
                </div>
              </div>
            </div>
          </div>

          {/* Dietary tags */}
          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('menuManagement.dietaryTags', 'Dietary Tags')}</h3>
            <div className="flex flex-wrap gap-2">
              {dietaryOptions.map(tag => {
                const selected = form.dietary.includes(tag);
                return (
                  <button
                    key={tag}
                    type="button"
                    onClick={() => toggleDietary(tag)}
                    className="px-3 py-1.5 rounded-full text-sm font-medium border-2 transition-all"
                    style={{
                      borderColor: selected ? 'hsl(var(--primary))' : 'hsl(var(--border))',
                      backgroundColor: selected ? 'hsl(var(--primary-light))' : 'hsl(var(--surface))',
                      color: selected ? 'hsl(var(--primary))' : 'hsl(var(--foreground-secondary))',
                    }}
                  >
                    {tag}
                  </button>
                );
              })}
            </div>
          </div>

          {/* Image upload */}
          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('menuManagement.itemImage', 'Item Image')}</h3>
            <div className="border-2 border-dashed rounded-xl p-6 text-center" style={{ borderColor: 'hsl(var(--border))', backgroundColor: 'hsl(var(--muted))' }}>
              <ImageIcon size={28} className="mx-auto mb-2" style={{ color: 'hsl(var(--muted-foreground))' }} />
              <p className="text-sm font-medium mb-1" style={{ color: 'hsl(var(--foreground))' }}>{t('menuManagement.uploadItemPhoto', 'Upload item photo')}</p>
              <p className="text-xs mb-3" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('menuManagement.uploadLimits', 'JPG, PNG — max 5MB. Recommended: 800×600px')}</p>
              <button className="btn-secondary text-xs py-1.5"><Upload size={13} /> {t('menuManagement.chooseImage', 'Choose Image')}</button>
            </div>
          </div>
        </div>

        {/* Right: Availability */}
        <div className="space-y-5">
          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('menuManagement.availability', 'Availability')}</h3>
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('menuManagement.availableOnMenu', 'Available on Menu')}</p>
                <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('menuManagement.availableHelpText', 'Customers can order this item')}</p>
              </div>
              <button onClick={() => setForm(f => ({ ...f, available: !f.available }))}>
                {form.available ? <ToggleRight size={28} style={{ color: 'hsl(var(--success))' }} /> : <ToggleLeft size={28} style={{ color: 'hsl(var(--muted-foreground))' }} />}
              </button>
            </div>
          </div>

          {form.name && (
            <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))' }}>
                <p className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{form.name}</p>
                {form.price && <p className="font-bold text-base mt-1" style={{ color: 'hsl(var(--primary))' }}>${parseFloat(form.price || '0').toFixed(2)}</p>}
                {form.description && <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{form.description}</p>}
                {form.dietary.length > 0 && (
                  <div className="flex flex-wrap gap-1 mt-2">
                    {form.dietary.map(d => <span key={d} className="badge badge-success text-xs">{d}</span>)}
                  </div>
                )}
              </div>
            </div>
          )}
        </div>
      </div>
    </>
  );
}
