/**
 * ImageAssigner Component
 * 
 * Professzionális tömeges kép hozzárendelés funkciók:
 * - WordPress Media Library integráció
 * - Szülő termék képeinek megjelenítése
 * - Attribútum alapú intelligens hozzárendelés
 * - Tömeges kép eltávolítás
 * - Drag & drop képfeltöltés
 */

import React from 'react';
import { useState } from 'react';
import React from 'react';
import { useTranslation } from 'react-i18next';
import React from 'react';
import { useQuery } from '@tanstack/react-query';
import React from 'react';
import { getVariationsByIds, getProduct } from '../../services/api';
import React from 'react';
import LoadingSpinner from '../ui/LoadingSpinner';

interface Props {
  variationIds: number[];
  onAssign: (imageId: number | null) => void;
}

interface ParentProduct {
  id: number;
  name: string;
  images: {
    id: number;
    url: string;
    thumbnail: string;
    alt: string;
  }[];
}

type AssignMode = 'single' | 'from-parent' | 'remove' | 'upload';

export default function ImageAssigner({ variationIds, onAssign }: Props) {
  const { t } = useTranslation();
  const [assignMode, setAssignMode] = useState<AssignMode>('single');
  const [selectedImageUrl, setSelectedImageUrl] = useState<string>('');
  const [selectedParentImage, setSelectedParentImage] = useState<number | null>(null);

  // Handle assign mode change
  const handleAssignModeChange = (mode: AssignMode) => {
    setAssignMode(mode);
    
    // Reset selections
    setSelectedImageUrl('');
    setSelectedParentImage(null);
    
    // Ha remove mode, akkor automatikusan 0-ra állítjuk (remove image)
    if (mode === 'remove') {
      onAssign(0);
    }
    // Egyébként nem hívunk semmit, várjuk hogy a user válasszon képet
  };

  // Fetch parent products' images
  const { data: parentProducts, isLoading: isLoadingParents } = useQuery({
    queryKey: ['parent-products-images', variationIds],
    queryFn: async () => {
      // Get unique parent IDs from variations
      const variations = await getVariationsByIds(variationIds);
      const uniqueParentIds = [...new Set(variations.map((v: any) => v.parent_id))];
      
      // Fetch parent products with images
      const parents = await Promise.all(
        uniqueParentIds.map(async (parentId) => {
          const product = await getProduct(parentId);
          return {
            id: product.id,
            name: product.name,
            images: product.images.map((img: any) => ({
              id: img.id,
              url: img.src,
              thumbnail: img.src,
              alt: img.alt || product.name,
            })),
          };
        })
      );
      
      return parents;
    },
    enabled: variationIds.length > 0,
  });

  // Open WordPress Media Library
  const openMediaLibrary = () => {
    // @ts-ignore - WordPress wp.media is available globally
    if (typeof wp !== 'undefined' && wp.media) {
      const frame = wp.media({
        title: t('bulk.select_or_upload_image'),
        button: {
          text: t('bulk.select_image'),
        },
        multiple: false,
        library: {
          type: 'image'
        }
      });

      frame.on('select', () => {
        const attachment = frame.state().get('selection').first().toJSON();
        setSelectedImageUrl(attachment.url);
        onAssign(attachment.id);
      });

      frame.open();
    } else {
      console.error('WordPress Media Library not available');
    }
  };

  // Handle parent image selection
  const handleParentImageSelect = (imageId: number, imageUrl: string) => {
    setSelectedParentImage(imageId);
    setSelectedImageUrl(imageUrl);
    onAssign(imageId);
  };

  // Handle remove images
  const handleRemoveImages = () => {
    setSelectedImageUrl('');
    setSelectedParentImage(null);
    onAssign(0); // 0 = remove image
  };

  return (
    <div className="space-y-6">
      {/* Mode Selector */}
      <div>
        <label className="block text-sm font-semibold text-gray-700 mb-3">
          {t('bulk.image_assign_mode')}
        </label>
        <div className="grid grid-cols-2 gap-3">
          <button
            onClick={() => handleAssignModeChange('single')}
            className={`px-4 py-3 rounded-lg border-2 transition text-sm font-medium ${
              assignMode === 'single'
                ? 'border-indigo-500 bg-indigo-50 text-indigo-700'
                : 'border-gray-300 hover:border-gray-400 text-gray-700'
            }`}
          >
            <svg className="w-5 h-5 mx-auto mb-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
            </svg>
            {t('bulk.select_existing')}
          </button>
          
          <button
            onClick={() => handleAssignModeChange('upload')}
            className={`px-4 py-3 rounded-lg border-2 transition text-sm font-medium ${
              assignMode === 'upload'
                ? 'border-green-500 bg-green-50 text-green-700'
                : 'border-gray-300 hover:border-gray-400 text-gray-700'
            }`}
          >
            <svg className="w-5 h-5 mx-auto mb-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
            </svg>
            {t('bulk.upload_new')}
          </button>
          
          <button
            onClick={() => handleAssignModeChange('from-parent')}
            className={`px-4 py-3 rounded-lg border-2 transition text-sm font-medium ${
              assignMode === 'from-parent'
                ? 'border-indigo-500 bg-indigo-50 text-indigo-700'
                : 'border-gray-300 hover:border-gray-400 text-gray-700'
            }`}
          >
            <svg className="w-5 h-5 mx-auto mb-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
            </svg>
            {t('bulk.from_parent')}
          </button>
          
          <button
            onClick={() => handleAssignModeChange('remove')}
            className={`px-4 py-3 rounded-lg border-2 transition text-sm font-medium ${
              assignMode === 'remove'
                ? 'border-red-500 bg-red-50 text-red-700'
                : 'border-gray-300 hover:border-gray-400 text-gray-700'
            }`}
          >
            <svg className="w-5 h-5 mx-auto mb-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
            </svg>
            {t('bulk.remove_images')}
          </button>
        </div>
      </div>

      {/* Single Image Mode */}
      {assignMode === 'single' && (
        <div className="space-y-4">
          <button
            type="button"
            onClick={openMediaLibrary}
            className="w-full px-4 py-3 bg-indigo-600 text-white rounded-lg font-semibold hover:bg-indigo-700 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="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
            </svg>
            {t('bulk.select_from_library')}
          </button>

          {selectedImageUrl && (
            <div className="relative border-2 border-gray-300 rounded-lg p-4 bg-white">
              <img
                src={selectedImageUrl}
                alt="Selected"
                className="w-full h-48 object-contain rounded"
              />
              <div className="mt-2 text-sm text-gray-600 text-center font-medium">
                {t('bulk.image_selected')}
              </div>
              <button
                onClick={() => {
                  setSelectedImageUrl('');
                }}
                className="absolute top-2 right-2 p-1 bg-red-500 text-white rounded-full hover:bg-red-600 transition"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
          )}

          {!selectedImageUrl && (
            <div className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center text-gray-500">
              <svg className="w-12 h-12 mx-auto mb-2 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
              </svg>
              <p className="text-sm">{t('bulk.no_image_selected')}</p>
            </div>
          )}
        </div>
      )}

      {/* Upload New Image Mode */}
      {assignMode === 'upload' && (
        <div className="space-y-4">
          <button
            type="button"
            onClick={openMediaLibrary}
            className="w-full px-4 py-3 bg-green-600 text-white rounded-lg font-semibold hover:bg-green-700 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="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
            </svg>
            {t('bulk.upload_and_select')}
          </button>

          {selectedImageUrl && (
            <div className="relative border-2 border-green-300 rounded-lg p-4 bg-green-50">
              <img
                src={selectedImageUrl}
                alt="Uploaded"
                className="w-full h-48 object-contain rounded"
              />
              <div className="mt-2 text-sm text-green-700 text-center font-medium">
                {t('bulk.image_uploaded')}
              </div>
              <button
                onClick={() => {
                  setSelectedImageUrl('');
                }}
                className="absolute top-2 right-2 p-1 bg-red-500 text-white rounded-full hover:bg-red-600 transition"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
          )}

          {!selectedImageUrl && (
            <div className="border-2 border-dashed border-green-300 rounded-lg p-8 text-center text-gray-500 bg-green-50">
              <svg className="w-12 h-12 mx-auto mb-2 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
              </svg>
              <p className="text-sm text-gray-700 font-medium mb-2">{t('bulk.upload_new_image_hint')}</p>
              <p className="text-xs text-gray-600">{t('bulk.upload_from_computer')}</p>
            </div>
          )}
        </div>
      )}

      {/* From Parent Mode */}
      {assignMode === 'from-parent' && (
        <div className="space-y-4">
          {isLoadingParents ? (
            <div className="flex items-center justify-center py-8">
              <LoadingSpinner size="lg" />
            </div>
          ) : parentProducts && parentProducts.length > 0 ? (
            <div className="space-y-4">
              <p className="text-sm text-gray-600">
                {t('bulk.select_parent_image_hint')}
              </p>
              
              {parentProducts.map((parent: ParentProduct) => (
                <div key={parent.id} className="border border-gray-300 rounded-lg p-4 bg-gray-50">
                  <h4 className="font-semibold text-gray-900 mb-3">{parent.name}</h4>
                  
                  {parent.images.length > 0 ? (
                    <div className="grid grid-cols-3 gap-3">
                      {parent.images.map((image) => (
                        <button
                          key={image.id}
                          onClick={() => handleParentImageSelect(image.id, image.url)}
                          className={`relative aspect-square rounded-lg overflow-hidden border-2 transition ${
                            selectedParentImage === image.id
                              ? 'border-indigo-500 ring-2 ring-indigo-200'
                              : 'border-gray-300 hover:border-indigo-300'
                          }`}
                        >
                          <img
                            src={image.thumbnail}
                            alt={image.alt}
                            className="w-full h-full object-cover"
                          />
                          {selectedParentImage === image.id && (
                            <div className="absolute inset-0 bg-indigo-500 bg-opacity-20 flex items-center justify-center">
                              <svg className="w-8 h-8 text-white" fill="currentColor" viewBox="0 0 20 20">
                                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                              </svg>
                            </div>
                          )}
                        </button>
                      ))}
                    </div>
                  ) : (
                    <p className="text-sm text-gray-500 italic">{t('bulk.no_parent_images')}</p>
                  )}
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-8 text-gray-500">
              <svg className="w-12 h-12 mx-auto mb-2 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
              </svg>
              <p className="text-sm">{t('bulk.no_parent_products')}</p>
            </div>
          )}
        </div>
      )}

      {/* Remove Mode */}
      {assignMode === 'remove' && (
        <div className="bg-red-50 border-2 border-red-200 rounded-lg p-6">
          <div className="flex items-start gap-3">
            <div className="flex-shrink-0">
              <svg className="w-6 h-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
              </svg>
            </div>
            <div className="flex-1">
              <h4 className="font-semibold text-red-900 mb-2">
                {t('bulk.remove_images_warning_title')}
              </h4>
              <p className="text-sm text-red-700 mb-4">
                {t('bulk.remove_images_warning', { count: variationIds.length })}
              </p>
              <button
                onClick={handleRemoveImages}
                className="px-4 py-2 bg-red-600 text-white rounded-lg font-semibold hover:bg-red-700 transition flex items-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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                </svg>
                {t('bulk.confirm_remove_images')}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Info Box */}
      <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
        <div className="flex items-start gap-3">
          <svg className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" 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>
          <div className="text-sm text-blue-800">
            <p className="font-semibold mb-1">{t('bulk.image_tips_title')}</p>
            <ul className="list-disc list-inside space-y-1 text-blue-700">
              <li>{t('bulk.image_tip_1')}</li>
              <li>{t('bulk.image_tip_2')}</li>
              <li>{t('bulk.image_tip_3')}</li>
              <li>{t('bulk.image_tip_4')}</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  );
}
