import React, { useState, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import {
  Package,
  Building,
  ChefHat,
  Wrench,
  ClipboardCheck,
  ShoppingCart,
  Users,
  UserPlus,
  Euro as EuroIcon,
  FileText,
  Factory,
  Search,
  X,
} from 'lucide-react';

export type ItemType =
  | 'inventory'
  | 'supplier'
  | 'recipe'
  | 'equipment'
  | 'quality-template'
  | 'customer-order'
  | 'customer'
  | 'team-member'
  | 'sales-entry'
  | 'purchase-order'
  | 'production-batch';

export interface ItemTypeConfig {
  id: ItemType;
  title: string;
  subtitle: string;
  icon: React.ComponentType<{ className?: string; style?: React.CSSProperties }>;
  badge?: string;
  badgeColor?: string;
  isHighlighted?: boolean;
  category: 'daily' | 'common' | 'setup';
  keywords?: string[];
}

// Base item types with icon and category only - titles/subtitles will be translated
export const ITEM_TYPE_CONFIGS: Record<ItemType, { icon: React.ComponentType<{ className?: string; style?: React.CSSProperties }>; category: 'daily' | 'common' | 'setup'; badgeColor: string }> = {
  'sales-entry': {
    icon: EuroIcon,
    category: 'daily',
    badgeColor: 'bg-gradient-to-r from-amber-100 to-orange-100 text-orange-800 font-semibold',
  },
  'inventory': {
    icon: Package,
    category: 'setup',
    badgeColor: 'bg-blue-100 text-blue-700',
  },
  'supplier': {
    icon: Building,
    category: 'setup',
    badgeColor: 'bg-blue-100 text-blue-700',
  },
  'recipe': {
    icon: ChefHat,
    category: 'common',
    badgeColor: 'bg-green-100 text-green-700',
  },
  'equipment': {
    icon: Wrench,
    category: 'setup',
    badgeColor: 'bg-blue-100 text-blue-700',
  },
  'quality-template': {
    icon: ClipboardCheck,
    category: 'setup',
    badgeColor: 'bg-blue-100 text-blue-700',
  },
  'customer-order': {
    icon: ShoppingCart,
    category: 'daily',
    badgeColor: 'bg-amber-100 text-amber-700',
  },
  'customer': {
    icon: Users,
    category: 'common',
    badgeColor: 'bg-green-100 text-green-700',
  },
  'team-member': {
    icon: UserPlus,
    category: 'setup',
    badgeColor: 'bg-blue-100 text-blue-700',
  },
  'purchase-order': {
    icon: FileText,
    category: 'daily',
    badgeColor: 'bg-amber-100 text-amber-700',
  },
  'production-batch': {
    icon: Factory,
    category: 'daily',
    badgeColor: 'bg-amber-100 text-amber-700',
  },
};

interface ItemTypeSelectorProps {
  onSelect: (itemType: ItemType) => void;
}

export const ItemTypeSelector: React.FC<ItemTypeSelectorProps> = ({ onSelect }) => {
  const { t } = useTranslation('wizards');
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<'all' | 'daily' | 'common' | 'setup'>('all');

  // Build item types with translations
  const itemTypes: ItemTypeConfig[] = useMemo(() => {
    return Object.entries(ITEM_TYPE_CONFIGS).map(([id, config]) => ({
      id: id as ItemType,
      title: t(`itemTypeSelector.items.${id}.title`),
      subtitle: t(`itemTypeSelector.items.${id}.subtitle`),
      icon: config.icon,
      badge: config.category === 'daily'
        ? t('itemTypeSelector.badges.daily')
        : config.category === 'common'
        ? t('itemTypeSelector.badges.common')
        : t('itemTypeSelector.badges.setup'),
      badgeColor: config.badgeColor,
      isHighlighted: id === 'sales-entry',
      category: config.category,
      keywords: t(`itemTypeSelector.items.${id}.keywords`, { returnObjects: true }) as string[],
    }));
  }, [t]);

  // Filter items based on search and category
  const filteredItems = useMemo(() => {
    return itemTypes.filter(item => {
      // Category filter
      if (selectedCategory !== 'all' && item.category !== selectedCategory) {
        return false;
      }

      // Search filter
      if (searchQuery.trim()) {
        const query = searchQuery.toLowerCase();
        const matchesTitle = item.title.toLowerCase().includes(query);
        const matchesSubtitle = item.subtitle.toLowerCase().includes(query);
        const matchesKeywords = item.keywords?.some(keyword => keyword.toLowerCase().includes(query));
        return matchesTitle || matchesSubtitle || matchesKeywords;
      }

      return true;
    });
  }, [itemTypes, searchQuery, selectedCategory]);

  const categoryLabels = {
    all: t('itemTypeSelector.categories.all'),
    daily: t('itemTypeSelector.categories.daily'),
    common: t('itemTypeSelector.categories.common'),
    setup: t('itemTypeSelector.categories.setup'),
  };

  return (
    <div className="space-y-6">
      {/* Search and Filters */}
      <div className="space-y-3">
        {/* Search Bar */}
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-[var(--text-tertiary)]" />
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder={t('itemTypeSelector.search.placeholder')}
            className="w-full pl-10 pr-10 py-2.5 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)] placeholder-[var(--text-tertiary)]"
          />
          {searchQuery && (
            <button
              onClick={() => setSearchQuery('')}
              className="absolute right-3 top-1/2 -translate-y-1/2 p-1 hover:bg-[var(--bg-secondary)] rounded transition-colors"
            >
              <X className="w-4 h-4 text-[var(--text-tertiary)]" />
            </button>
          )}
        </div>

        {/* Category Filters */}
        <div className="flex flex-wrap gap-2">
          {(['all', 'daily', 'common', 'setup'] as const).map((category) => (
            <button
              key={category}
              onClick={() => setSelectedCategory(category)}
              className={`px-4 py-2 rounded-full text-sm font-medium transition-all ${
                selectedCategory === category
                  ? 'bg-[var(--color-primary)] text-white shadow-md'
                  : 'bg-[var(--bg-secondary)] text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)]'
              }`}
            >
              {categoryLabels[category]}
            </button>
          ))}
        </div>
      </div>

      {/* Results Count */}
      {(searchQuery || selectedCategory !== 'all') && (
        <div className="text-sm text-[var(--text-secondary)]">
          {filteredItems.length === 0 ? (
            <p className="text-center py-4">{t('itemTypeSelector.search.noResults')}</p>
          ) : (
            <p>{filteredItems.length} {filteredItems.length === 1 ? t('itemTypeSelector.search.resultSingular') : t('itemTypeSelector.search.resultPlural')}</p>
          )}
        </div>
      )}

      {/* Item Type Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 md:gap-4">
        {filteredItems.map((itemType) => {
          const Icon = itemType.icon;
          const isHighlighted = itemType.isHighlighted;

          return (
            <button
              key={itemType.id}
              onClick={() => onSelect(itemType.id)}
              className={`
                group relative p-4 md:p-5 rounded-xl border-2 transition-all duration-200
                hover:shadow-lg hover:-translate-y-1 active:translate-y-0
                focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] focus:ring-offset-2
                ${
                  isHighlighted
                    ? 'border-[var(--color-primary)] bg-gradient-to-br from-[var(--color-primary)]/5 to-[var(--color-primary)]/10 shadow-md'
                    : 'border-[var(--border-secondary)] bg-[var(--bg-primary)] hover:border-[var(--color-primary)]/50'
                }
              `}
            >
              {/* Badge */}
              {itemType.badge && (
                <div className="absolute top-3 right-3">
                  <span className={`px-2 py-1 text-xs rounded-full ${itemType.badgeColor}`}>
                    {itemType.badge}
                  </span>
                </div>
              )}

              {/* Content */}
              <div className="flex items-start gap-4">
                {/* Icon */}
                <div
                  className={`
                    flex-shrink-0 p-3 rounded-lg transition-colors
                    ${
                      isHighlighted
                        ? 'bg-[var(--color-primary)] text-white group-hover:bg-[var(--color-primary)]/90'
                        : 'bg-[var(--bg-secondary)] text-[var(--color-primary)] group-hover:bg-[var(--color-primary)]/10'
                    }
                  `}
                >
                  <Icon className="w-6 h-6" />
                </div>

                {/* Text */}
                <div className="flex-1 text-left pr-16">
                  <h3 className="text-base md:text-lg font-semibold text-[var(--text-primary)] group-hover:text-[var(--color-primary)] transition-colors">
                    {itemType.title}
                  </h3>
                  <p className="text-sm text-[var(--text-secondary)] leading-snug mt-1">
                    {itemType.subtitle}
                  </p>
                </div>
              </div>

              {/* Hover Indicator */}
              <div className="absolute inset-0 rounded-xl ring-2 ring-[var(--color-primary)] opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none" />
            </button>
          );
        })}
      </div>
    </div>
  );
};
