// src\components\admin\categories\CategoryForm.tsx

'use client';

import { useState, useCallback, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import toast from 'react-hot-toast';
import Select, { StylesConfig, SingleValue } from 'react-select';
import dynamic from 'next/dynamic';
import ImageUpload from '@/components/ui/ImageUpload';
import SchemaEditor from '@/components/ui/SchemaEditor';
import { generateSlug, sanitizeSlug } from '@/lib/slugify';
import { getApiErrorMessage } from '@/lib/utils/apiError';

// RichTextEditor — SSR disabled (uses browser APIs)
const RichTextEditor = dynamic(
  () => import('@/components/admin/text-editor/RichTextEditor'),
  { ssr: false }
);

interface Language {
  code: string;
  name: string;
  name_native: string;
  is_rtl: boolean;
  is_default: boolean;
  is_active: boolean;
}

interface ParentCategory {
  id: string;
  name: string;
  parent_id: string | null;
}

interface Translation {
  language_code: string;
  name: string;
  slug: string;
  description: string | null;
  meta_title: string | null;
  meta_description: string | null;
  alt_text: string | null;
  schema_markup: Record<string, unknown>;
}

interface CategoryData {
  id?: string;
  parent_id: string | null;
  icon: string | null;
  is_active: boolean;
  is_indexable: boolean;
  display_at_home: boolean; // New field
  translations: Translation[];
}

interface CategoryFormProps {
  mode: 'create' | 'edit';
  initialData?: CategoryData | null;
  languages: Language[];
  parentCategories: ParentCategory[];
}

interface SelectOption {
  value: string;
  label: string;
}

const INPUT_STYLE = {
  background: 'var(--color-surface-alt)',
  border: '1px solid var(--color-border)',
  color: 'var(--color-text)',
} as const;

const LABEL_STYLE = { color: 'var(--color-text-secondary)' } as const;
const ERROR_STYLE = { color: 'var(--color-danger)' } as const;

export default function CategoryForm({ 
  mode, 
  initialData, 
  languages,
  parentCategories 
}: CategoryFormProps) {
  const router = useRouter();
  const isEditing = mode === 'edit';

  // Get active languages, default first
  const activeLanguages = useMemo(() => {
    return languages
      .filter(l => l.is_active)
      .sort((a, b) => {
        if (a.is_default) return -1;
        if (b.is_default) return 1;
        return a.name.localeCompare(b.name);
      });
  }, [languages]);

  const isMultiLang = activeLanguages.length > 1;

  // Get default language
  const defaultLanguage = activeLanguages.find(l => l.is_default) || activeLanguages[0];

  // Initialize translations
  const initialTranslations = useMemo(() => {
    if (isEditing && initialData?.translations && initialData.translations.length > 0) {
      return initialData.translations;
    }
    return activeLanguages.map(lang => ({
      language_code: lang.code,
      name: '',
      slug: '',
      description: null,
      meta_title: null,
      meta_description: null,
      alt_text: null,
      schema_markup: {},
    }));
  }, [isEditing, initialData, activeLanguages]);

  // Build react-select options for parent categories
  const parentOptions: SelectOption[] = useMemo(() => {
    return parentCategories.map(cat => ({
      value: cat.id,
      label: cat.name,
    }));
  }, [parentCategories]);

  // Find currently selected option
  const selectedParentOption = useMemo(() => {
    if (!initialData?.parent_id) return null;
    return parentOptions.find(o => o.value === initialData.parent_id) ?? null;
  }, [parentOptions, initialData]);

  // State for active tab
  const [activeTab, setActiveTab] = useState<string>(defaultLanguage?.code || activeLanguages[0]?.code || 'en');

  // Form state
  const [formData, setFormData] = useState({
    parent_id: initialData?.parent_id || null,
    icon: initialData?.icon || null,
    is_active: initialData?.is_active !== undefined ? initialData.is_active : true,
    is_indexable: initialData?.is_indexable !== undefined ? initialData.is_indexable : true,
    display_at_home: initialData?.display_at_home !== undefined ? initialData.display_at_home : false, // New field
    translations: initialTranslations,
  });

  const [selectedParent, setSelectedParent] = useState<SingleValue<SelectOption>>(selectedParentOption);
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<Record<string, Record<string, string>>>({});

  // react-select custom styles using CSS variables
  const selectStyles: StylesConfig<SelectOption, false> = useMemo(() => ({
    control: (base, state) => ({
      ...base,
      background: 'var(--color-surface-alt)',
      border: `1px solid ${state.isFocused ? 'var(--color-cta)' : 'var(--color-border)'}`,
      borderRadius: '0.5rem',
      boxShadow: state.isFocused ? '0 0 0 2px color-mix(in srgb, var(--color-cta) 20%, transparent)' : 'none',
      minHeight: '42px',
      cursor: 'pointer',
      transition: 'all 0.15s',
      '&:hover': { borderColor: 'var(--color-cta)' },
    }),
    valueContainer: (base) => ({ ...base, padding: '2px 12px' }),
    singleValue: (base) => ({ ...base, color: 'var(--color-text)', fontSize: '0.875rem' }),
    placeholder: (base) => ({ ...base, color: 'var(--color-text-tertiary)', fontSize: '0.875rem' }),
    input: (base) => ({ ...base, color: 'var(--color-text)', fontSize: '0.875rem' }),
    menu: (base) => ({
      ...base,
      background: 'var(--color-surface)',
      border: '1px solid var(--color-border)',
      borderRadius: '0.5rem',
      boxShadow: 'var(--shadow-card-md)',
      zIndex: 50,
      overflow: 'hidden',
    }),
    menuList: (base) => ({ ...base, padding: '4px' }),
    option: (base, state) => ({
      ...base,
      background: state.isSelected
        ? 'var(--color-cta)'
        : state.isFocused
        ? 'color-mix(in srgb, var(--color-cta) 10%, transparent)'
        : 'transparent',
      color: state.isSelected ? 'white' : 'var(--color-text)',
      fontSize: '0.875rem',
      borderRadius: '0.375rem',
      cursor: 'pointer',
      padding: '8px 12px',
      '&:active': { background: 'color-mix(in srgb, var(--color-cta) 20%, transparent)' },
    }),
    clearIndicator: (base) => ({
      ...base,
      color: 'var(--color-text-tertiary)',
      cursor: 'pointer',
      padding: '0 6px',
      '&:hover': { color: 'var(--color-danger)' },
    }),
    dropdownIndicator: (base) => ({
      ...base,
      color: 'var(--color-text-tertiary)',
      padding: '0 8px',
      '&:hover': { color: 'var(--color-text)' },
    }),
    indicatorSeparator: (base) => ({ ...base, background: 'var(--color-border)' }),
    noOptionsMessage: (base) => ({ ...base, color: 'var(--color-text-secondary)', fontSize: '0.875rem' }),
  }), []);

  const getTranslation = useCallback((languageCode: string) => {
    return formData.translations.find(t => t.language_code === languageCode);
  }, [formData.translations]);

  const updateTranslation = useCallback((languageCode: string, field: string, value: unknown) => {
    setFormData(prev => {
      const existingIndex = prev.translations.findIndex(t => t.language_code === languageCode);
      const newTranslations = [...prev.translations];
      
      if (existingIndex >= 0) {
        newTranslations[existingIndex] = { 
          ...newTranslations[existingIndex], 
          [field]: value 
        };
      } else {
        newTranslations.push({ 
          language_code: languageCode, 
          name: '',
          slug: '',
          description: null,
          meta_title: null,
          meta_description: null,
          alt_text: null,
          schema_markup: {},
          [field]: value 
        });
      }
      
      return { ...prev, translations: newTranslations };
    });
    
    // Clear error for this field
    if (errors[languageCode]?.[field]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        if (newErrors[languageCode]) {
          delete newErrors[languageCode][field];
          if (Object.keys(newErrors[languageCode]).length === 0) {
            delete newErrors[languageCode];
          }
        }
        return newErrors;
      });
    }
  }, [errors]);

  /**
   * Handle name change:
   * - Always update the name field
   * - In CREATE mode only: auto-generate slug from name using language-aware slugify
   */
  const handleNameChange = useCallback((languageCode: string, value: string) => {
    updateTranslation(languageCode, 'name', value);

    if (!isEditing) {
      updateTranslation(languageCode, 'slug', generateSlug(value));
    }
  }, [isEditing, updateTranslation]);

  /**
   * Handle manual slug change — sanitize input, never auto-overwrite after manual edit.
   */
  const handleSlugChange = useCallback((languageCode: string, value: string) => {
    updateTranslation(languageCode, 'slug', sanitizeSlug(value));
  }, [updateTranslation]);

  const handleTranslationChange = useCallback((languageCode: string, field: string, value: unknown) => {
    updateTranslation(languageCode, field, value);
  }, [updateTranslation]);

  const handleStatusChange = useCallback((field: 'is_active' | 'is_indexable' | 'display_at_home') => {
    setFormData(prev => ({ ...prev, [field]: !prev[field] }));
  }, []);

  const handleParentChange = useCallback((option: SingleValue<SelectOption>) => {
    setSelectedParent(option);
    setFormData(prev => ({ ...prev, parent_id: option?.value ?? null }));
  }, []);

  const handleImageUpload = useCallback((publicId: string) => {
    setFormData(prev => ({ ...prev, icon: publicId }));
  }, []);

  const handleImageRemove = useCallback(() => {
    setFormData(prev => ({ ...prev, icon: null }));
  }, []);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setErrors({});
    setLoading(true);

    // Validate: at least one translation with name and slug
    const hasValidTranslation = formData.translations.some(t => 
      t.name.trim().length > 0 && t.slug.trim().length > 0
    );
    if (!hasValidTranslation) {
      toast.error('At least one translation with name and slug is required');
      setLoading(false);
      return;
    }

    // Validate slugs are unique within same language
    const slugMap = new Map<string, Set<string>>();
    for (const t of formData.translations) {
      if (!slugMap.has(t.language_code)) {
        slugMap.set(t.language_code, new Set());
      }
      if (slugMap.get(t.language_code)!.has(t.slug)) {
        toast.error(`Duplicate slug "${t.slug}" for language ${t.language_code}`);
        setLoading(false);
        return;
      }
      slugMap.get(t.language_code)!.add(t.slug);
    }

    try {
      const url = isEditing ? `/api/categories/${initialData?.id}` : '/api/categories';
      const method = isEditing ? 'PUT' : 'POST';

      const payload = {
        parent_id: formData.parent_id,
        icon: formData.icon,
        is_active: formData.is_active,
        is_indexable: formData.is_indexable,
        display_at_home: formData.display_at_home, // New field
        translations: formData.translations.filter(t => t.name.trim().length > 0),
      };

      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      const data = await res.json();

      if (!res.ok || !data.success) {
        if (data.errors) {
          const fieldErrors: Record<string, Record<string, string>> = {};
          if (Array.isArray(data.errors)) {
            data.errors.forEach((err: { path: string[]; message: string }) => {
              if (err.path) {
                const match = err.path.join('.');
                if (match.includes('translations')) {
                  const langMatch = match.match(/translations\[(\d+)\]/);
                  if (langMatch) {
                    const idx = parseInt(langMatch[1]);
                    const translation = formData.translations[idx];
                    if (translation) {
                      const field = err.path[err.path.length - 1];
                      if (!fieldErrors[translation.language_code]) {
                        fieldErrors[translation.language_code] = {};
                      }
                      fieldErrors[translation.language_code][field] = err.message;
                    }
                  }
                }
              }
            });
          }
          setErrors(fieldErrors);
          toast.error('Please fix the validation errors');
        } else {
          toast.error(getApiErrorMessage(data, 'Failed to save category'));
        }
        return;
      }

      toast.success(data.message || (isEditing ? 'Category updated successfully' : 'Category created successfully'));
      router.push('/admin/dashboard/categories');
      router.refresh();
    } catch (err) {
      console.error('[CategoryForm]', err);
      toast.error('Network error — please try again');
    } finally {
      setLoading(false);
    }
  }

  // If no languages, show message
  if (activeLanguages.length === 0) {
    return (
      <div className="p-6 rounded-lg text-center" style={{
        background: 'var(--color-surface)',
        border: '1px solid var(--color-border)',
        borderRadius: 'var(--radius-card)',
      }}>
        <p style={{ color: 'var(--color-text-secondary)' }}>
          No active languages found. Please add languages first.
        </p>
      </div>
    );
  }

  return (
    <div className="p-6 md:p-8" style={{
      background: 'var(--color-surface)',
      border: '1px solid var(--color-border)',
      borderRadius: 'var(--radius-card)',
      boxShadow: 'var(--shadow-card-md)',
      maxWidth: '1000px',
      width: '100%',
    }}>
      <form onSubmit={handleSubmit}>
        <div className="space-y-6">

          {/* Basic Info */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                Parent Category
              </label>
              <Select<SelectOption, false>
                instanceId="parent-category-select"
                options={parentOptions}
                value={selectedParent}
                onChange={handleParentChange}
                placeholder="Search or select parent…"
                isClearable
                isSearchable
                styles={selectStyles}
                noOptionsMessage={() => 'No categories found'}
              />
              <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
                Select a parent category or leave empty for root level
              </p>
            </div>

            <ImageUpload
              value={formData.icon}
              onUpload={handleImageUpload}
              onRemove={handleImageRemove}
              label="Category Image / Icon"
              folder="categories"
              maxSize={2}
              aspectRatio={1}
            />
          </div>

          {/* Status Toggles */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                Active Status
              </label>
              <button
                type="button"
                onClick={() => handleStatusChange('is_active')}
                className="px-4 py-2 rounded-lg text-sm font-medium transition-all"
                style={{
                  background: formData.is_active ? 'var(--color-success)' : 'var(--color-surface-alt)',
                  border: formData.is_active ? 'none' : '1px solid var(--color-border)',
                  color: formData.is_active ? 'white' : 'var(--color-text-secondary)',
                }}
              >
                {formData.is_active ? '✅ Active' : '❌ Inactive'}
              </button>
            </div>

            <div>
              <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                Indexable (SEO)
              </label>
              <button
                type="button"
                onClick={() => handleStatusChange('is_indexable')}
                className="px-4 py-2 rounded-lg text-sm font-medium transition-all"
                style={{
                  background: formData.is_indexable ? 'var(--color-info)' : 'var(--color-surface-alt)',
                  border: formData.is_indexable ? 'none' : '1px solid var(--color-border)',
                  color: formData.is_indexable ? 'white' : 'var(--color-text-secondary)',
                }}
              >
                {formData.is_indexable ? '✅ Indexable' : '🚫 No Index'}
              </button>
            </div>

            <div>
              <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                Display at Home
              </label>
              <button
                type="button"
                onClick={() => handleStatusChange('display_at_home')}
                className="px-4 py-2 rounded-lg text-sm font-medium transition-all"
                style={{
                  background: formData.display_at_home ? 'var(--color-cta)' : 'var(--color-surface-alt)',
                  border: formData.display_at_home ? 'none' : '1px solid var(--color-border)',
                  color: formData.display_at_home ? 'white' : 'var(--color-text-secondary)',
                }}
              >
                {formData.display_at_home ? '🏠 Show on Home' : '🏠 Hide from Home'}
              </button>
            </div>
          </div>

          {/* Language Tabs */}
          <div>
            {isMultiLang && (
              <div>
                <label className="block text-sm font-medium mb-3" style={LABEL_STYLE}>
                  Translations <span className="text-red-500">*</span>
                </label>

                <div className="flex flex-wrap gap-1 border-b" style={{ borderColor: 'var(--color-border)' }}>
                  {activeLanguages.map((lang) => {
                    const translation = getTranslation(lang.code);
                    const hasError = errors[lang.code]?.name || errors[lang.code]?.slug;
                    const hasTranslation = translation?.name && translation.name.trim().length > 0;

                    return (
                      <button
                        key={lang.code}
                        type="button"
                        onClick={() => setActiveTab(lang.code)}
                        className={`px-4 py-2 text-sm font-medium transition-all whitespace-nowrap border-b-2 ${
                          activeTab === lang.code ? 'border-cta text-cta' : 'border-transparent text-text-secondary hover:text-text'
                        } ${hasError ? 'border-red-500' : ''}`}
                        style={{
                          color: activeTab === lang.code ? 'var(--color-cta)' : 'var(--color-text-secondary)',
                          borderColor: activeTab === lang.code ? 'var(--color-cta)' : 'transparent',
                          direction: lang.is_rtl ? 'rtl' : 'ltr',
                        }}
                      >
                        <span className="flex items-center gap-1">
                          {lang.is_default ? '⭐ ' : ''}
                          {lang.name_native}
                          <span className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
                            ({lang.code})
                          </span>
                          {hasTranslation && <span className="text-xs text-green-500">✅</span>}
                          {hasError && <span className="text-red-500">*</span>}
                        </span>
                      </button>
                    );
                  })}
                </div>
              </div>
            )}

            {/* Tab Content */}
            <div className="mt-4">
              {activeLanguages.map((lang) => {
                const isActive = activeTab === lang.code;
                const translation = getTranslation(lang.code);
                const isRTL = lang.is_rtl;
                const errorsForLang = errors[lang.code] || {};

                return (
                  <div key={lang.code} className={isActive ? 'block' : 'hidden'}>
                    <div className="space-y-4">

                      {/* Name */}
                      <div>
                        <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                          Name <span className="text-red-500">*</span>
                        </label>
                        <input
                          type="text"
                          value={translation?.name || ''}
                          onChange={(e) => handleNameChange(lang.code, e.target.value)}
                          placeholder={isMultiLang ? `Enter name in ${lang.name}` : 'Enter category name'}
                          className={`w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 ${errorsForLang.name ? 'border-red-500' : ''}`}
                          style={{ ...INPUT_STYLE, direction: isRTL ? 'rtl' : 'ltr' }}
                        />
                        {errorsForLang.name && (
                          <p className="text-xs mt-1" style={ERROR_STYLE}>{errorsForLang.name}</p>
                        )}
                      </div>

                      {/* Slug */}
                      <div>
                        <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                          Slug <span className="text-red-500">*</span>
                          {!isEditing && (
                            <span className="ml-2 text-xs font-normal" style={{ color: 'var(--color-text-tertiary)' }}>
                              (auto-generated from name)
                            </span>
                          )}
                        </label>
                        <input
                          type="text"
                          value={translation?.slug || ''}
                          onChange={(e) => handleSlugChange(lang.code, e.target.value)}
                          placeholder={isMultiLang ? `Enter slug in ${lang.name}` : 'Enter slug'}
                          className={`w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 ${errorsForLang.slug ? 'border-red-500' : ''}`}
                          style={{ ...INPUT_STYLE, direction: isRTL ? 'rtl' : 'ltr' }}
                        />
                        {errorsForLang.slug && (
                          <p className="text-xs mt-1" style={ERROR_STYLE}>{errorsForLang.slug}</p>
                        )}
                        <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
                          URL-friendly name (e.g., electronics, clothing)
                        </p>
                      </div>

                      {/* Description — RichTextEditor */}
                      <div>
                        <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                          Description
                        </label>
                        <RichTextEditor
                          content={translation?.description ?? ''}
                          onChange={(html) => handleTranslationChange(lang.code, 'description', html)}
                          isRTL={isRTL}
                        />
                      </div>

                      {/* Alt Text */}
                      <div>
                        <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                          Alt Text (Image SEO)
                        </label>
                        <input
                          type="text"
                          value={translation?.alt_text || ''}
                          onChange={(e) => handleTranslationChange(lang.code, 'alt_text', e.target.value)}
                          placeholder={isMultiLang ? `Enter alt text for image in ${lang.name}` : 'Enter alt text for image'}
                          maxLength={255}
                          className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20"
                          style={{ ...INPUT_STYLE, direction: isRTL ? 'rtl' : 'ltr' }}
                        />
                        <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
                          {translation?.alt_text?.length || 0}/255 characters — describes image for accessibility & SEO
                        </p>
                      </div>

                      {/* Meta Title */}
                      <div>
                        <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                          Meta Title (SEO)
                        </label>
                        <input
                          type="text"
                          value={translation?.meta_title || ''}
                          onChange={(e) => handleTranslationChange(lang.code, 'meta_title', e.target.value)}
                          placeholder={isMultiLang ? `Enter meta title in ${lang.name}` : 'Enter meta title'}
                          maxLength={160}
                          className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20"
                          style={{ ...INPUT_STYLE, direction: isRTL ? 'rtl' : 'ltr' }}
                        />
                        <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
                          {translation?.meta_title?.length || 0}/160 characters
                        </p>
                      </div>

                      {/* Meta Description */}
                      <div>
                        <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                          Meta Description (SEO)
                        </label>
                        <textarea
                          rows={2}
                          value={translation?.meta_description || ''}
                          onChange={(e) => handleTranslationChange(lang.code, 'meta_description', e.target.value)}
                          placeholder={isMultiLang ? `Enter meta description in ${lang.name}` : 'Enter meta description'}
                          maxLength={320}
                          className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 resize-none"
                          style={{ ...INPUT_STYLE, direction: isRTL ? 'rtl' : 'ltr' }}
                        />
                        <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
                          {translation?.meta_description?.length || 0}/320 characters
                        </p>
                      </div>

                      {/* Schema Editor */}
                      <SchemaEditor
                        value={translation?.schema_markup || {}}
                        onChange={(schemas) => handleTranslationChange(lang.code, 'schema_markup', schemas)}
                        label={isMultiLang ? `Schema Markup (${lang.name})` : 'Schema Markup'}
                        isRTL={isRTL}
                      />
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Form Actions */}
          <div className="flex gap-3 pt-4 border-t" style={{ borderColor: 'var(--color-border)' }}>
            <button
              type="submit"
              disabled={loading}
              className="px-6 py-2.5 rounded-lg text-sm font-medium transition-all disabled:opacity-50 hover:opacity-90"
              style={{ background: 'var(--color-cta)', color: 'white' }}
            >
              {loading ? (
                <span className="flex items-center gap-2">
                  <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none"/>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"/>
                  </svg>
                  Saving...
                </span>
              ) : (isEditing ? 'Update Category' : 'Create Category')}
            </button>
            <button
              type="button"
              onClick={() => router.back()}
              className="px-6 py-2.5 rounded-lg text-sm font-medium transition-all hover:opacity-80"
              style={{
                background: 'var(--color-surface-alt)',
                color: 'var(--color-text)',
                border: '1px solid var(--color-border)',
              }}
            >
              Cancel
            </button>
          </div>

        </div>
      </form>
    </div>
  );
}