import { useState, useEffect, useCallback, useRef } from 'react';
import {
  X,
  Search,
  Zap,
  UserPlus,
  Mail,
  FileText,
  MessageSquare,
  ArrowRight,
  Info,
  PlusCircle,
  Link,
  type LucideIcon,
} from 'lucide-react';
import { ServiceIcon } from './ServiceIcon';
import { useTriggers, useActions, useIntegrations } from '../context/DataContext';
import { Input } from './ui/input';
import { Button } from './ui/button';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from './ui/tooltip';
import { cn } from '../lib/utils';
import { ConnectionManagerDialog } from './ConnectionManagerDialog';
import { useCategorizedItems, TriggerAction } from '../hooks/useCategorizedItems';
import { useConnectionManager } from '../hooks/useConnectionManager';
import { __, sprintf } from '@/lib/i18n';

interface AppSelectorPanelProps {
  type: 'trigger' | 'action';
  onSelect: (item: TriggerAction) => void;
  onClose: () => void;
}

// Icon mapping
const iconMap: Record<string, LucideIcon> = {
  UserPlus,
  FileText,
  Mail,
  MessageSquare,
  Zap,
};

/**
 * AppSelectorPanel - Zapier-style inline app/action selector
 * Displays as a centered modal with searchable grid
 */
export function AppSelectorPanel({ type, onSelect, onClose }: AppSelectorPanelProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [focusedIndex, setFocusedIndex] = useState(-1);
  const scrollContainerRef = useRef<HTMLDivElement>(null);
  const itemRefs = useRef<Map<number, HTMLButtonElement | HTMLDivElement>>(new Map());

  // Get data from shared context
  const {
    triggers,
    loading: triggersLoading,
    error: triggersError,
    refetch: refetchTriggers,
  } = useTriggers();
  const {
    actions,
    loading: actionsLoading,
    error: actionsError,
    refetch: refetchActions,
  } = useActions();
  const { integrations, refetch: refetchIntegrations } = useIntegrations();

  // Categorize items by availability status
  const { filteredItems, availableItems, notConnectedItems, gatedItems } = useCategorizedItems({
    type,
    triggers,
    actions,
    searchQuery,
  });

  // Connection dialog state management
  const {
    connectionDialogOpen,
    connectionDialogIntegration,
    handleNotConnectedClick,
    handleConnectionsChange,
    setConnectionDialogOpen,
  } = useConnectionManager({
    integrations,
    refetchActions,
    refetchIntegrations,
  });

  // Combine all items for keyboard navigation (in display order)
  const allItems = [...availableItems, ...notConnectedItems, ...gatedItems];

  // Select appropriate loading/error state based on type
  const isLoading = type === 'trigger' ? triggersLoading : actionsLoading;
  const error = type === 'trigger' ? triggersError : actionsError;

  // Handle keyboard navigation (Escape, Arrow keys, Enter)
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Don't interfere with typing in the search input
      const target = e.target as HTMLElement;
      const isSearchInput = target.tagName === 'INPUT';

      if (e.key === 'Escape') {
        onClose();
        return;
      }

      // Only handle navigation keys when not typing (or allow in input for up/down)
      if (e.key === 'ArrowDown' || e.key === 'ArrowRight') {
        e.preventDefault();
        setFocusedIndex((prev) => (prev === -1 ? 0 : Math.min(prev + 1, allItems.length - 1)));
      } else if (e.key === 'ArrowUp' || e.key === 'ArrowLeft') {
        e.preventDefault();
        setFocusedIndex((prev) => (prev === -1 ? allItems.length - 1 : Math.max(prev - 1, 0)));
      } else if (
        e.key === 'Enter' &&
        !isSearchInput &&
        focusedIndex !== -1 &&
        allItems[focusedIndex]
      ) {
        e.preventDefault();
        const item = allItems[focusedIndex];
        // Handle different item types
        if (item.isAvailable && (!item.requiresConnection || item.isConnected)) {
          onSelect(item);
        } else if (item.isAvailable && item.requiresConnection && !item.isConnected) {
          handleNotConnectedClick(item);
        } else if (!item.isAvailable && item.installUrl) {
          window.open(item.installUrl, '_blank', 'noopener,noreferrer');
        }
      }
    };
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [onClose, allItems, focusedIndex, onSelect, handleNotConnectedClick]);

  // Reset focused index when search changes
  useEffect(() => {
    setFocusedIndex(-1);
  }, [searchQuery]);

  // Scroll focused item into view
  useEffect(() => {
    const focusedElement = itemRefs.current.get(focusedIndex);
    if (focusedElement && scrollContainerRef.current) {
      focusedElement.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
    }
  }, [focusedIndex]);

  // Handle backdrop click
  const handleBackdropClick = useCallback(
    (e: React.MouseEvent) => {
      if (e.target === e.currentTarget) {
        onClose();
      }
    },
    [onClose],
  );

  // Retry fetching
  const handleRetry = useCallback(async () => {
    if (type === 'trigger') {
      await refetchTriggers();
    } else {
      await refetchActions();
    }
  }, [type, refetchTriggers, refetchActions]);

  // Helper to get global index for an item (used for focus tracking)
  const getGlobalIndex = useCallback(
    (item: (typeof allItems)[0]) => allItems.findIndex((i) => i.id === item.id),
    [allItems],
  );

  // Helper to check if an item is focused
  const isFocused = useCallback(
    (item: (typeof allItems)[0]) => getGlobalIndex(item) === focusedIndex,
    [getGlobalIndex, focusedIndex],
  );

  // Helper to set ref for an item
  const setItemRef = useCallback(
    (item: (typeof allItems)[0], el: HTMLButtonElement | HTMLDivElement | null) => {
      const index = getGlobalIndex(item);
      if (el) {
        itemRefs.current.set(index, el);
      } else {
        itemRefs.current.delete(index);
      }
    },
    [getGlobalIndex],
  );

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center"
      onClick={handleBackdropClick}
    >
      {/* Backdrop */}
      <div className="absolute inset-0 bg-black/20" />

      {/* Panel */}
      <div className="relative bg-white rounded-xl shadow-2xl w-[700px] max-h-[80vh] flex flex-col border border-slate-200">
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-200">
          <div>
            <h2 className="text-lg font-semibold text-slate-900">
              {type === 'trigger' ? __('Choose a Trigger') : __('Choose an Action')}
            </h2>
            <p className="text-sm text-slate-500">
              {type === 'trigger'
                ? __('Select an event that starts your workflow')
                : __('Select an action to perform')}
            </p>
          </div>
          <Button
            variant="ghost"
            size="icon"
            onClick={onClose}
            className="text-slate-500 hover:text-slate-900"
          >
            <X className="w-5 h-5" />
          </Button>
        </div>

        {/* Search */}
        <div className="px-6 py-3 border-b border-slate-200">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
            <Input
              placeholder={type === 'trigger' ? __('Search triggers...') : __('Search actions...')}
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10"
              autoFocus
            />
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 min-h-0 overflow-auto" ref={scrollContainerRef}>
          <div className="p-4 pb-2">
            {isLoading ? (
              <div className="grid grid-cols-2 gap-3">
                {Array.from({ length: 6 }).map((_, i) => (
                  <div
                    key={i}
                    className="flex items-center gap-3 py-3 px-4 rounded-lg border border-slate-200 animate-pulse"
                  >
                    <div className="w-9 h-9 rounded-lg bg-slate-200 flex-shrink-0" />
                    <div className="flex-1 h-4 bg-slate-200 rounded" />
                    <div className="w-3.5 h-3.5 rounded-full bg-slate-100 flex-shrink-0" />
                  </div>
                ))}
              </div>
            ) : error ? (
              <div className="text-center py-16">
                <p className="text-sm text-red-600 mb-3">{error}</p>
                <Button variant="outline" size="sm" onClick={handleRetry} className="text-cyan-600">
                  {__('Retry')}
                </Button>
              </div>
            ) : filteredItems.length === 0 ? (
              <div className="text-center py-16">
                <p className="text-sm text-slate-500">
                  {type === 'trigger' ? __('No triggers found') : __('No actions found')}
                </p>
                <p className="text-xs text-slate-400 mt-1">
                  {__('Try a different search term or category')}
                </p>
              </div>
            ) : (
              <TooltipProvider delayDuration={300}>
                <div className="space-y-6">
                  {/* Available Items Section */}
                  {availableItems.length > 0 && (
                    <div>
                      <h3 className="text-sm font-semibold text-slate-900 mb-3">
                        {type === 'trigger' ? __('Available Triggers') : __('Available Actions')}
                      </h3>
                      <div className="grid grid-cols-2 gap-3">
                        {availableItems.map((item) => {
                          const Icon = iconMap[item.icon] || Zap;
                          const focused = isFocused(item);
                          return (
                            <button
                              key={item.id}
                              ref={(el) => setItemRef(item, el)}
                              onClick={() => onSelect(item)}
                              className={cn(
                                'relative flex items-center gap-3 py-3 px-4 rounded-lg border transition-all text-left group',
                                focused
                                  ? 'border-cyan-500 bg-cyan-50 ring-2 ring-cyan-500 ring-offset-1'
                                  : 'border-slate-200 hover:border-cyan-600 hover:bg-cyan-50',
                              )}
                            >
                              <div
                                className={cn(
                                  'w-9 h-9 rounded-lg flex items-center justify-center flex-shrink-0',
                                  type === 'trigger' ? 'bg-success/10' : 'bg-cyan-600/10',
                                )}
                              >
                                {item.integration ? (
                                  <ServiceIcon
                                    service={item.integration}
                                    size={18}
                                    fallback={<Icon className="w-4 h-4" />}
                                  />
                                ) : (
                                  <Icon
                                    className={cn(
                                      'w-4 h-4',
                                      type === 'trigger' ? 'text-success' : 'text-cyan-600',
                                    )}
                                  />
                                )}
                              </div>
                              <p className="flex-1 font-medium text-slate-900 group-hover:text-cyan-600 line-clamp-2">
                                {item.name}
                              </p>
                              <Tooltip>
                                <TooltipTrigger asChild>
                                  <span
                                    className="flex-shrink-0 cursor-help"
                                    onClick={(e) => e.stopPropagation()}
                                  >
                                    <Info className="w-3.5 h-3.5 text-slate-400 hover:text-cyan-600 transition-colors" />
                                  </span>
                                </TooltipTrigger>
                                <TooltipContent side="bottom" className="max-w-xs">
                                  <p>{item.description}</p>
                                </TooltipContent>
                              </Tooltip>
                              <ArrowRight className="w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity text-cyan-600 flex-shrink-0" />
                            </button>
                          );
                        })}
                      </div>
                    </div>
                  )}

                  {/* Connection Required Section */}
                  {notConnectedItems.length > 0 && (
                    <div>
                      <div className="mb-3">
                        <h3 className="text-sm font-semibold text-amber-600">
                          {__('Connection Required')}
                        </h3>
                        <p className="text-xs text-slate-400 mt-0.5">
                          {__('Connect your account to use these actions')}
                        </p>
                      </div>
                      <div className="grid grid-cols-2 gap-3">
                        {notConnectedItems.map((item) => {
                          const Icon = iconMap[item.icon] || Zap;
                          const focused = isFocused(item);
                          return (
                            <Tooltip key={item.id}>
                              <TooltipTrigger asChild>
                                <button
                                  ref={(el) => setItemRef(item, el)}
                                  onClick={() => handleNotConnectedClick(item)}
                                  className={cn(
                                    'relative flex items-center gap-3 py-3 px-4 rounded-lg border transition-all text-left group',
                                    focused
                                      ? 'border-amber-500 bg-amber-50 ring-2 ring-amber-500 ring-offset-1'
                                      : 'border-amber-200 bg-amber-50/50 hover:border-amber-400 hover:bg-amber-50',
                                  )}
                                >
                                  <div
                                    className={cn(
                                      'w-9 h-9 rounded-lg flex items-center justify-center flex-shrink-0 opacity-70',
                                      type === 'trigger' ? 'bg-success/10' : 'bg-cyan-600/10',
                                    )}
                                  >
                                    {item.integration ? (
                                      <ServiceIcon
                                        service={item.integration}
                                        size={18}
                                        fallback={<Icon className="w-4 h-4" />}
                                      />
                                    ) : (
                                      <Icon
                                        className={cn(
                                          'w-4 h-4',
                                          type === 'trigger' ? 'text-success' : 'text-cyan-600',
                                        )}
                                      />
                                    )}
                                  </div>
                                  <p className="flex-1 font-medium text-amber-700 group-hover:text-amber-800 line-clamp-2">
                                    {item.name}
                                  </p>
                                  <Tooltip>
                                    <TooltipTrigger asChild>
                                      <span
                                        className="flex-shrink-0 cursor-help"
                                        onClick={(e) => e.stopPropagation()}
                                      >
                                        <Info className="w-3.5 h-3.5 text-slate-400 hover:text-amber-600 transition-colors" />
                                      </span>
                                    </TooltipTrigger>
                                    <TooltipContent side="bottom" className="max-w-xs">
                                      <p>{item.description}</p>
                                    </TooltipContent>
                                  </Tooltip>
                                  <Tooltip>
                                    <TooltipTrigger asChild>
                                      <span
                                        className="flex-shrink-0 p-0.5 rounded hover:bg-amber-100 transition-colors cursor-pointer"
                                        onClick={(e) => {
                                          e.stopPropagation();
                                          handleNotConnectedClick(item);
                                        }}
                                      >
                                        <Link className="w-4 h-4 text-amber-600 hover:text-amber-700" />
                                      </span>
                                    </TooltipTrigger>
                                    <TooltipContent side="top">
                                      <p>{__('Connect account')}</p>
                                    </TooltipContent>
                                  </Tooltip>
                                </button>
                              </TooltipTrigger>
                              <TooltipContent side="top" className="max-w-xs">
                                <p>
                                  {sprintf(
                                    __('Click to connect your %s account'),
                                    item.integration || '',
                                  )}
                                </p>
                              </TooltipContent>
                            </Tooltip>
                          );
                        })}
                      </div>
                    </div>
                  )}

                  {/* Gated Items Section */}
                  {gatedItems.length > 0 && (
                    <div>
                      <div className="mb-3">
                        <h3 className="text-sm font-semibold text-slate-500">
                          {__('External Plugin Required')}
                        </h3>
                        <p className="text-xs text-slate-400 mt-0.5">
                          {__('Install these plugins to unlock')}
                        </p>
                      </div>
                      <div className="grid grid-cols-2 gap-3">
                        {gatedItems.map((item) => {
                          const Icon = iconMap[item.icon] || Zap;
                          const focused = isFocused(item);
                          const handleInstallClick = (e: React.MouseEvent) => {
                            e.stopPropagation();
                            e.preventDefault();
                            if (item.installUrl) {
                              // Open plugin install/purchase page in new tab
                              window.open(item.installUrl, '_blank', 'noopener,noreferrer');
                            }
                          };
                          return (
                            <Tooltip key={item.id}>
                              <TooltipTrigger asChild>
                                <div
                                  ref={(el) => setItemRef(item, el)}
                                  className={cn(
                                    'relative flex items-center gap-3 py-3 px-4 rounded-lg border transition-all text-left',
                                    focused
                                      ? 'border-slate-400 bg-slate-100 ring-2 ring-slate-400 ring-offset-1'
                                      : 'border-slate-200 bg-slate-50',
                                  )}
                                >
                                  <div
                                    className={cn(
                                      'w-9 h-9 rounded-lg flex items-center justify-center flex-shrink-0 grayscale',
                                      type === 'trigger' ? 'bg-success/10' : 'bg-cyan-600/10',
                                    )}
                                  >
                                    {item.integration ? (
                                      <ServiceIcon
                                        service={item.integration}
                                        size={18}
                                        fallback={<Icon className="w-4 h-4" />}
                                      />
                                    ) : (
                                      <Icon
                                        className={cn(
                                          'w-4 h-4',
                                          type === 'trigger' ? 'text-success' : 'text-cyan-600',
                                        )}
                                      />
                                    )}
                                  </div>
                                  <p className="flex-1 font-medium text-slate-500 line-clamp-2">
                                    {item.name}
                                  </p>
                                  <Tooltip>
                                    <TooltipTrigger asChild>
                                      <span
                                        className="flex-shrink-0 cursor-help"
                                        onClick={(e) => e.stopPropagation()}
                                      >
                                        <Info className="w-3.5 h-3.5 text-slate-400 hover:text-slate-500 transition-colors" />
                                      </span>
                                    </TooltipTrigger>
                                    <TooltipContent side="bottom" className="max-w-xs">
                                      <p>{item.description}</p>
                                    </TooltipContent>
                                  </Tooltip>
                                  {item.installUrl ? (
                                    <Tooltip>
                                      <TooltipTrigger asChild>
                                        <button
                                          onClick={handleInstallClick}
                                          className="flex-shrink-0 p-0.5 rounded hover:bg-slate-200 transition-colors cursor-pointer"
                                          aria-label={
                                            item.pluginType === 'paid'
                                              ? 'Purchase plugin'
                                              : 'Install plugin'
                                          }
                                        >
                                          <PlusCircle className="w-4 h-4 text-cyan-600 hover:text-cyan-700" />
                                        </button>
                                      </TooltipTrigger>
                                      <TooltipContent side="top">
                                        <p>
                                          {item.pluginType === 'paid'
                                            ? __('Purchase plugin')
                                            : __('Install plugin')}
                                        </p>
                                      </TooltipContent>
                                    </Tooltip>
                                  ) : (
                                    <PlusCircle className="flex-shrink-0 w-4 h-4 text-slate-400" />
                                  )}
                                </div>
                              </TooltipTrigger>
                              <TooltipContent side="top" className="max-w-xs">
                                <p>{item.availabilityReason}</p>
                              </TooltipContent>
                            </Tooltip>
                          );
                        })}
                      </div>
                    </div>
                  )}
                </div>
              </TooltipProvider>
            )}
          </div>
        </div>

        {/* Footer */}
        <div className="px-6 py-3 border-t border-slate-200 bg-slate-50">
          <div className="flex items-center justify-between">
            <p className="text-xs text-slate-500">
              {filteredItems.length} {type === 'trigger' ? __('triggers') : __('actions')}
              {searchQuery && (
                <span className="text-slate-400">
                  {' '}
                  {__('matching')} "{searchQuery}"
                </span>
              )}
            </p>
            <p className="text-xs text-slate-400 space-x-2">
              <span>
                <kbd className="px-1 py-0.5 bg-white border border-slate-200 rounded text-[10px] font-mono">
                  ↑↓
                </kbd>{' '}
                {__('navigate')}
              </span>
              <span>·</span>
              <span>
                <kbd className="px-1 py-0.5 bg-white border border-slate-200 rounded text-[10px] font-mono">
                  Enter
                </kbd>{' '}
                {__('select')}
              </span>
              <span>·</span>
              <span>
                <kbd className="px-1 py-0.5 bg-white border border-slate-200 rounded text-[10px] font-mono">
                  Esc
                </kbd>{' '}
                {__('close')}
              </span>
            </p>
          </div>
        </div>
      </div>

      {/* Connection Manager Dialog */}
      <ConnectionManagerDialog
        open={connectionDialogOpen}
        onOpenChange={setConnectionDialogOpen}
        integration={connectionDialogIntegration}
        onConnectionsChange={handleConnectionsChange}
      />
    </div>
  );
}

export default AppSelectorPanel;
