import { useState, useEffect, useMemo } from 'react'
import { Search, ChevronDown, ChevronUp, Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/Button'
import { EmptyState } from '@/components/common/EmptyState'
import { StepLibraryIllustration } from '@/components/common/EmptyStateIllustrations'
import { cn } from '@/lib/utils'
import { stepsApi } from '@/api/steps'
import { stepCategoriesApi } from '@/api/stepCategories'
import { StepCard } from './StepCard'
import { StepDetailModal } from './StepDetailModal'
import type { Step, StepListItem, StepCategory, PopularTag, StepListParams } from '@/types/step'

interface StepLibraryBrowserProps {
  onInsert?: (step: Step) => void
  onCreateNew?: () => void
  showCreateButton?: boolean
  onEdit?: (step: StepListItem) => void
  onDelete?: (step: StepListItem) => void
  onSave?: (step: StepListItem) => void
  currentUserId?: string
  refreshKey?: number
}

export function StepLibraryBrowser({ onInsert, onCreateNew, showCreateButton = false, onEdit, onDelete, onSave, currentUserId, refreshKey }: StepLibraryBrowserProps) {
  // State
  const [steps, setSteps] = useState<StepListItem[]>([])
  const [categories, setCategories] = useState<StepCategory[]>([])
  const [popularTags, setPopularTags] = useState<PopularTag[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  // Filters
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedCategoryId, setSelectedCategoryId] = useState<string | undefined>()
  const [selectedStepType, setSelectedStepType] = useState<'decision' | 'action' | 'solution' | undefined>()
  const [minRating, setMinRating] = useState<number | undefined>()
  const [sortBy, setSortBy] = useState<'recent' | 'popular' | 'highest_rated' | 'most_used'>('recent')
  const [selectedTag, setSelectedTag] = useState<string | undefined>()

  // UI state
  const [previewStepId, setPreviewStepId] = useState<string | null>(null)
  const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>({})
  const [retryCount, setRetryCount] = useState(0)

  // Load initial data
  useEffect(() => {
    const loadInitialData = async () => {
      setIsLoading(true)
      setError(null)
      try {
        const [categoriesData, tagsData] = await Promise.all([
          stepCategoriesApi.list(),
          stepsApi.getPopularTags()
        ])
        setCategories(categoriesData.filter(c => c.is_active))
        setPopularTags(tagsData.slice(0, 10)) // Show top 10 tags
      } catch (err) {
        console.error('Failed to load initial data:', err)
        setError('Failed to load categories and tags')
      } finally {
        setIsLoading(false)
      }
    }

    loadInitialData()
  }, [retryCount])

  // Load steps when filters change
  useEffect(() => {
    const loadSteps = async () => {
      setIsLoading(true)
      setError(null)
      try {
        const params: StepListParams = {
          category_id: selectedCategoryId,
          step_type: selectedStepType,
          min_rating: minRating,
          sort_by: sortBy,
          tags: selectedTag ? [selectedTag] : undefined
        }

        let stepsData: StepListItem[]
        if (searchQuery.trim()) {
          stepsData = await stepsApi.search(searchQuery)
        } else {
          stepsData = await stepsApi.list(params)
        }

        setSteps(stepsData)
      } catch (err) {
        console.error('Failed to load steps:', err)
        setError('Failed to load steps')
      } finally {
        setIsLoading(false)
      }
    }

    loadSteps()
  }, [searchQuery, selectedCategoryId, selectedStepType, minRating, sortBy, selectedTag, refreshKey, retryCount])

  // Group steps by visibility
  const groupedSteps = useMemo(() => {
    return {
      private: steps.filter(s => s.visibility === 'private'),
      team: steps.filter(s => s.visibility === 'team'),
      public: steps.filter(s => s.visibility === 'public')
    }
  }, [steps])

  const toggleSection = (section: string) => {
    setCollapsedSections(prev => ({ ...prev, [section]: !prev[section] }))
  }

  const handlePreview = (step: StepListItem) => {
    setPreviewStepId(step.id)
  }

  const handleInsertFromPreview = (step: Step) => {
    setPreviewStepId(null)
    if (onInsert) {
      onInsert(step)
    }
  }

  const handleInsertFromCard = (stepItem: StepListItem) => {
    if (onInsert) {
      stepsApi.get(stepItem.id).then(onInsert)
    }
  }

  const handleTagClick = (tag: string) => {
    setSelectedTag(selectedTag === tag ? undefined : tag)
  }

  const clearFilters = () => {
    setSearchQuery('')
    setSelectedCategoryId(undefined)
    setSelectedStepType(undefined)
    setMinRating(undefined)
    setSelectedTag(undefined)
  }

  const hasActiveFilters = searchQuery || selectedCategoryId || selectedStepType || minRating || selectedTag

  return (
    <div className="flex h-full flex-col">
      {/* Header - Filters */}
      <div className="space-y-4 border-b border-border p-4">
        {/* Search */}
        <div className="relative">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <input
            type="text"
            placeholder="Search steps..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full rounded-md border border-border bg-card py-2 pl-10 pr-4 text-sm text-foreground placeholder:text-muted-foreground focus:outline-hidden focus:border-primary focus:ring-1 focus:ring-primary/20"
          />
        </div>

        {/* Filter Row */}
        <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
          {/* Category Filter */}
          <select
            aria-label="Filter by category"
            value={selectedCategoryId || ''}
            onChange={(e) => setSelectedCategoryId(e.target.value || undefined)}
            className="rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground focus:outline-hidden focus:border-primary focus:ring-1 focus:ring-primary/20"
          >
            <option value="">All Categories</option>
            {categories.map(cat => (
              <option key={cat.id} value={cat.id}>{cat.name}</option>
            ))}
          </select>

          {/* Type Filter */}
          <select
            aria-label="Filter by step type"
            value={selectedStepType || ''}
            onChange={(e) => setSelectedStepType((e.target.value as 'decision' | 'action' | 'solution') || undefined)}
            className="rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground focus:outline-hidden focus:border-primary focus:ring-1 focus:ring-primary/20"
          >
            <option value="">All Types</option>
            <option value="decision">Decision</option>
            <option value="action">Action</option>
            <option value="solution">Solution</option>
          </select>

          {/* Min Rating Filter */}
          <select
            aria-label="Filter by minimum rating"
            value={minRating?.toString() || ''}
            onChange={(e) => setMinRating(e.target.value ? Number(e.target.value) : undefined)}
            className="rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground focus:outline-hidden focus:border-primary focus:ring-1 focus:ring-primary/20"
          >
            <option value="">Any Rating</option>
            <option value="4">4+ Stars</option>
            <option value="3">3+ Stars</option>
            <option value="2">2+ Stars</option>
          </select>

          {/* Sort By */}
          <select
            aria-label="Sort steps by"
            value={sortBy}
            onChange={(e) => setSortBy(e.target.value as 'recent' | 'popular' | 'highest_rated' | 'most_used')}
            className="rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground focus:outline-hidden focus:border-primary focus:ring-1 focus:ring-primary/20"
          >
            <option value="recent">Most Recent</option>
            <option value="popular">Most Popular</option>
            <option value="highest_rated">Highest Rated</option>
            <option value="most_used">Most Used</option>
          </select>
        </div>

        {/* Popular Tags */}
        {popularTags.length > 0 && (
          <div>
            <div className="mb-2 text-xs font-medium text-muted-foreground">Popular Tags:</div>
            <div className="flex flex-wrap gap-1.5">
              {popularTags.map(tag => (
                <button
                  key={tag.tag}
                  onClick={() => handleTagClick(tag.tag)}
                  className={cn(
                    'rounded-full px-2.5 py-1 text-xs transition-colors',
                    selectedTag === tag.tag
                      ? 'bg-primary text-white'
                      : 'border border-border bg-[var(--color-bg-elevated)] text-muted-foreground hover:text-foreground hover:border-[var(--color-border-hover)]'
                  )}
                >
                  {tag.tag} ({tag.count})
                </button>
              ))}
            </div>
          </div>
        )}

        {/* Clear Filters */}
        {hasActiveFilters && (
          <button
            onClick={clearFilters}
            className="text-sm text-muted-foreground hover:text-foreground hover:underline"
          >
            Clear all filters
          </button>
        )}
      </div>

      {/* Body - Step List */}
      <div className="flex-1 overflow-y-auto p-4">
        {isLoading ? (
          <div className="flex items-center justify-center py-12">
            <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
          </div>
        ) : error ? (
          <div className="rounded-lg border border-red-400/20 bg-red-400/10 p-4 text-center">
            <p className="text-sm text-red-400 mb-3">{error}</p>
            <Button variant="secondary" size="sm" onClick={() => setRetryCount(c => c + 1)}>
              Try again
            </Button>
          </div>
        ) : steps.length === 0 ? (
          hasActiveFilters ? (
            <div className="rounded-lg border border-border bg-accent/50 p-12 text-center">
              <p className="mb-2 text-lg font-medium text-foreground">No steps found</p>
              <p className="text-sm text-muted-foreground">Try adjusting your filters</p>
            </div>
          ) : (
            <EmptyState
              illustration={<StepLibraryIllustration />}
              title="Build your solutions library"
              description="Save proven resolutions from troubleshooting sessions. Your team's knowledge grows with every ticket solved."
              action={
                onCreateNew ? (
                  <Button onClick={onCreateNew}>Browse Steps</Button>
                ) : undefined
              }
              learnMoreLink="/guides/step-library"
            />
          )
        ) : (
          <div className="space-y-6">
            {/* My Steps */}
            {groupedSteps.private.length > 0 && (
              <div>
                <button
                  onClick={() => toggleSection('private')}
                  className="mb-3 flex w-full items-center justify-between"
                >
                  <h3 className="text-sm font-semibold text-foreground">My Steps ({groupedSteps.private.length})</h3>
                  {collapsedSections.private ? (
                    <ChevronDown className="h-4 w-4" />
                  ) : (
                    <ChevronUp className="h-4 w-4" />
                  )}
                </button>
                {!collapsedSections.private && (
                  <div className="grid gap-4 sm:grid-cols-2">
                    {groupedSteps.private.map(step => (
                      <StepCard
                        key={step.id}
                        step={step}
                        onPreview={handlePreview}
                        onInsert={onInsert ? handleInsertFromCard : undefined}
                        onEdit={onEdit}
                        onDelete={onDelete}
                        onSave={onSave}
                        currentUserId={currentUserId}
                      />
                    ))}
                  </div>
                )}
              </div>
            )}

            {/* Team Steps */}
            {groupedSteps.team.length > 0 && (
              <div>
                <button
                  onClick={() => toggleSection('team')}
                  className="mb-3 flex w-full items-center justify-between"
                >
                  <h3 className="text-sm font-semibold text-foreground">Team Steps ({groupedSteps.team.length})</h3>
                  {collapsedSections.team ? (
                    <ChevronDown className="h-4 w-4" />
                  ) : (
                    <ChevronUp className="h-4 w-4" />
                  )}
                </button>
                {!collapsedSections.team && (
                  <div className="grid gap-4 sm:grid-cols-2">
                    {groupedSteps.team.map(step => (
                      <StepCard
                        key={step.id}
                        step={step}
                        onPreview={handlePreview}
                        onInsert={onInsert ? handleInsertFromCard : undefined}
                        onEdit={onEdit}
                        onDelete={onDelete}
                        onSave={onSave}
                        currentUserId={currentUserId}
                      />
                    ))}
                  </div>
                )}
              </div>
            )}

            {/* Community Steps */}
            {groupedSteps.public.length > 0 && (
              <div>
                <button
                  onClick={() => toggleSection('public')}
                  className="mb-3 flex w-full items-center justify-between"
                >
                  <h3 className="text-sm font-semibold text-foreground">Community ({groupedSteps.public.length})</h3>
                  {collapsedSections.public ? (
                    <ChevronDown className="h-4 w-4" />
                  ) : (
                    <ChevronUp className="h-4 w-4" />
                  )}
                </button>
                {!collapsedSections.public && (
                  <div className="grid gap-4 sm:grid-cols-2">
                    {groupedSteps.public.map(step => (
                      <StepCard
                        key={step.id}
                        step={step}
                        onPreview={handlePreview}
                        onInsert={onInsert ? handleInsertFromCard : undefined}
                        onEdit={onEdit}
                        onDelete={onDelete}
                        onSave={onSave}
                        currentUserId={currentUserId}
                      />
                    ))}
                  </div>
                )}
              </div>
            )}
          </div>
        )}
      </div>

      {/* Footer - Optional Create Button */}
      {showCreateButton && onCreateNew && (
        <div className="border-t border-border p-4">
          <Button onClick={onCreateNew} className="w-full">
            + Create New Step
          </Button>
        </div>
      )}

      {/* Preview Modal */}
      {previewStepId && (
        <StepDetailModal
          stepId={previewStepId}
          onClose={() => setPreviewStepId(null)}
          onInsert={handleInsertFromPreview}
        />
      )}
    </div>
  )
}
