/**
 * Column Definitions for AG Grid
 * 
 * Maps ColumnId to AG Grid ColDef objects
 */

import React from 'react';
import type { ColDef, ICellRendererParams } from 'ag-grid-community';
import type { ColumnId } from '../../types/columns';
import type { TFunction } from 'i18next';
import { formatPrice, formatWeight, formatDimension, type WCSettings } from '../../utils/woocommerce';

type PreviewGetter = (variationId: number, field: string) => any;

export function createPreviewCellRenderer(
  field: string,
  formatter?: (val: any) => string,
  getPreview?: PreviewGetter
) {
  return (params: ICellRendererParams) => {
    const isParent = params.data.type === 'parent';
    if (isParent) {
      return <span className="font-bold text-gray-700 truncate">{params.value}</span>;
    }

    const preview = getPreview?.(params.data.id, field);
    console.log(`[PreviewRenderer] ID: ${params.data.id}, field: ${field}, preview:`, preview);
    
    const currentValue = params.value;
    const formattedCurrent = formatter ? formatter(currentValue) : currentValue;

    if (preview) {
      const formattedNew = formatter ? formatter(preview.new_value) : preview.new_value;
      console.log(`[PreviewRenderer] Rendering preview - current: ${formattedCurrent}, new: ${formattedNew}`);
      return (
        <div className="flex flex-col gap-0.5">
          <span className="text-gray-600 truncate">{formattedCurrent}</span>
          <div className="flex items-center gap-1 text-xs">
            <span className="text-gray-400">→</span>
            <span className="font-semibold text-emerald-600 bg-emerald-50 px-2 py-0.5 rounded border border-emerald-200 truncate">
              {formattedNew}
            </span>
          </div>
        </div>
      );
    }

    return <span className="truncate">{formattedCurrent}</span>;
  };
}

export function getColumnDefinition(
  columnId: ColumnId,
  t: TFunction,
  width?: number,
  getPreview?: PreviewGetter,
  setSalePriceEdit?: (state: any) => void,
  toggleParentExpand?: (parentId: number) => void,
  taxClassOptions?: string[], // 🎯 Tax classes from WooCommerce
  wcSettings?: WCSettings // 🎯 WooCommerce settings (currency, units, formatting)
): ColDef {
  const commonCellStyle = (params: any) => {
    const isParent = params.data.type === 'parent';
    if (isParent) return { backgroundColor: '#f3f4f6' } as any; // Sötétebb szürke a parentnél

    const preview = getPreview?.(params.data.id, columnId);
    return preview ? { backgroundColor: '#fefce8', borderLeft: '3px solid #eab308' } as any : null;
  };

  switch (columnId) {
    case 'id':
      return {
        field: 'id',
        headerName: 'ID',
        width: width || 70,
        checkboxSelection: true,
        headerCheckboxSelection: false,
        pinned: 'left',
        cellClass: 'font-mono text-xs text-gray-600',
      };

    case 'image':
      return {
        field: 'image_url',
        headerName: t('image'),
        width: width || 90,
        pinned: 'left',
        cellRenderer: (params: ICellRendererParams) => {
          const preview = getPreview?.(params.data.id, 'image_url');
          const currentImageUrl = params.value;

          if (preview) {
            const newImageUrl = preview.new_value as string;
            return (
              <div className="flex flex-col items-center justify-center h-full gap-1">
                {currentImageUrl && (
                  <img
                    src={currentImageUrl}
                    alt="Current"
                    className="w-10 h-10 object-cover rounded border border-gray-300 opacity-50"
                    title="Jelenlegi kép"
                  />
                )}
                {newImageUrl && (
                  <div className="relative">
                    <img
                      src={newImageUrl}
                      alt="New"
                      className="w-14 h-14 object-cover rounded-lg shadow-md border-2 border-emerald-500"
                      title="Új kép"
                    />
                    <span className="absolute -top-1 -right-1 w-4 h-4 bg-emerald-500 rounded-full flex items-center justify-center text-white text-xs">
                      ✓
                    </span>
                  </div>
                )}
              </div>
            );
          }

          if (!currentImageUrl) return null;
          return (
            <div className="flex items-center justify-center h-full">
              <img
                src={currentImageUrl}
                alt=""
                className="w-10 h-10 object-cover rounded-lg shadow-sm border border-gray-200"
              />
            </div>
          );
        },
        cellStyle: commonCellStyle,
      };

    case 'parent_name':
      return {
        field: 'parent_name',
        headerName: t('product'),
        width: width || 280,
        pinned: 'left',
        cellRenderer: (params: any) => {
          const isParent = params.data.type === 'parent';

          if (isParent) {
            const isExpanded = params.data.expanded;
            const variationCount = params.data.variation_count || 0;
            return (
              <button
                onClick={() => toggleParentExpand?.(params.data.id)}
                className="py-1 w-full text-left hover:bg-gray-200 transition-colors cursor-pointer flex items-center justify-between gap-2"
              >
                <div className="overflow-hidden flex-1">
                  <div className="font-bold text-xs text-gray-900 mb-0.5 truncate">
                    {params.data.parent_name}
                  </div>
                  <div className="text-xs text-gray-500 font-medium">
                    {variationCount} variáció
                  </div>
                </div>
                <span className="text-sm text-blue-600 flex-shrink-0">
                  {isExpanded ? '▼' : '▶'}
                </span>
              </button>
            );
          }

          return (
            <div className="py-1 pl-4">
              <div className="font-semibold text-xs text-gray-900 mb-0.5 truncate">{params.data.parent_name}</div>
              <div className="text-xs text-gray-500 font-medium truncate">
                {params.data.attributes ? Object.entries(params.data.attributes).map(([, value]) =>
                  value
                ).join(' • ') : ''}
              </div>
            </div>
          );
        },
        cellStyle: (params) => {
          const isParent = params.data.type === 'parent';
          return isParent ? { backgroundColor: '#f3f4f6' } : null; // Sötétebb szürke
        },
      };

    case 'sku':
      return {
        field: 'sku',
        headerName: t('sku'),
        width: width || 160,
        editable: (params) => params.data.type !== 'parent',
        cellClass: (params) => params.data.type === 'parent' ? '' : 'editable-cell font-mono text-xs',
        cellRenderer: createPreviewCellRenderer('sku', undefined, getPreview),
        cellStyle: (params) => {
          const isParent = params.data.type === 'parent';
          if (isParent) return { backgroundColor: '#f3f4f6', color: '#9ca3af' } as any; // Sötétebb szürke

          const preview = getPreview?.(params.data.id, 'sku');
          // SKU: csak monospace, NINCS szürke háttér
          const baseStyle = { 
            fontFamily: 'monospace', 
            fontSize: '0.75rem',
            whiteSpace: 'nowrap',
            overflow: 'hidden',
            textOverflow: 'ellipsis'
          } as any;
          return preview 
            ? { ...baseStyle, backgroundColor: '#fefce8', borderLeft: '3px solid #eab308' } as any 
            : baseStyle;
        },
      };

    case 'price':
      return {
        field: 'price',
        headerName: t('price'),
        width: width || 130,
        editable: (params) => params.data.type !== 'parent',
        cellClass: (params) => params.data.type === 'parent' ? 'font-bold text-gray-700' : 'editable-cell font-semibold text-gray-900',
        valueFormatter: (params) => {
          if (params.data.type === 'parent') return params.value; // Already formatted in VariationsTable
          return wcSettings ? formatPrice(params.value, wcSettings) : `${params.value} Ft`;
        },
        valueParser: (params) => params.newValue.replace(/[^\d]/g, ''),
        cellRenderer: createPreviewCellRenderer('price', (val) => wcSettings ? formatPrice(val, wcSettings) : `${val} Ft`, getPreview),
        cellStyle: commonCellStyle,
      };

    case 'regular_price':
      return {
        field: 'regular_price',
        headerName: t('regular_price'),
        width: width || 130,
        editable: (params) => params.data.type !== 'parent',
        cellClass: (params) => params.data.type === 'parent' ? 'font-bold text-gray-700' : 'editable-cell',
        valueFormatter: (params) => {
          if (params.data.type === 'parent') return params.value || '-'; // Already formatted
          return wcSettings ? formatPrice(params.value, wcSettings) : (params.value ? `${params.value} Ft` : '-');
        },
        valueParser: (params) => params.newValue.replace(/[^\d]/g, ''),
        cellRenderer: createPreviewCellRenderer('regular_price', (val) => wcSettings ? formatPrice(val, wcSettings) : `${val} Ft`, getPreview),
        cellStyle: commonCellStyle,
      };

    case 'sale_price':
      return {
        field: 'sale_price',
        headerName: t('sale_price'),
        width: width || 180,
        editable: false,
        cellClass: (params) => params.data.type === 'parent' ? 'font-bold text-orange-700' : 'editable-cell font-semibold text-orange-600',
        onCellDoubleClicked: (params) => {
          if (params.data.type === 'parent' || !setSalePriceEdit) return;

          const cellElement = params.event?.target as HTMLElement;
          const cellRect = cellElement?.closest('.ag-cell')?.getBoundingClientRect();

          if (cellRect) {
            const dropdownHeight = 440;
            const viewportHeight = window.innerHeight;
            const spaceBelow = viewportHeight - cellRect.bottom;
            const showAbove = spaceBelow < dropdownHeight + 20;

            setSalePriceEdit({
              variationId: params.data.id,
              currentPrice: params.data.sale_price || '',
              dateFrom: params.data.date_on_sale_from || null,
              dateTo: params.data.date_on_sale_to || null,
              position: {
                top: showAbove ? cellRect.top - dropdownHeight - 4 : cellRect.bottom + 4,
                left: cellRect.left,
                width: cellRect.width,
                showAbove,
              },
            });
          }
        },
        valueFormatter: (params) => {
          if (params.data.type === 'parent') return params.value || '-';
          return wcSettings ? formatPrice(params.value, wcSettings) : (params.value ? `${params.value} Ft` : '-');
        },
        cellRenderer: (params: ICellRendererParams) => {
          const isParent = params.data.type === 'parent';

          if (isParent) {
            return (
              <div className="flex items-center h-full">
                <span className="font-bold text-orange-700 truncate">{params.value || '-'}</span>
              </div>
            );
          }

          const pricePreview = getPreview?.(params.data.id, 'sale_price');
          const currentValue = params.value;
          const formattedCurrent = wcSettings ? formatPrice(currentValue, wcSettings) : (currentValue ? `${currentValue} Ft` : '-');
          const dateFrom = params.data.date_on_sale_from;
          const dateTo = params.data.date_on_sale_to;
          const hasDates = dateFrom || dateTo;
          
          // ✅ CRITICAL: Manual double-click handler (cellRenderer blocks AG Grid's onCellDoubleClicked)
          const handleDoubleClick = () => {
            console.log('[sale_price cellRenderer] Double-click detected!', { 
              id: params.data.id, 
              setSalePriceEdit: !!setSalePriceEdit 
            });
            
            if (!setSalePriceEdit) {
              console.error('[sale_price cellRenderer] NO setSalePriceEdit callback!');
              return;
            }
            
            const cellElement = params.eGridCell;
            const cellRect = cellElement?.getBoundingClientRect();

            if (cellRect) {
              const dropdownHeight = 440;
              const viewportHeight = window.innerHeight;
              const spaceBelow = viewportHeight - cellRect.bottom;
              const showAbove = spaceBelow < dropdownHeight + 20;

              console.log('[sale_price cellRenderer] Opening modal at:', {
                top: showAbove ? cellRect.top - dropdownHeight - 4 : cellRect.bottom + 4,
                left: cellRect.left,
                showAbove
              });

              setSalePriceEdit({
                variationId: params.data.id,
                currentPrice: params.data.sale_price || '',
                dateFrom: params.data.date_on_sale_from || null,
                dateTo: params.data.date_on_sale_to || null,
                position: {
                  top: showAbove ? cellRect.top - dropdownHeight - 4 : cellRect.bottom + 4,
                  left: cellRect.left,
                  width: cellRect.width,
                  showAbove,
                },
              });
            }
          };

          if (pricePreview) {
            const formattedNew = wcSettings ? formatPrice(pricePreview.new_value, wcSettings) : (pricePreview.new_value ? `${pricePreview.new_value} Ft` : '-');

            return (
              <div 
                className="flex flex-col gap-0.5 py-1 cursor-pointer" 
                onDoubleClick={handleDoubleClick}
              >
                <div className="flex items-center gap-2">
                  <span className="text-orange-600 truncate">{formattedCurrent}</span>
                  {hasDates && (
                    <span className="text-xs text-gray-500 flex-shrink-0" title={`${dateFrom || '?'} → ${dateTo || '?'}`}>
                      📅
                    </span>
                  )}
                </div>
                <div className="flex items-center gap-1 text-xs">
                  <span className="text-gray-400">→</span>
                  <span className="font-semibold text-emerald-600 bg-emerald-50 px-2 py-0.5 rounded border border-emerald-200 truncate">
                    {formattedNew}
                  </span>
                </div>
              </div>
            );
          }

          return (
            <div 
              className="flex items-center gap-2 cursor-pointer" 
              onDoubleClick={handleDoubleClick}
            >
              <span className="font-semibold text-orange-600 truncate">{formattedCurrent}</span>
              {hasDates && (
                <span className="text-xs text-gray-500 flex-shrink-0" title={`${dateFrom || '?'} → ${dateTo || '?'}`}>
                  📅
                </span>
              )}
            </div>
          );
        },
        cellStyle: commonCellStyle,
      };

    case 'stock_quantity':
      return {
        field: 'stock_quantity',
        headerName: t('stock'),
        width: width || 90,
        editable: (params) => params.data.type !== 'parent',
        cellClass: (params) => params.data.type === 'parent' ? 'font-bold text-center text-blue-700' : 'editable-cell font-bold text-center',
        valueParser: (params) => parseInt(params.newValue) || 0,
        cellRenderer: createPreviewCellRenderer('stock_quantity', undefined, getPreview),
        cellStyle: commonCellStyle,
      };

    case 'stock_status':
      return {
        field: 'stock_status',
        headerName: t('status'),
        width: width || 130,
        editable: (params) => params.data.type !== 'parent',
        cellEditor: 'agSelectCellEditor',
        cellEditorParams: {
          values: ['instock', 'outofstock', 'onbackorder'],
        },
        cellClass: (params) => params.data.type === 'parent' ? '' : 'editable-cell',
        cellRenderer: (params: any) => {
          const isParent = params.data.type === 'parent';
          if (isParent) {
            return <span className="text-gray-500">-</span>;
          }

          const statusClass =
            params.value === 'instock' ? 'bg-emerald-100 text-emerald-800 border-emerald-200' :
            params.value === 'outofstock' ? 'bg-red-100 text-red-800 border-red-200' :
            'bg-amber-100 text-amber-800 border-amber-200';

          return (
            <div className="flex items-center h-full">
              <span className={`px-2 py-0.5 rounded-full text-xs font-semibold border ${statusClass} truncate max-w-full`}>
                {t(`stock_status.${params.value}`)}
              </span>
            </div>
          );
        },
        cellStyle: commonCellStyle,
      };

    // További oszlopok alapértelmezett definíciói
    case 'manage_stock':
      return {
        field: 'manage_stock',
        headerName: t('manage_stock'),
        width: width || 120,
        editable: (params) => params.data.type !== 'parent',
        cellEditor: 'agSelectCellEditor',
        cellEditorParams: {
          values: [true, false],
        },
        cellClass: (params) => params.data.type === 'parent' ? '' : 'editable-cell text-center',
        cellRenderer: (params: any) => {
          const isParent = params.data.type === 'parent';
          if (isParent) return <span className="text-gray-500">-</span>;
          return params.value ? <span className="text-green-600 font-bold">✓</span> : <span className="text-gray-400">-</span>;
        },
        cellStyle: commonCellStyle,
      };

    case 'weight':
      return {
        field: 'weight',
        headerName: t('weight'),
        width: width || 100,
        editable: (params) => params.data.type !== 'parent',
        cellClass: (params) => params.data.type === 'parent' ? '' : 'editable-cell',
        valueFormatter: (params) => wcSettings ? formatWeight(params.value, wcSettings) : (params.value ? `${params.value} kg` : '-'),
        cellStyle: commonCellStyle,
      };

    case 'length':
    case 'width':
    case 'height':
      return {
        field: columnId,
        headerName: t(columnId),
        width: width || 90,
        editable: (params) => params.data.type !== 'parent',
        cellClass: (params) => params.data.type === 'parent' ? '' : 'editable-cell',
        valueFormatter: (params) => wcSettings ? formatDimension(params.value, wcSettings) : (params.value ? `${params.value} cm` : '-'),
        cellStyle: commonCellStyle,
      };

    case 'tax_class':
      // 🎯 Use RAW slugs directly from WooCommerce
      console.log('[columnDefinitions] taxClassOptions RAW:', taxClassOptions);
      
      // Build dropdown options with UNIQUE values
      const rawOptions = taxClassOptions || ['parent', ''];
      const uniqueOptions = Array.from(new Set(rawOptions)); // Remove duplicates
      
      console.log('[columnDefinitions] uniqueOptions:', uniqueOptions);
      
      return {
        field: 'tax_class',
        headerName: t('tax_class'),
        width: width || 150,
        editable: (params) => params.data.type !== 'parent',
        cellEditor: 'agSelectCellEditor',
        cellEditorParams: {
          values: uniqueOptions, // 🎯 RAW unique slugs from WooCommerce
        },
        cellClass: (params) => params.data.type === 'parent' ? '' : 'editable-cell',
        valueFormatter: (params) => {
          const value = params.value;
          // 🎯 Display RAW values as-is from WooCommerce (no translation needed)
          // If WooCommerce tax classes are renamed, this will automatically reflect
          if (!value || value === '') return 'Standard';
          if (value === 'parent') return 'Parent';
          // Just capitalize and replace hyphens with spaces
          return value
            .split('-')
            .map((word: string) => word.charAt(0).toUpperCase() + word.slice(1))
            .join(' ');
        },
        cellStyle: commonCellStyle,
      };

    case 'status':
      return {
        field: 'status',
        headerName: t('status'),
        width: width || 100,
        editable: (params) => params.data.type !== 'parent',
        cellEditor: 'agSelectCellEditor',
        cellEditorParams: {
          values: ['publish', 'private', 'draft'],
        },
        cellClass: (params) => params.data.type === 'parent' ? '' : 'editable-cell',
        cellRenderer: (params: any) => {
          const isParent = params.data.type === 'parent';
          if (isParent) return <span className="text-gray-500">-</span>;
          
          const statusClass = params.value === 'publish' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800';
          return <span className={`px-1.5 py-0.5 rounded text-xs ${statusClass}`}>{params.value}</span>;
        },
        cellStyle: commonCellStyle,
      };

    case 'description':
      return {
        field: 'description',
        headerName: t('description'),
        width: width || 200,
        editable: (params) => params.data.type !== 'parent',
        cellClass: (params) => params.data.type === 'parent' ? '' : 'editable-cell',
        cellStyle: commonCellStyle,
      };

    case 'backorders':
      return {
        field: 'backorders',
        headerName: t('backorders'),
        width: width || 120,
        editable: (params) => params.data.type !== 'parent',
        cellEditor: 'agSelectCellEditor',
        cellEditorParams: {
          values: ['no', 'notify', 'yes'],
        },
        cellClass: (params) => params.data.type === 'parent' ? '' : 'editable-cell text-center',
        cellRenderer: (params: any) => {
          const isParent = params.data.type === 'parent';
          if (isParent) return <span className="text-gray-500">-</span>;
          return params.value === 'yes' || params.value === 'notify' ? <span className="text-green-600 font-bold">✓</span> : <span className="text-gray-400">-</span>;
        },
        cellStyle: commonCellStyle,
      };

    case 'low_stock_threshold':
      return {
        field: 'low_stock_threshold',
        headerName: t('low_stock_threshold'),
        width: width || 140,
        editable: (params) => params.data.type !== 'parent',
        cellClass: (params) => params.data.type === 'parent' ? '' : 'editable-cell',
        valueParser: (params) => parseInt(params.newValue) || 0,
        cellStyle: commonCellStyle,
      };

    case 'virtual':
    case 'downloadable':
      return {
        field: columnId,
        headerName: t(columnId),
        width: width || 110,
        editable: (params) => params.data.type !== 'parent',
        cellEditor: 'agSelectCellEditor',
        cellEditorParams: {
          values: [true, false],
        },
        cellClass: (params) => params.data.type === 'parent' ? '' : 'editable-cell text-center',
        cellRenderer: (params: any) => {
          const isParent = params.data.type === 'parent';
          if (isParent) return <span className="text-gray-500">-</span>;
          return params.value ? <span className="text-green-600 font-bold">✓</span> : <span className="text-gray-400">-</span>;
        },
        cellStyle: commonCellStyle,
      };

    default:
      return {
        field: columnId,
        headerName: columnId,
        width: width || 120,
      };
  }
}
