import { useState, useEffect, useCallback, useRef } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { Search, SlidersHorizontal, ChevronDown, Loader2 } from 'lucide-react'
import { cn } from '@/lib/utils'
import { PageMeta } from '@/components/common/PageMeta'
import { BrandLogo } from '@/components/common/BrandLogo'
import { FlowTemplateCard } from '@/components/public/FlowTemplateCard'
import { ScriptTemplateCard } from '@/components/public/ScriptTemplateCard'
import { TemplateDetailModal } from '@/components/public/TemplateDetailModal'
import { publicTemplatesApi } from '@/api/publicTemplates'
import type {
  PublicFlowTemplate,
  PublicScriptTemplate,
  PublicFlowDetail,
  PublicScriptDetail,
  PublicGalleryResponse,
} from '@/types'

type SortOption = 'most_used' | 'newest' | 'highest_success'
type TypeFilter = 'all' | 'flows' | 'scripts'

const sortLabels: Record<SortOption, string> = {
  most_used: 'Most Used',
  newest: 'Newest',
  highest_success: 'Highest Success Rate',
}

export default function PublicTemplatesPage() {
  const [searchParams, setSearchParams] = useSearchParams()

  // State
  const [data, setData] = useState<PublicGalleryResponse | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  // Filters
  const [searchQuery, setSearchQuery] = useState(searchParams.get('q') || '')
  const [activeCategory, setActiveCategory] = useState(searchParams.get('category') || '')
  const [typeFilter, setTypeFilter] = useState<TypeFilter>(
    (searchParams.get('type') as TypeFilter) || 'all'
  )
  const [sort, setSort] = useState<SortOption>(
    (searchParams.get('sort') as SortOption) || 'most_used'
  )
  const [sortOpen, setSortOpen] = useState(false)

  // Detail modal
  const [selectedFlow, setSelectedFlow] = useState<PublicFlowDetail | null>(null)
  const [selectedScript, setSelectedScript] = useState<PublicScriptDetail | null>(null)
  const [detailLoading, setDetailLoading] = useState(false)

  const searchTimeout = useRef<ReturnType<typeof setTimeout> | null>(null)

  // Fetch gallery data
  const fetchGallery = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const result = await publicTemplatesApi.listGallery({
        category: activeCategory || undefined,
        type: typeFilter === 'all' ? undefined : typeFilter,
        sort,
      })
      setData(result)
    } catch {
      setError('Failed to load templates. Please try again.')
    } finally {
      setLoading(false)
    }
  }, [activeCategory, typeFilter, sort])

  // Search
  const doSearch = useCallback(async (q: string) => {
    if (!q.trim()) {
      fetchGallery()
      return
    }
    setLoading(true)
    setError(null)
    try {
      const result = await publicTemplatesApi.search(q.trim())
      setData(result)
    } catch {
      setError('Search failed. Please try again.')
    } finally {
      setLoading(false)
    }
  }, [fetchGallery])

  // Initial load & filter changes
  useEffect(() => {
    if (!searchQuery.trim()) {
      fetchGallery()
    }
  }, [fetchGallery, searchQuery])

  // Sync filters to URL
  useEffect(() => {
    const params = new URLSearchParams()
    if (searchQuery) params.set('q', searchQuery)
    if (activeCategory) params.set('category', activeCategory)
    if (typeFilter !== 'all') params.set('type', typeFilter)
    if (sort !== 'most_used') params.set('sort', sort)
    setSearchParams(params, { replace: true })
  }, [searchQuery, activeCategory, typeFilter, sort, setSearchParams])

  // Debounced search
  const handleSearchChange = (value: string) => {
    setSearchQuery(value)
    if (searchTimeout.current) clearTimeout(searchTimeout.current)
    searchTimeout.current = setTimeout(() => {
      doSearch(value)
    }, 400)
  }

  // Open detail modal
  const openFlowDetail = async (template: PublicFlowTemplate) => {
    setDetailLoading(true)
    try {
      const detail = await publicTemplatesApi.getFlowDetail(template.id)
      setSelectedFlow(detail)
    } catch {
      // Fallback to the list data
      setSelectedFlow(template)
    } finally {
      setDetailLoading(false)
    }
  }

  const openScriptDetail = async (template: PublicScriptTemplate) => {
    setDetailLoading(true)
    try {
      const detail = await publicTemplatesApi.getScriptDetail(template.id)
      setSelectedScript(detail)
    } catch {
      // Script list items don't have full detail — show what we have
      setSelectedScript({
        ...template,
        parameters: [],
      })
    } finally {
      setDetailLoading(false)
    }
  }

  const categories = data?.categories || []
  const flows = data?.flow_templates || []
  const scripts = data?.script_templates || []
  const showFlows = typeFilter === 'all' || typeFilter === 'flows'
  const showScripts = typeFilter === 'all' || typeFilter === 'scripts'

  return (
    <>
      <PageMeta
        title="MSP Templates Gallery"
        description="Browse battle-tested troubleshooting flows and scripts built by MSP engineers. Free to explore."
      />

      <div className="min-h-screen bg-background text-foreground">
        {/* Subtle ambient glow */}
        <div
          className="fixed top-[-20%] right-[-10%] w-[600px] h-[600px] rounded-full pointer-events-none"
          style={{
            background: 'radial-gradient(circle, rgba(96,165,250,0.05) 0%, transparent 70%)',
          }}
        />

        {/* Header */}
        <header className="sticky top-0 z-40 border-b border-border bg-background/80">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between">
            <Link to="/" className="flex items-center gap-2.5">
              <BrandLogo size="sm" />
              <span className="font-heading text-lg font-semibold">
                <span className="text-foreground">Resolution</span>
                <span className="text-accent-text">Flow</span>
              </span>
            </Link>
            <div className="flex items-center gap-3">
              <Link
                to="/login"
                className="px-4 py-2 rounded-lg text-sm font-medium text-muted-foreground hover:text-foreground transition-colors"
              >
                Sign In
              </Link>
              <Link
                to="/register"
                className="px-4 py-2 rounded-lg text-sm font-semibold bg-primary text-white hover:brightness-110 active:scale-[0.98] transition-all"
              >
                Sign Up Free
              </Link>
            </div>
          </div>
        </header>

        {/* Hero */}
        <section className="pt-16 pb-10 px-4 sm:px-6 lg:px-8">
          <div className="max-w-3xl mx-auto text-center">
            <h1 className="font-heading text-4xl lg:text-5xl font-bold tracking-tight">
              MSP Troubleshooting{' '}
              <span className="text-accent-text">Templates</span>
            </h1>
            <p className="mt-4 text-lg text-muted-foreground max-w-2xl mx-auto">
              Battle-tested flows and scripts built by MSP engineers. Free to browse, powerful when connected to FlowPilot.
            </p>

            {/* Search */}
            <div className="mt-8 max-w-xl mx-auto relative">
              <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-muted-foreground" />
              <input
                type="text"
                placeholder="Search templates..."
                value={searchQuery}
                onChange={(e) => handleSearchChange(e.target.value)}
                className="w-full pl-12 pr-4 py-3.5 rounded-2xl text-sm bg-card border border-border text-foreground placeholder:text-muted-foreground focus:outline-none focus:border-[rgba(96,165,250,0.3)] transition-colors"
              />
            </div>
          </div>
        </section>

        {/* Filters */}
        <section className="px-4 sm:px-6 lg:px-8 pb-6">
          <div className="max-w-7xl mx-auto space-y-4">
            {/* Category pills */}
            {categories.length > 0 && (
              <div className="flex flex-wrap gap-2">
                <button
                  type="button"
                  onClick={() => setActiveCategory('')}
                  className={cn(
                    'px-3 py-1.5 rounded-full text-sm font-medium border transition-colors',
                    !activeCategory
                      ? 'bg-accent-dim text-foreground border-primary/30'
                      : 'bg-card border-border text-muted-foreground hover:text-foreground hover:border-[rgba(255,255,255,0.12)]'
                  )}
                >
                  All
                </button>
                {categories.map((cat) => (
                  <button
                    key={cat}
                    type="button"
                    onClick={() => setActiveCategory(cat === activeCategory ? '' : cat)}
                    className={cn(
                      'px-3 py-1.5 rounded-full text-sm font-medium border transition-colors',
                      cat === activeCategory
                        ? 'bg-accent-dim text-foreground border-primary/30'
                        : 'bg-card border-border text-muted-foreground hover:text-foreground hover:border-[rgba(255,255,255,0.12)]'
                    )}
                  >
                    {cat}
                  </button>
                ))}
              </div>
            )}

            {/* Type toggle + Sort */}
            <div className="flex items-center justify-between gap-4 flex-wrap">
              {/* Type segmented control */}
              <div className="flex items-center rounded-xl border border-border bg-card overflow-hidden">
                {(['all', 'flows', 'scripts'] as TypeFilter[]).map((t) => (
                  <button
                    key={t}
                    type="button"
                    onClick={() => setTypeFilter(t)}
                    className={cn(
                      'px-4 py-2 text-sm font-medium transition-colors',
                      t === typeFilter
                        ? 'bg-accent-dim text-foreground'
                        : 'text-muted-foreground hover:text-foreground'
                    )}
                  >
                    {t === 'all' ? 'All' : t === 'flows' ? 'Flows' : 'Scripts'}
                  </button>
                ))}
              </div>

              {/* Sort dropdown */}
              <div className="relative">
                <button
                  type="button"
                  onClick={() => setSortOpen(!sortOpen)}
                  className="flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-medium bg-[rgba(255,255,255,0.04)] border border-[rgba(255,255,255,0.06)] text-foreground hover:border-[rgba(255,255,255,0.12)] transition-colors"
                >
                  <SlidersHorizontal className="w-4 h-4 text-muted-foreground" />
                  {sortLabels[sort]}
                  <ChevronDown className={cn('w-4 h-4 text-muted-foreground transition-transform', sortOpen && 'rotate-180')} />
                </button>
                {sortOpen && (
                  <>
                    <div className="fixed inset-0 z-10" onClick={() => setSortOpen(false)} />
                    <div className="absolute right-0 mt-1 z-20 w-52 rounded-xl border border-border bg-card shadow-lg shadow-black/30 overflow-hidden">
                      {(Object.entries(sortLabels) as [SortOption, string][]).map(([key, label]) => (
                        <button
                          key={key}
                          type="button"
                          onClick={() => {
                            setSort(key)
                            setSortOpen(false)
                          }}
                          className={cn(
                            'w-full text-left px-4 py-2.5 text-sm transition-colors',
                            key === sort
                              ? 'bg-accent-dim text-foreground'
                              : 'text-muted-foreground hover:text-foreground hover:bg-[rgba(255,255,255,0.04)]'
                          )}
                        >
                          {label}
                        </button>
                      ))}
                    </div>
                  </>
                )}
              </div>
            </div>
          </div>
        </section>

        {/* Content */}
        <section className="px-4 sm:px-6 lg:px-8 pb-20">
          <div className="max-w-7xl mx-auto">
            {/* Loading */}
            {loading && (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 lg:gap-6">
                {Array.from({ length: 6 }).map((_, i) => (
                  <div key={i} className="card-flat p-5 space-y-3 animate-pulse">
                    <div className="h-5 bg-[rgba(255,255,255,0.06)] rounded w-3/4" />
                    <div className="h-4 bg-[rgba(255,255,255,0.04)] rounded w-full" />
                    <div className="h-4 bg-[rgba(255,255,255,0.04)] rounded w-2/3" />
                    <div className="h-3 bg-[rgba(255,255,255,0.03)] rounded w-1/2 mt-4" />
                  </div>
                ))}
              </div>
            )}

            {/* Error */}
            {!loading && error && (
              <div className="text-center py-16">
                <p className="text-muted-foreground text-sm">{error}</p>
                <button
                  type="button"
                  onClick={fetchGallery}
                  className="mt-4 px-4 py-2 rounded-lg text-sm font-medium bg-primary text-white hover:brightness-110 active:scale-[0.98] transition-all"
                >
                  Try Again
                </button>
              </div>
            )}

            {/* Empty */}
            {!loading && !error && flows.length === 0 && scripts.length === 0 && (
              <div className="text-center py-16">
                <p className="text-muted-foreground text-sm">
                  No templates found. Try a different search or category.
                </p>
              </div>
            )}

            {/* Results */}
            {!loading && !error && (flows.length > 0 || scripts.length > 0) && (
              <div className="space-y-8">
                {/* Flows */}
                {showFlows && flows.length > 0 && (
                  <div>
                    {typeFilter === 'all' && (
                      <h2 className="font-sans text-xs text-[0.625rem] uppercase tracking-[0.1em] text-muted-foreground mb-4">
                        Flows ({data?.total_flows || flows.length})
                      </h2>
                    )}
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 lg:gap-6">
                      {flows.map((flow) => (
                        <FlowTemplateCard
                          key={flow.id}
                          template={flow}
                          onClick={() => openFlowDetail(flow)}
                        />
                      ))}
                    </div>
                  </div>
                )}

                {/* Scripts */}
                {showScripts && scripts.length > 0 && (
                  <div>
                    {typeFilter === 'all' && (
                      <h2 className="font-sans text-xs text-[0.625rem] uppercase tracking-[0.1em] text-muted-foreground mb-4">
                        Scripts ({data?.total_scripts || scripts.length})
                      </h2>
                    )}
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 lg:gap-6">
                      {scripts.map((script) => (
                        <ScriptTemplateCard
                          key={script.id}
                          template={script}
                          onClick={() => openScriptDetail(script)}
                        />
                      ))}
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>
        </section>

        {/* Footer */}
        <footer className="border-t border-border py-8 px-4 sm:px-6 lg:px-8">
          <div className="max-w-7xl mx-auto flex items-center justify-between">
            <Link
              to="/"
              className="text-muted-foreground text-sm hover:text-foreground transition-colors"
            >
              Powered by <span className="font-semibold">ResolutionFlow</span>
            </Link>
            <div className="flex items-center gap-4">
              <Link
                to="/register"
                className="text-sm text-muted-foreground hover:text-foreground transition-colors"
              >
                Get Started
              </Link>
            </div>
          </div>
        </footer>

        {/* Detail loading overlay */}
        {detailLoading && (
          <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
            <Loader2 className="w-8 h-8 text-primary animate-spin" />
          </div>
        )}

        {/* Detail modals */}
        {selectedFlow && (
          <TemplateDetailModal
            type="flow"
            template={selectedFlow}
            onClose={() => setSelectedFlow(null)}
          />
        )}
        {selectedScript && (
          <TemplateDetailModal
            type="script"
            template={selectedScript}
            onClose={() => setSelectedScript(null)}
          />
        )}
      </div>
    </>
  )
}
