/**
 * BulkPanel Component
 * 
 * Hybrid mode: Slide-in panel (desktop) OR Full-screen view (mobile/user preference)
 */

import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { AlertTriangle } from 'lucide-react';
import { useBulkPreview, useBulkUpdate } from '../../hooks/useBulkOperations';
import { useLicenseInfo, useCheckLimit } from '../../hooks/useLicense';
import toast from 'react-hot-toast';
import ProBadge from '../ui/ProBadge';
import ImageAssigner from './ImageAssigner';
import LoadingSpinner from '../ui/LoadingSpinner';
import type { BulkOperationType, BulkFieldType } from '../../types/bulk';
import type { PreviewData } from '../../types/preview';

interface Props {
  variationIds: number[];
  mode: 'slide-in' | 'full-screen';
  onPreview: (preview: PreviewData) => void;
  onClearPreview: () => void;
}

type TabType = 'price' | 'stock' | 'sku' | 'image';

// Price subsections
type PriceSubsection = 'regular' | 'sale' | 'rounding';

export default function BulkPanel({ variationIds, mode, onPreview, onClearPreview }: Props) {
  const { t } = useTranslation();
  const [activeTab, setActiveTab] = useState<TabType>('price');
  const [priceSubsection, setPriceSubsection] = useState<PriceSubsection>('regular');
  const [operationType, setOperationType] = useState<BulkOperationType>('percentage');
  const [value, setValue] = useState('');
  const [rounding, setRounding] = useState<number>(1);
  const [saleDateFrom, setSaleDateFrom] = useState<string>('');
  const [saleDateTo, setSaleDateTo] = useState<string>('');
  
  const previewMutation = useBulkPreview();
  const updateMutation = useBulkUpdate();
  const { data: licenseInfo, isLoading: licenseLoading } = useLicenseInfo();
  const limitCheck = useCheckLimit('bulk_operations', variationIds.length);
  
  // Show warning if limit exceeded (only if license info loaded)
  const showLimitWarning = !licenseLoading && limitCheck.exceeded;

  // Tab váltáskor törlődik a preview
  const handleTabChange = (tab: TabType) => {
    setActiveTab(tab);
    setPriceSubsection('regular'); // Reset to regular price
    setOperationType(getOperationsForTab(tab, 'regular')[0]);
    setValue('');
    setRounding(1);
    setSaleDateFrom('');
    setSaleDateTo('');
    onClearPreview(); // Preview törlése
  };

  // Művelet típus váltáskor törlődik a preview
  const handleOperationChange = (op: BulkOperationType) => {
    setOperationType(op);
    onClearPreview();
  };

  // Handle preview
  const handlePreview = async () => {
    // ✅ SECURITY FIX 9: Validate input based on operation type
    if (activeTab === 'image') {
      if (value === null || value === undefined || value === '') {
        toast.error(t('bulk.enter_value'));
        return;
      }
    } else if (!value && priceSubsection !== 'rounding' && operationType !== 'remove') {
      toast.error(t('bulk.enter_value'));
      return;
    }
    
    // ✅ SECURITY FIX 10: Frontend validation for price/stock values
    if (activeTab === 'price' && value && operationType !== 'remove') {
      const numValue = parseFloat(value);
      
      // Check if valid number
      if (isNaN(numValue)) {
        toast.error('Invalid price value. Must be a number.');
        return;
      }
      
      // Check percentage range (-100% to +1000%)
      if (operationType === 'percentage') {
        if (numValue < -100 || numValue > 1000) {
          toast.error('Percentage must be between -100% and +1000%');
          return;
        }
      }
      
      // Check fixed/set value range (0 to 10,000,000)
      if (operationType === 'fixed' || operationType === 'set') {
        if (numValue < -10000000 || numValue > 10000000) {
          toast.error('Price value must be between -10,000,000 and +10,000,000');
          return;
        }
      }
    }
    
    // ✅ SECURITY FIX 11: Frontend validation for stock values
    if (activeTab === 'stock' && value) {
      const numValue = parseInt(value);
      
      // Check if valid integer
      if (isNaN(numValue)) {
        toast.error('Invalid stock value. Must be a number.');
        return;
      }
      
      // Check stock range (-10,000 to +100,000)
      if (numValue < -10000 || numValue > 100000) {
        toast.error('Stock value must be between -10,000 and +100,000');
        return;
      }
    }
    
    // ✅ SECURITY FIX 12: Validate sale dates
    if (priceSubsection === 'sale' && operationType !== 'remove') {
      if (saleDateFrom && saleDateTo) {
        const dateFrom = new Date(saleDateFrom);
        const dateTo = new Date(saleDateTo);
        
        if (dateFrom > dateTo) {
          toast.error('Sale start date cannot be after end date');
          return;
        }
      }
    }

    const field = getFieldForTab(activeTab, priceSubsection);
    // Image esetén az operation mindig 'set'
    const operation = activeTab === 'image' ? 'set' : operationType;
    
    try {
      const bulkOperation: any = {
        field,
        operation: operation,
        value: value || '0',
      };
      
      // Add rounding if applicable
      if (activeTab === 'price' && rounding > 1) {
        bulkOperation.rounding = rounding;
      }
      
      // Add sale dates if sale price operation
      if (priceSubsection === 'sale' && operationType !== 'remove') {
        if (saleDateFrom) bulkOperation.date_from = saleDateFrom;
        if (saleDateTo) bulkOperation.date_to = saleDateTo;
      }
      
      const result = await previewMutation.mutateAsync({
        variation_ids: variationIds,
        operations: [bulkOperation],
      });
      
      // Transform preview data to PreviewData format
      const previewData: PreviewData = {};
      result.data.preview.forEach((item: any) => {
        previewData[item.id] = [];
        
        // Add changes based on field
        if (field === 'regular_price' || field === 'price') {
          previewData[item.id].push({
            field: 'price',
            old_value: item.current_price || item.old_price,
            new_value: item.new_price,
          });
        }
        if (field === 'sale_price' && item.new_sale_price) {
          previewData[item.id].push({
            field: 'sale_price',
            old_value: item.current_sale_price || item.old_sale_price,
            new_value: item.new_sale_price,
          });
          
          // Add sale date fields if present
          if (item.sale_date_from || item.sale_date_to) {
            previewData[item.id].push({
              field: 'sale_dates',
              old_value: null,
              new_value: {
                from: item.sale_date_from || null,
                to: item.sale_date_to || null,
              },
            });
          }
        }
        if (field === 'stock_quantity') {
          previewData[item.id].push({
            field: 'stock_quantity',
            old_value: item.current_stock || item.old_stock,
            new_value: item.new_stock,
          });
        }
        if (field === 'sku') {
          previewData[item.id].push({
            field: 'sku',
            old_value: item.current_sku || item.old_sku,
            new_value: item.new_sku,
          });
        }
        if (field === 'image') {
          previewData[item.id].push({
            field: 'image_url',
            old_value: item.current_image_url || '',
            new_value: item.new_image_url || '',
          });
        }
      });
      
      console.log('[BulkPanel] Preview data:', previewData);
      onPreview(previewData);
      toast.success(t('bulk.preview_ready'));
    } catch (error: any) {
      console.error('[BulkPanel] Preview error:', error);

      // 🔒 SECURITY: Handle PRO-only feature errors from backend
      if (error.response?.status === 403) {
        toast.error(
          error.response?.data?.message ||
          t('errors.pro_feature_required', { defaultValue: 'This feature is available in PRO version only. Please upgrade to access it.' })
        );
      } else {
        toast.error(t('bulk.preview_error'));
      }
    }
  };

  // Handle apply
  const handleApply = async () => {
    // Image esetén mindig kell value (kép ID vagy 0 remove esetén)
    if (activeTab === 'image') {
      if (value === null || value === undefined || value === '') {
        toast.error(t('bulk.enter_value'));
        return;
      }
    } else if (!value && priceSubsection !== 'rounding' && operationType !== 'remove') {
      toast.error(t('bulk.enter_value'));
      return;
    }

    const field = getFieldForTab(activeTab, priceSubsection);
    // Image esetén az operation mindig 'set'
    const operation = activeTab === 'image' ? 'set' : operationType;
    
    try {
      const bulkOperation: any = {
        field,
        operation: operation,
        value: value || '0',
      };
      
      // Add rounding if applicable
      if (activeTab === 'price' && rounding > 1) {
        bulkOperation.rounding = rounding;
      }
      
      // Add sale dates if sale price operation
      if (priceSubsection === 'sale' && operationType !== 'remove') {
        if (saleDateFrom) bulkOperation.date_from = saleDateFrom;
        if (saleDateTo) bulkOperation.date_to = saleDateTo;
      }
      
      const result = await updateMutation.mutateAsync({
        variation_ids: variationIds,
        operations: [bulkOperation],
      });
      
      if (result.success) {
        toast.success(result.message);
        // Reset form after successful update
        setValue('');
      } else {
        toast.error(t('bulk.update_error'));
      }
    } catch (error: any) {
      // 🔒 SECURITY: Handle PRO-only feature errors from backend
      if (error.response?.status === 403) {
        toast.error(
          error.response?.data?.message ||
          t('errors.pro_feature_required', { defaultValue: 'This feature is available in PRO version only. Please upgrade to access it.' })
        );
      } else {
        toast.error(t('bulk.update_error'));
      }
    }
  };

  const getFieldForTab = (tab: TabType, subsection?: PriceSubsection): BulkFieldType => {
    switch (tab) {
      case 'price':
        if (subsection === 'sale') {
          return 'sale_price';
        }
        return 'regular_price';
      case 'stock':
        return 'stock_quantity';
      case 'sku':
        return 'sku';
      case 'image':
        return 'image';
    }
  };

  const getOperationsForTab = (tab: TabType, subsection?: PriceSubsection): BulkOperationType[] => {
    switch (tab) {
      case 'price':
        if (subsection === 'sale') {
          return ['percentage', 'fixed', 'set', 'remove'];
        }
        return ['percentage', 'fixed', 'set'];
      case 'stock':
        return ['increment', 'decrement', 'set'];
      case 'sku':
        return ['pattern'];
      case 'image':
        return ['set']; // Image csak "set" műveletet támogat
    }
  };

  const isLoading = previewMutation.isPending || updateMutation.isPending;
  
  // Button disabled logic
  const isButtonDisabled = () => {
    if (isLoading) return true;
    
    // Image tab: need value (image ID or 0 for remove)
    if (activeTab === 'image') {
      return value === null || value === undefined || value === '';
    }
    
    // Other tabs: need value except for rounding and remove operations
    if (priceSubsection === 'rounding' || operationType === 'remove') {
      return false;
    }
    
    return !value;
  };

  // Slide-in mode render
  if (mode === 'slide-in') {
    return (
      /* Slide-in Panel - NINCS backdrop, NINCS X gomb */
      <div 
        className="fixed right-0 bg-white shadow-2xl z-50 flex flex-col animate-slide-in-right border-l border-gray-200 w-96"
        style={{ top: '32px', height: 'calc(100vh - 32px)' }}
      >
          {/* Header */}
          <div className="px-6 py-4 border-b border-gray-200 bg-gradient-to-r from-indigo-500 to-purple-600">
            <div className="flex items-center gap-3 mb-3">
              <div className="w-8 h-8 bg-white rounded-lg flex items-center justify-center shadow-md shrink-0">
                <svg className="w-5 h-5 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4zm0 0h12a2 2 0 002-2v-4a2 2 0 00-2-2h-2.343M11 7.343l1.657-1.657a2 2 0 012.828 0l2.829 2.829a2 2 0 010 2.828l-8.486 8.485M7 17h.01" />
                </svg>
              </div>
              <div className="flex-1 min-w-0">
                <h2 className="text-lg font-bold text-white">
                  {t('bulk.title')}
                </h2>
                <div className="flex items-center gap-2 text-xs">
                  <span className="text-indigo-100">
                    {variationIds.length} {t('bulk.selected_items')}
                  </span>
                  {limitCheck.limit > 0 && (
                    <>
                      <span className="text-indigo-200">•</span>
                      <span className={showLimitWarning ? 'text-yellow-300 font-semibold' : 'text-indigo-100'}>
                        FREE: max {limitCheck.limit}
                      </span>
                    </>
                  )}
                </div>
              </div>
            </div>
            
            {/* Limit Warning Banner */}
            {showLimitWarning && (
              <div className="mt-2 px-3 py-2 bg-yellow-50 border border-yellow-200 rounded-lg flex items-start gap-2">
                <AlertTriangle size={16} className="text-yellow-600 shrink-0 mt-0.5" />
                <div className="flex-1 min-w-0">
                  <p className="text-xs text-yellow-800 leading-snug">
                    <strong>{t('bulk.limit_exceeded')}</strong> {t('bulk.limit_warning_free', { limit: limitCheck.limit })}
                  </p>
                  <div className="flex items-center gap-2 mt-1.5">
                    <ProBadge variant="inline" size="sm" />
                    <span className="text-xs text-yellow-700 font-medium">{t('bulk.limit_warning_pro_unlimited')}</span>
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* Tabs */}
          <div className="flex border-b border-gray-200 bg-gray-50">
            {(['price', 'stock', 'sku', 'image'] as TabType[]).map((tab) => {
              const isSkuLocked = tab === 'sku' && licenseInfo?.tier === 'free';
              
              return (
                <button
                  key={tab}
                  onClick={() => !isSkuLocked && handleTabChange(tab)}
                  disabled={isSkuLocked}
                  className={`flex-1 px-4 py-3 text-sm font-semibold transition relative ${
                    activeTab === tab
                      ? 'text-indigo-600 border-b-2 border-indigo-600 bg-white'
                      : isSkuLocked
                      ? 'text-gray-400 cursor-not-allowed bg-gray-100'
                      : 'text-gray-600 hover:text-gray-900 hover:bg-gray-100'
                  }`}
                  title={isSkuLocked ? t('bulk.sku_locked_tooltip') : ''}
                >
                  <span className="flex items-center justify-center gap-2">
                    {t(`bulk.tab_${tab}`)}
                    {isSkuLocked && <ProBadge variant="inline" size="sm" />}
                  </span>
                </button>
              );
            })}
          </div>

          {/* Content */}
          <div className="flex-1 overflow-y-auto p-6">
            {/* Price Subsections - csak Price tab esetén */}
            {activeTab === 'price' && (
              <div className="mb-6">
                <div className="flex gap-2 bg-gray-100 rounded-lg p-1">
                  {(['regular', 'sale', 'rounding'] as PriceSubsection[]).map((subsection) => (
                    <button
                      key={subsection}
                      onClick={() => {
                        setPriceSubsection(subsection);
                        setOperationType(getOperationsForTab('price', subsection)[0]);
                        setValue('');
                        setSaleDateFrom('');
                        setSaleDateTo('');
                        onClearPreview();
                      }}
                      className={`flex-1 px-3 py-2 text-xs font-semibold rounded-md transition ${
                        priceSubsection === subsection
                          ? 'bg-white text-indigo-600 shadow-sm'
                          : 'text-gray-600 hover:text-gray-900'
                      }`}
                    >
                      {t(`bulk.price_${subsection}`)}
                    </button>
                  ))}
                </div>
              </div>
            )}

            {/* Operation Type - CSAK ha több mint 1 opció van! */}
            {activeTab !== 'image' && !(activeTab === 'price' && priceSubsection === 'rounding') && 
             getOperationsForTab(activeTab, priceSubsection).length > 1 && (
              <div className="mb-6">
                <label className="block text-sm font-semibold text-gray-700 mb-3">
                  {t('bulk.operation_type')}
                </label>
                <div className="space-y-2">
                  {getOperationsForTab(activeTab, priceSubsection).map((op) => (
                    <label
                      key={op}
                      className={`flex items-center p-3 border-2 rounded-lg cursor-pointer transition ${
                        operationType === op
                          ? 'border-indigo-500 bg-indigo-50'
                          : 'border-gray-200 hover:border-gray-300 hover:bg-gray-50'
                      }`}
                    >
                      <input
                        type="radio"
                        name="operation"
                        value={op}
                        checked={operationType === op}
                        onChange={(e) => handleOperationChange(e.target.value as BulkOperationType)}
                        className="w-4 h-4 text-indigo-600"
                      />
                      <span className="ml-3 text-sm font-medium text-gray-900">
                        {t(`bulk.operation_${op}`)}
                      </span>
                    </label>
                  ))}
                </div>
              </div>
            )}

            {/* Sale Date Pickers - csak sale_price és nem remove operation esetén */}
            {activeTab === 'price' && priceSubsection === 'sale' && operationType !== 'remove' && (
              <div className="mb-6 space-y-3">
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-2">
                    {t('bulk.sale_date_from')} ({t('bulk.optional')})
                  </label>
                  <input
                    type="date"
                    value={saleDateFrom}
                    onChange={(e) => setSaleDateFrom(e.target.value)}
                    className="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition"
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-2">
                    {t('bulk.sale_date_to')} ({t('bulk.optional')})
                  </label>
                  <input
                    type="date"
                    value={saleDateTo}
                    onChange={(e) => setSaleDateTo(e.target.value)}
                    className="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition"
                  />
                </div>
              </div>
            )}

            {/* Rounding Input - csak rounding subsection esetén */}
            {activeTab === 'price' && priceSubsection === 'rounding' && (
              <div className="mb-6">
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  {t('bulk.round_to')}
                </label>
                <select
                  value={rounding}
                  onChange={(e) => setRounding(Number(e.target.value))}
                  className="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition"
                >
                  <option value={1}>{t('bulk.no_rounding')}</option>
                  <option value={10}>10</option>
                  <option value={50}>50</option>
                  <option value={100}>100</option>
                  <option value={500}>500</option>
                  <option value={1000}>1000</option>
                </select>
                <p className="mt-2 text-xs text-gray-500">
                  {t('bulk.rounding_hint')}
                </p>
              </div>
            )}

            {/* Value Input vagy Image Assigner */}
            {activeTab === 'image' ? (
              <div className="mb-6">
                <ImageAssigner
                  variationIds={variationIds}
                  onAssign={(imageId) => {
                    setValue(imageId ? imageId.toString() : '0');
                    console.log('[BulkPanel] Image assigned:', imageId);
                  }}
                />
              </div>
            ) : priceSubsection !== 'rounding' && operationType !== 'remove' && (
              <div className="mb-6">
                <label className="block text-sm font-semibold text-gray-700 mb-2">
                  {t('bulk.value')}
                </label>
                <input
                  type="text"
                  value={value}
                  onChange={(e) => setValue(e.target.value)}
                  placeholder={t(`bulk.placeholder_${activeTab}`)}
                  className="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition text-lg font-mono"
                />
                <p className="mt-2 text-xs text-gray-500">
                  {t(`bulk.hint_${operationType}`)}
                </p>
              </div>
            )}
          </div>

          {/* Footer Actions */}
          <div className="px-6 py-4 border-t border-gray-200 bg-gray-50 space-y-3">
            <button
              onClick={handlePreview}
              disabled={isButtonDisabled()}
              className="w-full px-4 py-3 bg-gray-600 text-white rounded-lg font-semibold hover:bg-gray-700 disabled:bg-gray-300 disabled:cursor-not-allowed transition flex items-center justify-center gap-2"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
              </svg>
              {t('bulk.preview')}
            </button>
            
            <button
              onClick={handleApply}
              disabled={isButtonDisabled()}
              className="w-full px-4 py-3 bg-gradient-to-r from-indigo-500 to-purple-600 text-white rounded-lg font-semibold hover:from-indigo-600 hover:to-purple-700 disabled:from-gray-300 disabled:to-gray-300 disabled:cursor-not-allowed transition flex items-center justify-center gap-2 shadow-lg"
            >
              {isLoading ? (
                <>
                  <LoadingSpinner size="sm" color="white" />
                  {t('bulk.applying')}
                </>
              ) : (
                <>
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                  </svg>
                  {t('bulk.apply')}
                </>
              )}
            </button>
          </div>
        </div>
    );
  }

  // Full-screen mode render
  return (
    <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
      {/* Info banner */}
      <div className="bg-gradient-to-r from-indigo-500 to-purple-600 px-6 py-4">
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-white rounded-lg flex items-center justify-center shadow-md shrink-0">
              <svg className="w-6 h-6 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4zm0 0h12a2 2 0 002-2v-4a2 2 0 00-2-2h-2.343M11 7.343l1.657-1.657a2 2 0 012.828 0l2.829 2.829a2 2 0 010 2.828l-8.486 8.485M7 17h.01" />
              </svg>
            </div>
            <div className="flex-1 min-w-0">
              <h2 className="text-lg font-bold text-white">
                {t('bulk.title')}
              </h2>
              <div className="flex items-center gap-2 text-sm">
                <span className="text-indigo-100">
                  {variationIds.length} {t('bulk.selected_items')}
                </span>
                {limitCheck.limit > 0 && (
                  <>
                    <span className="text-indigo-200">•</span>
                    <span className={showLimitWarning ? 'text-yellow-300 font-semibold' : 'text-indigo-100'}>
                      FREE: max {limitCheck.limit}
                    </span>
                  </>
                )}
              </div>
            </div>
          </div>
        </div>
        
        {/* Limit Warning Banner - Full-screen mode */}
        {showLimitWarning && (
          <div className="mt-2 px-3 py-2 bg-yellow-50 border border-yellow-200 rounded-lg flex items-start gap-2">
            <AlertTriangle size={16} className="text-yellow-600 shrink-0 mt-0.5" />
            <div className="flex-1 min-w-0">
              <p className="text-xs text-yellow-800 leading-snug">
                <strong>{t('bulk.limit_exceeded')}</strong> {t('bulk.limit_warning_free', { limit: limitCheck.limit })}
              </p>
              <div className="flex items-center gap-2 mt-1.5">
                <ProBadge variant="inline" size="sm" />
                <span className="text-xs text-yellow-700 font-medium">{t('bulk.limit_warning_pro_unlimited')}</span>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Tabs */}
      <div className="flex border-b border-gray-200 bg-gray-50">
        {(['price', 'stock', 'sku', 'image'] as TabType[]).map((tab) => {
          const isSkuLocked = tab === 'sku' && licenseInfo?.tier === 'free';
          
          return (
            <button
              key={tab}
              onClick={() => !isSkuLocked && handleTabChange(tab)}
              disabled={isSkuLocked}
              className={`flex-1 px-6 py-4 text-sm font-semibold transition ${
                activeTab === tab
                  ? 'text-indigo-600 border-b-2 border-indigo-600 bg-white'
                  : isSkuLocked
                  ? 'text-gray-400 cursor-not-allowed bg-gray-100'
                  : 'text-gray-600 hover:text-gray-900 hover:bg-gray-100'
              }`}
              title={isSkuLocked ? t('bulk.sku_locked_tooltip') : ''}
            >
              <span className="flex items-center justify-center gap-2">
                {t(`bulk.tab_${tab}`)}
                {isSkuLocked && <ProBadge variant="inline" size="sm" />}
              </span>
            </button>
          );
        })}
      </div>

      {/* Content */}
      <div className="p-8">
        <div className="max-w-4xl mx-auto">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
            {/* Left column - Operation settings */}
            <div className="space-y-6">
              {/* Price Subsections - csak Price tab esetén */}
              {activeTab === 'price' && (
                <div>
                  <div className="flex gap-2 bg-gray-100 rounded-lg p-1">
                    {(['regular', 'sale', 'rounding'] as PriceSubsection[]).map((subsection) => (
                      <button
                        key={subsection}
                        onClick={() => {
                          setPriceSubsection(subsection);
                          setOperationType(getOperationsForTab('price', subsection)[0]);
                          setValue('');
                          setSaleDateFrom('');
                          setSaleDateTo('');
                          onClearPreview();
                        }}
                        className={`flex-1 px-3 py-2 text-sm font-semibold rounded-md transition ${
                          priceSubsection === subsection
                            ? 'bg-white text-indigo-600 shadow-sm'
                            : 'text-gray-600 hover:text-gray-900'
                        }`}
                      >
                        {t(`bulk.price_${subsection}`)}
                      </button>
                    ))}
                  </div>
                </div>
              )}

              {/* Operation Type - CSAK ha több mint 1 opció van! */}
              {activeTab !== 'image' && !(activeTab === 'price' && priceSubsection === 'rounding') && 
               getOperationsForTab(activeTab, priceSubsection).length > 1 && (
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-3">
                    {t('bulk.operation_type')}
                  </label>
                  <div className="space-y-2">
                    {getOperationsForTab(activeTab, priceSubsection).map((op) => (
                      <label
                        key={op}
                        className={`flex items-center p-4 border-2 rounded-lg cursor-pointer transition ${
                          operationType === op
                            ? 'border-indigo-500 bg-indigo-50'
                            : 'border-gray-200 hover:border-gray-300 hover:bg-gray-50'
                        }`}
                      >
                        <input
                          type="radio"
                          name="operation"
                          value={op}
                          checked={operationType === op}
                          onChange={(e) => handleOperationChange(e.target.value as BulkOperationType)}
                          className="w-5 h-5 text-indigo-600"
                        />
                        <span className="ml-3 text-sm font-medium text-gray-900">
                          {t(`bulk.operation_${op}`)}
                        </span>
                      </label>
                    ))}
                  </div>
                </div>
              )}

              {/* Sale Date Pickers - csak sale_price és nem remove operation esetén */}
              {activeTab === 'price' && priceSubsection === 'sale' && operationType !== 'remove' && (
                <div className="space-y-3">
                  <div>
                    <label className="block text-sm font-semibold text-gray-700 mb-2">
                      {t('bulk.sale_date_from')} ({t('bulk.optional')})
                    </label>
                    <input
                      type="date"
                      value={saleDateFrom}
                      onChange={(e) => setSaleDateFrom(e.target.value)}
                      className="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-gray-700 mb-2">
                      {t('bulk.sale_date_to')} ({t('bulk.optional')})
                    </label>
                    <input
                      type="date"
                      value={saleDateTo}
                      onChange={(e) => setSaleDateTo(e.target.value)}
                      className="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition"
                    />
                  </div>
                </div>
              )}

              {/* Rounding Input - csak rounding subsection esetén */}
              {activeTab === 'price' && priceSubsection === 'rounding' && (
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-2">
                    {t('bulk.round_to')}
                  </label>
                  <select
                    value={rounding}
                    onChange={(e) => setRounding(Number(e.target.value))}
                    className="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition"
                  >
                    <option value={1}>{t('bulk.no_rounding')}</option>
                    <option value={10}>10</option>
                    <option value={50}>50</option>
                    <option value={100}>100</option>
                    <option value={500}>500</option>
                    <option value={1000}>1000</option>
                  </select>
                  <p className="mt-2 text-sm text-gray-500">
                    {t('bulk.rounding_hint')}
                  </p>
                </div>
              )}

              {/* Value Input vagy Image Assigner */}
              {activeTab === 'image' ? (
                <div>
                  <ImageAssigner
                    variationIds={variationIds}
                    onAssign={(imageId) => {
                      setValue(imageId ? imageId.toString() : '0');
                      console.log('[BulkPanel] Image assigned:', imageId);
                    }}
                  />
                </div>
              ) : priceSubsection !== 'rounding' && operationType !== 'remove' && (
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-2">
                    {t('bulk.value')}
                  </label>
                  <input
                    type="text"
                    value={value}
                    onChange={(e) => setValue(e.target.value)}
                    placeholder={t(`bulk.placeholder_${activeTab}`)}
                    className="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition text-lg font-mono"
                  />
                  <p className="mt-2 text-sm text-gray-500">
                    {t(`bulk.hint_${operationType}`)}
                  </p>
                </div>
              )}
            </div>

            {/* Right column - Actions */}
            <div className="space-y-4">
              <div className="bg-gradient-to-br from-indigo-50 to-purple-50 rounded-xl p-6 border border-indigo-100">
                <h3 className="font-bold text-gray-900 mb-4 flex items-center gap-2">
                  <svg className="w-5 h-5 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  {t('bulk.actions')}
                </h3>
                
                <div className="space-y-3">
                  <button
                    onClick={handlePreview}
                    disabled={isButtonDisabled()}
                    className="w-full px-6 py-4 bg-gray-600 text-white rounded-lg font-semibold hover:bg-gray-700 disabled:bg-gray-300 disabled:cursor-not-allowed transition flex items-center justify-center gap-2 shadow-md"
                  >
                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                    </svg>
                    {t('bulk.preview')}
                  </button>
                  
                  <button
                    onClick={handleApply}
                    disabled={isButtonDisabled()}
                    className="w-full px-6 py-4 bg-gradient-to-r from-indigo-500 to-purple-600 text-white rounded-lg font-semibold hover:from-indigo-600 hover:to-purple-700 disabled:from-gray-300 disabled:to-gray-300 disabled:cursor-not-allowed transition flex items-center justify-center gap-2 shadow-lg"
                  >
                    {isLoading ? (
                      <>
                        <LoadingSpinner size="sm" color="white" />
                        {t('bulk.applying')}
                      </>
                    ) : (
                      <>
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                        </svg>
                        {t('bulk.apply')}
                      </>
                    )}
                  </button>
                </div>

                <div className="mt-4 p-4 bg-white rounded-lg border border-indigo-200">
                  <p className="text-xs text-gray-600">
                    💡 <strong>{t('bulk.tip')}:</strong> {t('bulk.tip_message')}
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
