/**
 * InlineSalePriceEditor Component
 * 
 * Inline dropdown editor for sale price with date pickers
 * Full keyboard navigation support
 */

import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';

interface Props {
  currentPrice: string;
  dateFrom: string | null;
  dateTo: string | null;
  onSave: (price: string, dateFrom: string, dateTo: string) => void;
  onCancel: () => void;
  position: { top: number; left: number; width: number; showAbove: boolean };
}

export default function InlineSalePriceEditor({ 
  currentPrice, 
  dateFrom, 
  dateTo, 
  onSave, 
  onCancel,
  position 
}: Props) {
  const { t } = useTranslation();
  const [price, setPrice] = useState(currentPrice || '');
  const [from, setFrom] = useState(dateFrom || '');
  const [to, setTo] = useState(dateTo || '');
  const priceInputRef = useRef<HTMLInputElement>(null);
  const fromInputRef = useRef<HTMLInputElement>(null);
  const toInputRef = useRef<HTMLInputElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // Auto-focus price input with delay to prevent AG Grid from stealing focus
    const focusTimer = setTimeout(() => {
      if (priceInputRef.current) {
        priceInputRef.current.focus();
        priceInputRef.current.select();
        console.log('[InlineSalePriceEditor] Auto-focus + select applied');
      }
    }, 50); // Small delay to let AG Grid settle

    // Click outside to close
    const handleClickOutside = (e: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        onCancel();
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      clearTimeout(focusTimer);
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [onCancel]);

  const handleKeyDown = (e: React.KeyboardEvent, field: 'price' | 'from' | 'to') => {
    if (e.key === 'Enter') {
      e.preventDefault();
      
      // Tab navigation with Enter
      if (field === 'price' && fromInputRef.current) {
        fromInputRef.current.focus();
      } else if (field === 'from' && toInputRef.current) {
        toInputRef.current.focus();
      } else {
        // Save on final Enter
        handleSave();
      }
    } else if (e.key === 'Escape') {
      e.preventDefault();
      onCancel();
    } else if (e.key === 'Tab') {
      // Allow natural tab navigation
      // Don't prevent default
    }
  };

  const handleSave = () => {
    onSave(price, from, to);
  };

  return (
    <>
      {/* Backdrop overlay */}
      <div className="fixed inset-0 z-40" onClick={onCancel} />
      
      {/* Inline dropdown editor */}
      <div
        ref={containerRef}
        className="fixed z-50 bg-white rounded-lg shadow-2xl border-2 border-indigo-500"
        style={{
          top: `${position.top}px`,
          left: `${position.left}px`,
          minWidth: `${Math.max(position.width, 340)}px`,
          maxWidth: '420px',
        }}
      >
        {/* Arrow pointing up or down */}
        {position.showAbove ? (
          // Arrow pointing DOWN (when dropdown is above cell)
          <div 
            className="absolute -bottom-2 left-8 w-4 h-4 bg-white border-r-2 border-b-2 border-indigo-500 transform rotate-45"
          />
        ) : (
          // Arrow pointing UP (when dropdown is below cell)
          <div 
            className="absolute -top-2 left-8 w-4 h-4 bg-white border-l-2 border-t-2 border-indigo-500 transform rotate-45"
          />
        )}

        <div className="p-4 space-y-3">
          {/* Header */}
          <div className="flex items-center justify-between pb-2 border-b border-gray-200">
            <h4 className="text-sm font-bold text-gray-900 flex items-center gap-2">
              <svg className="w-4 h-4 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              {t('sale_price')}
            </h4>
            <button
              onClick={onCancel}
              className="text-gray-400 hover:text-gray-600 transition"
              title={t('common.close')}
            >
              <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>

          {/* Price Input */}
          <div>
            <label className="block text-xs font-semibold text-gray-700 mb-1.5">
              {t('sale_price')}
            </label>
            <div className="relative">
              <input
                ref={priceInputRef}
                type="text"
                value={price}
                onChange={(e) => setPrice(e.target.value.replace(/[^\d]/g, ''))}
                onKeyDown={(e) => handleKeyDown(e, 'price')}
                placeholder="0"
                className="w-full pl-3 pr-10 py-2.5 border-2 border-gray-300 rounded-lg focus:border-orange-500 focus:ring-2 focus:ring-orange-200 transition text-base font-mono font-semibold text-orange-600"
              />
              <span className="absolute right-3 top-1/2 -translate-y-1/2 text-sm font-semibold text-gray-500">
                Ft
              </span>
            </div>
          </div>

          {/* Date From */}
          <div>
            <label className="block text-xs font-semibold text-gray-700 mb-1.5">
              {t('bulk.sale_date_from')} <span className="text-gray-400 text-xs">({t('bulk.optional')})</span>
            </label>
            <input
              ref={fromInputRef}
              type="date"
              value={from}
              onChange={(e) => setFrom(e.target.value)}
              onKeyDown={(e) => handleKeyDown(e, 'from')}
              className="w-full px-3 py-2.5 border-2 border-gray-300 rounded-lg focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition text-sm"
            />
          </div>

          {/* Date To */}
          <div>
            <label className="block text-xs font-semibold text-gray-700 mb-1.5">
              {t('bulk.sale_date_to')} <span className="text-gray-400 text-xs">({t('bulk.optional')})</span>
            </label>
            <input
              ref={toInputRef}
              type="date"
              value={to}
              onChange={(e) => setTo(e.target.value)}
              onKeyDown={(e) => handleKeyDown(e, 'to')}
              className="w-full px-3 py-2.5 border-2 border-gray-300 rounded-lg focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition text-sm"
            />
          </div>

          {/* Actions */}
          <div className="flex gap-2 pt-2">
            <button
              onClick={onCancel}
              className="flex-1 px-3 py-2 bg-gray-100 text-gray-700 rounded-lg text-sm font-semibold hover:bg-gray-200 transition"
            >
              {t('common.cancel')}
            </button>
            <button
              onClick={handleSave}
              className="flex-1 px-3 py-2 bg-gradient-to-r from-orange-500 to-red-600 text-white rounded-lg text-sm font-semibold hover:from-orange-600 hover:to-red-700 transition shadow-md"
            >
              {t('saved')}
            </button>
          </div>

          {/* Keyboard hints */}
          <div className="pt-2 border-t border-gray-100">
            <p className="text-xs text-gray-500 text-center">
              💡 <kbd className="px-1.5 py-0.5 bg-gray-100 rounded text-xs font-mono">Enter</kbd> = {t('editor.next_field')} · 
              <kbd className="px-1.5 py-0.5 bg-gray-100 rounded text-xs font-mono ml-1">Esc</kbd> = {t('common.cancel')}
            </p>
          </div>
        </div>
      </div>
    </>
  );
}
