/**
 * CatalogListPanel Component
 *
 * Left sidebar panel displaying a searchable, filterable list of plans and add-ons.
 * Supports filtering by type, status, visibility, and legacy status.
 */

import React, { useState, useMemo } from 'react';
import { Search, Plus, Package, Puzzle, Eye, EyeOff, Archive } from 'lucide-react';
import { Badge } from '../../components/ui';

// =============================================================================
// Types
// =============================================================================

export interface CatalogItem {
  id: number;
  type: 'plan' | 'addon';
  code: string;
  name: string;
  isActive: boolean;
  isPublic: boolean;
  isLegacy: boolean;
  priceMonthly?: number;
  priceYearly?: number;
  subscriberCount?: number;
  stripeProductId?: string;
}

export interface CatalogListPanelProps {
  items: CatalogItem[];
  selectedId: number | null;
  onSelect: (item: CatalogItem) => void;
  onCreatePlan: () => void;
  onCreateAddon: () => void;
  isLoading?: boolean;
}

type TypeFilter = 'all' | 'plan' | 'addon';
type StatusFilter = 'all' | 'active' | 'inactive';
type VisibilityFilter = 'all' | 'public' | 'hidden';
type LegacyFilter = 'all' | 'current' | 'legacy';

// =============================================================================
// Component
// =============================================================================

export const CatalogListPanel: React.FC<CatalogListPanelProps> = ({
  items,
  selectedId,
  onSelect,
  onCreatePlan,
  onCreateAddon,
  isLoading = false,
}) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [typeFilter, setTypeFilter] = useState<TypeFilter>('all');
  const [statusFilter, setStatusFilter] = useState<StatusFilter>('all');
  const [visibilityFilter, setVisibilityFilter] = useState<VisibilityFilter>('all');
  const [legacyFilter, setLegacyFilter] = useState<LegacyFilter>('all');

  // Filter items
  const filteredItems = useMemo(() => {
    return items.filter((item) => {
      // Type filter
      if (typeFilter !== 'all' && item.type !== typeFilter) return false;

      // Status filter
      if (statusFilter === 'active' && !item.isActive) return false;
      if (statusFilter === 'inactive' && item.isActive) return false;

      // Visibility filter
      if (visibilityFilter === 'public' && !item.isPublic) return false;
      if (visibilityFilter === 'hidden' && item.isPublic) return false;

      // Legacy filter
      if (legacyFilter === 'current' && item.isLegacy) return false;
      if (legacyFilter === 'legacy' && !item.isLegacy) return false;

      // Search filter
      if (searchTerm) {
        const term = searchTerm.toLowerCase();
        return (
          item.name.toLowerCase().includes(term) ||
          item.code.toLowerCase().includes(term)
        );
      }

      return true;
    });
  }, [items, typeFilter, statusFilter, visibilityFilter, legacyFilter, searchTerm]);

  const formatPrice = (cents?: number): string => {
    if (cents === undefined || cents === 0) return 'Free';
    return `$${(cents / 100).toFixed(2)}`;
  };

  return (
    <div className="flex flex-col h-full bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700">
      {/* Header with Create buttons */}
      <div className="p-4 border-b border-gray-200 dark:border-gray-700">
        <div className="flex gap-2">
          <button
            onClick={onCreatePlan}
            className="flex-1 inline-flex items-center justify-center gap-2 px-3 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700"
          >
            <Plus className="w-4 h-4" />
            Create Plan
          </button>
          <button
            onClick={onCreateAddon}
            className="flex-1 inline-flex items-center justify-center gap-2 px-3 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700"
          >
            <Plus className="w-4 h-4" />
            Create Add-on
          </button>
        </div>
      </div>

      {/* Search */}
      <div className="p-4 border-b border-gray-200 dark:border-gray-700">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
          <input
            type="text"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            placeholder="Search by name or code..."
            className="w-full pl-10 pr-4 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
          />
        </div>
      </div>

      {/* Filters */}
      <div className="p-4 border-b border-gray-200 dark:border-gray-700 space-y-3">
        <div className="grid grid-cols-2 gap-2">
          <div>
            <label htmlFor="type-filter" className="sr-only">
              Type
            </label>
            <select
              id="type-filter"
              aria-label="Type"
              value={typeFilter}
              onChange={(e) => setTypeFilter(e.target.value as TypeFilter)}
              className="w-full px-2 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
            >
              <option value="all">All Types</option>
              <option value="plan">Base Plans</option>
              <option value="addon">Add-ons</option>
            </select>
          </div>
          <div>
            <label htmlFor="status-filter" className="sr-only">
              Status
            </label>
            <select
              id="status-filter"
              aria-label="Status"
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value as StatusFilter)}
              className="w-full px-2 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
            >
              <option value="all">All Status</option>
              <option value="active">Active</option>
              <option value="inactive">Inactive</option>
            </select>
          </div>
        </div>
        <div className="grid grid-cols-2 gap-2">
          <div>
            <label htmlFor="visibility-filter" className="sr-only">
              Visibility
            </label>
            <select
              id="visibility-filter"
              aria-label="Visibility"
              value={visibilityFilter}
              onChange={(e) => setVisibilityFilter(e.target.value as VisibilityFilter)}
              className="w-full px-2 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
            >
              <option value="all">All Visibility</option>
              <option value="public">Public</option>
              <option value="hidden">Hidden</option>
            </select>
          </div>
          <div>
            <label htmlFor="legacy-filter" className="sr-only">
              Legacy
            </label>
            <select
              id="legacy-filter"
              aria-label="Legacy"
              value={legacyFilter}
              onChange={(e) => setLegacyFilter(e.target.value as LegacyFilter)}
              className="w-full px-2 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
            >
              <option value="all">All Versions</option>
              <option value="current">Current</option>
              <option value="legacy">Legacy</option>
            </select>
          </div>
        </div>
      </div>

      {/* Items List */}
      <div className="flex-1 overflow-y-auto">
        {filteredItems.length === 0 ? (
          <div className="p-8 text-center text-gray-500 dark:text-gray-400">
            <Package className="w-8 h-8 mx-auto mb-2 opacity-50" />
            <p>No items found</p>
            {searchTerm && (
              <p className="text-xs mt-1">Try adjusting your search or filters</p>
            )}
          </div>
        ) : (
          <div className="divide-y divide-gray-200 dark:divide-gray-700">
            {filteredItems.map((item) => (
              <CatalogListItem
                key={`${item.type}-${item.id}`}
                item={item}
                isSelected={selectedId === item.id}
                onSelect={() => onSelect(item)}
                formatPrice={formatPrice}
              />
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

// =============================================================================
// List Item Component
// =============================================================================

interface CatalogListItemProps {
  item: CatalogItem;
  isSelected: boolean;
  onSelect: () => void;
  formatPrice: (cents?: number) => string;
}

const CatalogListItem: React.FC<CatalogListItemProps> = ({
  item,
  isSelected,
  onSelect,
  formatPrice,
}) => {
  return (
    <button
      onClick={onSelect}
      className={`w-full p-4 text-left transition-colors ${
        isSelected
          ? 'bg-blue-50 dark:bg-blue-900/20 border-l-2 border-blue-600'
          : 'hover:bg-gray-50 dark:hover:bg-gray-700/50'
      }`}
    >
      <div className="flex items-start gap-3">
        {/* Icon */}
        <div
          className={`p-2 rounded-lg ${
            item.type === 'plan'
              ? 'bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400'
              : 'bg-purple-100 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400'
          }`}
        >
          {item.type === 'plan' ? (
            <Package className="w-4 h-4" />
          ) : (
            <Puzzle className="w-4 h-4" />
          )}
        </div>

        {/* Content */}
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 flex-wrap">
            <span className="font-medium text-gray-900 dark:text-white truncate">
              {item.name}
            </span>
            <span className="px-1.5 py-0.5 text-xs font-medium bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded">
              {item.code}
            </span>
          </div>

          {/* Badges */}
          <div className="flex items-center gap-1.5 mt-1 flex-wrap">
            {/* Type badge */}
            <span
              className={`px-1.5 py-0.5 text-xs font-medium rounded ${
                item.type === 'plan'
                  ? 'bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400'
                  : 'bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-400'
              }`}
            >
              {item.type === 'plan' ? 'Base' : 'Add-on'}
            </span>

            {/* Status badge */}
            {!item.isActive && (
              <span className="px-1.5 py-0.5 text-xs font-medium bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400 rounded">
                Inactive
              </span>
            )}

            {/* Visibility badge */}
            {!item.isPublic && (
              <span className="px-1.5 py-0.5 text-xs font-medium bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded flex items-center gap-1">
                <EyeOff className="w-3 h-3" />
                Hidden
              </span>
            )}

            {/* Legacy badge */}
            {item.isLegacy && (
              <span className="px-1.5 py-0.5 text-xs font-medium bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 rounded flex items-center gap-1">
                <Archive className="w-3 h-3" />
                Legacy
              </span>
            )}
          </div>

          {/* Price and subscriber count */}
          <div className="flex items-center gap-3 mt-2 text-xs text-gray-500 dark:text-gray-400">
            <span className="font-medium text-gray-900 dark:text-white">
              {formatPrice(item.priceMonthly)}/mo
            </span>
            {item.subscriberCount !== undefined && (
              <span>{item.subscriberCount} subscribers</span>
            )}
          </div>
        </div>
      </div>
    </button>
  );
};
