import { useState, useEffect, useRef } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import { Search, Plus, Loader2 } from 'lucide-react'
import { treesApi } from '@/api/trees'
import { sessionsApi } from '@/api/sessions'
import type { TreeListItem } from '@/types'
import type { Session } from '@/types/session'
import { getTreeNavigatePath } from '@/lib/routing'
import { usePermissions } from '@/hooks/usePermissions'
import { QuickStats } from '@/components/dashboard/QuickStats'
import { FiltersBar } from '@/components/dashboard/FiltersBar'
import { SectionGroup } from '@/components/dashboard/SectionGroup'
import { SessionsPanel } from '@/components/dashboard/SessionsPanel'
import { TreeListItem as TreeListItemComponent } from '@/components/dashboard/TreeListItem'

function timeAgo(dateStr: string): string {
  const now = Date.now()
  const then = new Date(dateStr).getTime()
  const diffMs = now - then
  const minutes = Math.floor(diffMs / 60000)
  if (minutes < 1) return 'just now'
  if (minutes < 60) return `${minutes}m ago`
  const hours = Math.floor(minutes / 60)
  if (hours < 24) return `${hours}h ago`
  const days = Math.floor(hours / 24)
  if (days === 1) return 'Yesterday'
  return `${days}d ago`
}

export function QuickStartPage() {
  const navigate = useNavigate()
  const { canCreateTrees } = usePermissions()

  const [query, setQuery] = useState('')
  const [searchResults, setSearchResults] = useState<TreeListItem[]>([])
  const [isSearching, setIsSearching] = useState(false)
  const [showResults, setShowResults] = useState(false)
  const searchRef = useRef<HTMLDivElement>(null)
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)

  const [trees, setTrees] = useState<TreeListItem[]>([])
  const [activeSessions, setActiveSessions] = useState<Session[]>([])
  const [allSessions, setAllSessions] = useState<Session[]>([])
  const [isLoading, setIsLoading] = useState(true)

  const [activeFilter, setActiveFilter] = useState('all')

  // Load data on mount
  useEffect(() => {
    async function loadData() {
      try {
        const [treeList, active, recent] = await Promise.all([
          treesApi.list({ sort_by: 'updated_at' }),
          sessionsApi.list({ completed: false, size: 5 }),
          sessionsApi.list({ size: 10 }),
        ])
        setTrees(treeList)
        setActiveSessions(active)
        setAllSessions(recent)
      } catch (err) {
        console.error('Failed to load dashboard data:', err)
      } finally {
        setIsLoading(false)
      }
    }
    loadData()
  }, [])

  // Debounced search
  useEffect(() => {
    if (debounceRef.current) clearTimeout(debounceRef.current)
    if (query.length < 2) {
      setSearchResults([])
      setShowResults(false)
      setIsSearching(false)
      return
    }
    setIsSearching(true)
    setShowResults(true)
    debounceRef.current = setTimeout(async () => {
      try {
        const results = await treesApi.search(query, 8)
        setSearchResults(results)
      } catch {
        setSearchResults([])
      } finally {
        setIsSearching(false)
      }
    }, 300)
    return () => { if (debounceRef.current) clearTimeout(debounceRef.current) }
  }, [query])

  // Close dropdown on outside click
  useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (searchRef.current && !searchRef.current.contains(e.target as Node)) {
        setShowResults(false)
      }
    }
    document.addEventListener('mousedown', handleClick)
    return () => document.removeEventListener('mousedown', handleClick)
  }, [])

  // Compute stats
  const totalTrees = trees.length
  const openSessions = activeSessions.length
  const todaySessions = allSessions.filter(s => {
    const d = new Date(s.started_at)
    const now = new Date()
    return d.toDateString() === now.toDateString()
  }).length
  const completedSessions = allSessions.filter(s => s.completed_at).length

  // Filter trees
  const filteredTrees = activeFilter === 'all'
    ? trees
    : activeFilter === 'recent'
      ? trees.slice(0, 10)
      : trees

  // Map sessions for SessionsPanel
  const recentSessionItems = allSessions.slice(0, 5).map(s => ({
    id: s.id,
    treeName: s.tree_snapshot?.name || 'Unknown',
    status: (s.completed_at ? 'completed' : 'in_progress') as 'completed' | 'in_progress',
    ticketNumber: s.ticket_number || undefined,
    timeAgo: timeAgo(s.started_at),
  }))

  const filters = [
    { id: 'all', label: 'All' },
    { id: 'recent', label: 'Recently Used' },
    { id: 'my', label: 'My Flows' },
    { id: 'team', label: 'Team Flows' },
  ]

  return (
    <div className="p-6 space-y-6">
      {/* Page Header */}
      <div className="flex items-start justify-between">
        <div>
          <h1 className="font-heading text-[1.375rem] font-bold tracking-tight text-foreground">
            Dashboard
          </h1>
          <p className="mt-1 text-sm text-muted-foreground">
            Welcome back. Here&apos;s what&apos;s happening with your flows.
          </p>
        </div>
        <div className="flex items-center gap-2">
          {canCreateTrees && (
            <Link
              to="/trees/new"
              className="flex items-center gap-2 rounded-lg bg-gradient-brand px-4 py-2 text-sm font-semibold text-white shadow-lg shadow-primary/20 hover:opacity-90 transition-opacity"
            >
              <Plus size={16} />
              Create Flow
            </Link>
          )}
        </div>
      </div>

      {/* Quick Stats */}
      <QuickStats
        stats={[
          { label: 'Active Flows', value: totalTrees, gradient: true },
          { label: 'Sessions Today', value: todaySessions, color: '#f59e0b' },
          { label: 'Open Sessions', value: openSessions, meta: `${completedSessions} completed` },
          { label: 'Docs Generated', value: completedSessions },
        ]}
      />

      {/* Filters */}
      <FiltersBar filters={filters} activeFilter={activeFilter} onFilterChange={setActiveFilter} />

      {/* Search (inline, not hero) */}
      <div ref={searchRef} className="relative">
        <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
        <input
          type="text"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          onFocus={() => query.length >= 2 && setShowResults(true)}
          placeholder="Search flows, sessions, tags…"
          className="w-full rounded-lg border border-border bg-card py-2.5 pl-9 pr-4 text-sm text-foreground placeholder:text-muted-foreground focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20"
        />
        {showResults && (
          <div className="absolute z-10 mt-1 w-full rounded-lg border border-border bg-card shadow-xl overflow-hidden">
            {isSearching ? (
              <div className="flex items-center justify-center py-6">
                <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
              </div>
            ) : searchResults.length === 0 ? (
              <div className="px-4 py-6 text-center text-sm text-muted-foreground">No results found</div>
            ) : (
              <ul className="max-h-72 overflow-y-auto py-1">
                {searchResults.map((tree) => (
                  <li key={tree.id}>
                    <button
                      onClick={() => navigate(getTreeNavigatePath(tree.id, tree.tree_type))}
                      className="w-full px-4 py-3 text-left transition-colors hover:bg-accent"
                    >
                      <div className="text-sm font-medium text-foreground">{tree.name}</div>
                      {tree.description && (
                        <div className="mt-0.5 line-clamp-1 text-xs text-muted-foreground">{tree.description}</div>
                      )}
                    </button>
                  </li>
                ))}
              </ul>
            )}
          </div>
        )}
      </div>

      {/* Recent Sessions */}
      <SessionsPanel sessions={recentSessionItems} delay={150} />

      {/* Tree/Flow List */}
      {isLoading ? (
        <div className="flex justify-center py-12">
          <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
        </div>
      ) : (
        <SectionGroup
          title="All Flows"
          count={filteredTrees.length}
          delay={200}
        >
          {filteredTrees.slice(0, 20).map(tree => (
            <TreeListItemComponent
              key={tree.id}
              id={tree.id}
              name={tree.name}
              description={tree.description}
              treeType={tree.tree_type || 'troubleshooting'}
              category={tree.category_info ? { name: tree.category_info.name, color: undefined } : null}
              tags={tree.tags}
              usageCount={tree.usage_count}
              updatedAt={tree.updated_at}
            />
          ))}
          {filteredTrees.length > 20 && (
            <Link
              to="/trees"
              className="block rounded-lg border border-border bg-card px-4 py-3 text-center text-sm text-muted-foreground hover:text-foreground hover:border-border/80 transition-colors"
            >
              View all {filteredTrees.length} flows →
            </Link>
          )}
        </SectionGroup>
      )}
    </div>
  )
}

export default QuickStartPage
