/**
 * Attribute Manager Component
 * Shows global and local attributes with conversion capability
 */

import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import toast from 'react-hot-toast';
import { useAttributes, useConvertAttribute } from '../../hooks/useAttributes';
import { useLicenseInfo } from '../../hooks/useLicense';
import type { Attribute } from '../../types/attribute';
import { AlertCircle, CheckCircle, Globe, FileText } from 'lucide-react';
import LoadingSpinner from '../ui/LoadingSpinner';
import ProBadge from '../ui/ProBadge';
import UpgradePrompt from '../ui/UpgradePrompt';

export default function AttributeManager() {
  const { t } = useTranslation();
  const { data, isLoading, error } = useAttributes();
  const convertMutation = useConvertAttribute();
  const { data: licenseInfo } = useLicenseInfo();
  
  const [selectedAttribute, setSelectedAttribute] = useState<Attribute | null>(null);
  const [newGlobalName, setNewGlobalName] = useState('');
  const [showConvertModal, setShowConvertModal] = useState(false);
  
  const isLocked = licenseInfo?.tier === 'free';

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-96">
        <LoadingSpinner size="lg" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="text-center">
          <AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
          <p className="text-red-600">{t('attributes.load_error')}</p>
        </div>
      </div>
    );
  }

  const attributes = data?.data?.attributes || [];

  const handleConvertClick = (attribute: Attribute) => {
    setSelectedAttribute(attribute);
    // Auto-generate global name (remove "attribute_" prefix, add "pa_" prefix)
    const cleanName = attribute.name.replace(/^attribute_/, '');
    setNewGlobalName(`pa_${cleanName}`);
    setShowConvertModal(true);
  };

  const handleConvertConfirm = async () => {
    if (!selectedAttribute || !newGlobalName) return;

    const loadingToast = toast.loading(t('attributes.converting'));

    try {
      await convertMutation.mutateAsync({
        local_attribute: selectedAttribute.name,
        new_global_name: newGlobalName,
      });

      toast.dismiss(loadingToast);
      toast.success(
        t('attributes.convert_success', {
          count: selectedAttribute.used_in_variations,
        })
      );

      setShowConvertModal(false);
      setSelectedAttribute(null);
      setNewGlobalName('');
    } catch (err: any) {
      toast.dismiss(loadingToast);

      // 🔒 SECURITY: Handle PRO-only feature error from backend
      if (err.response?.status === 403) {
        toast.error(
          err.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(err.message || t('attributes.convert_error'));
      }
    }
  };

  return (
    <div className="p-6 relative">
      {/* PRO Overlay - Nagyon átlátszó hogy jól látszódjon a háttér tartalom */}
      {isLocked && (
        <div className="absolute inset-0 z-10 bg-white/50 backdrop-blur-[1.0px] flex items-center justify-center p-6">
          <div className="max-w-2xl w-full">
            <UpgradePrompt 
              feature={t('attributes.title')}
              currentLimit={t('attributes.not_available')}
              proLimit={t('attributes.pro_conversion')}
              onUpgrade={() => window.open('https://bytebays.com/variation-hub/', '_blank')}
            />
          </div>
        </div>
      )}
      
      <div className={`${isLocked ? 'pointer-events-none' : ''}`}>
        <div className="mb-6">
          <h1 className="text-2xl font-bold text-gray-900 mb-2 flex items-center gap-3">
            {t('attributes.title')}
            {isLocked && <ProBadge variant="inline" size="md" />}
          </h1>
          <p className="text-gray-600">
            {t('attributes.description')}
          </p>
        </div>

      {/* Warning for local attributes */}
      {attributes.some((attr: Attribute) => !attr.is_global) && (
        <div className="mb-6 p-4 bg-yellow-50 border border-yellow-200 rounded-lg flex items-start gap-3">
          <AlertCircle className="w-5 h-5 text-yellow-600 flex-shrink-0 mt-0.5" />
          <div>
            <h3 className="font-medium text-yellow-900 mb-1">
              {t('attributes.local_warning_title')}
            </h3>
            <p className="text-sm text-yellow-700">
              {t('attributes.local_warning_description')}
            </p>
          </div>
        </div>
      )}

      {/* Attributes Table */}
      <div className="bg-white rounded-lg shadow overflow-hidden">
        <table className="min-w-full divide-y divide-gray-200">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                {t('attributes.name')}
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                {t('attributes.type')}
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                {t('attributes.terms')}
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                {t('attributes.usage')}
              </th>
              <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                {t('attributes.actions')}
              </th>
            </tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {attributes.length === 0 ? (
              <tr>
                <td colSpan={5} className="px-6 py-12 text-center text-gray-500">
                  {t('attributes.no_attributes')}
                </td>
              </tr>
            ) : (
              attributes.map((attribute: Attribute) => (
                <tr key={attribute.name} className="hover:bg-gray-50">
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-2">
                      {attribute.is_global ? (
                        <Globe className="w-4 h-4 text-green-600" />
                      ) : (
                        <FileText className="w-4 h-4 text-orange-600" />
                      )}
                      <div>
                        <div className="font-medium text-gray-900">
                          {attribute.label || attribute.name}
                        </div>
                        <div className="text-xs text-gray-500">
                          {attribute.name}
                        </div>
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    {attribute.is_global ? (
                      <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                        <CheckCircle className="w-3 h-3 mr-1" />
                        {t('attributes.global')}
                      </span>
                    ) : (
                      <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-orange-100 text-orange-800">
                        <AlertCircle className="w-3 h-3 mr-1" />
                        {t('attributes.local')}
                      </span>
                    )}
                  </td>
                  <td className="px-6 py-4">
                    <div className="text-sm text-gray-900">
                      {attribute.is_global ? (
                        <div className="flex flex-wrap gap-1">
                          {attribute.terms.slice(0, 3).map((term) => (
                            <span
                              key={term.id}
                              className="inline-block px-2 py-0.5 bg-gray-100 text-gray-700 rounded text-xs"
                            >
                              {term.name}
                            </span>
                          ))}
                          {attribute.terms.length > 3 && (
                            <span className="inline-block px-2 py-0.5 text-gray-500 text-xs">
                              +{attribute.terms.length - 3} {t('attributes.more')}
                            </span>
                          )}
                        </div>
                      ) : (
                        <div className="flex flex-wrap gap-1">
                          {(attribute.values || []).slice(0, 3).map((value, idx) => (
                            <span
                              key={idx}
                              className="inline-block px-2 py-0.5 bg-gray-100 text-gray-700 rounded text-xs"
                            >
                              {value}
                            </span>
                          ))}
                          {(attribute.values || []).length > 3 && (
                            <span className="inline-block px-2 py-0.5 text-gray-500 text-xs">
                              +{(attribute.values || []).length - 3} {t('attributes.more')}
                            </span>
                          )}
                        </div>
                      )}
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <span className="text-sm text-gray-900">
                      {attribute.used_in_variations} {t('attributes.variations')}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-right">
                    {!attribute.is_global && (
                      <button
                        onClick={() => handleConvertClick(attribute)}
                        disabled={convertMutation.isPending}
                        className="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        {t('attributes.convert_to_global')}
                      </button>
                    )}
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* Convert Confirmation Modal */}
      {showConvertModal && selectedAttribute && (
        <div className="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl max-w-md w-full mx-4">
            <div className="p-6">
              <h3 className="text-lg font-medium text-gray-900 mb-4">
                {t('attributes.convert_modal_title')}
              </h3>
              
              <div className="mb-4">
                <p className="text-sm text-gray-600 mb-2">
                  {t('attributes.convert_modal_description', {
                    name: selectedAttribute.label || selectedAttribute.name,
                    count: selectedAttribute.used_in_variations,
                  })}
                </p>
              </div>

              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  {t('attributes.new_global_name')}
                </label>
                <input
                  type="text"
                  value={newGlobalName}
                  onChange={(e) => setNewGlobalName(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="pa_..."
                />
                <p className="mt-1 text-xs text-gray-500">
                  {t('attributes.global_name_hint')}
                </p>
              </div>

              <div className="flex gap-3 justify-end">
                <button
                  onClick={() => {
                    setShowConvertModal(false);
                    setSelectedAttribute(null);
                    setNewGlobalName('');
                  }}
                  disabled={convertMutation.isPending}
                  className="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50"
                >
                  {t('common.cancel')}
                </button>
                <button
                  onClick={handleConvertConfirm}
                  disabled={convertMutation.isPending || !newGlobalName}
                  className="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
                >
                  {convertMutation.isPending && (
                    <LoadingSpinner size="sm" color="white" />
                  )}
                  {t('attributes.convert_confirm')}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
      </div>
    </div>
  );
}
