'use client'

import { useEffect, useState } from 'react'
import { useStore } from '@/lib/store'
import { Sidebar } from '@/components/Sidebar'
import { Toast, useToast } from '@/components/Toast'
import { AuctionsTab } from '@/components/hunt/AuctionsTab'
import { DropsTab } from '@/components/hunt/DropsTab'
import { SearchTab } from '@/components/hunt/SearchTab'
import { TrendSurferTab } from '@/components/hunt/TrendSurferTab'
import { BrandableForgeTab } from '@/components/hunt/BrandableForgeTab'
import {
  Eye,
  Gavel,
  Crosshair,
  Zap,
  Target,
  TrendingUp,
  Settings,
  Sparkles,
  Menu,
  Tag,
  Coins,
  Shield,
  LogOut,
  Crown,
  X,
  Briefcase,
  Search,
  Download,
  Flame,
  Wand2,
} from 'lucide-react'
import clsx from 'clsx'
import Link from 'next/link'
import Image from 'next/image'

// ============================================================================
// TYPES
// ============================================================================

type HuntTab = 'auctions' | 'drops' | 'search' | 'trends' | 'forge'

// ============================================================================
// TAB CONFIG
// ============================================================================

const TABS: Array<{ key: HuntTab; label: string; shortLabel: string; icon: any; color: string }> = [
  { key: 'auctions', label: 'Auctions', shortLabel: 'Auctions', icon: Gavel, color: 'accent' },
  { key: 'drops', label: 'Drops', shortLabel: 'Drops', icon: Download, color: 'blue' },
  { key: 'search', label: 'Search', shortLabel: 'Search', icon: Search, color: 'white' },
  { key: 'trends', label: 'Trends', shortLabel: 'Trends', icon: Flame, color: 'orange' },
  { key: 'forge', label: 'Forge', shortLabel: 'Forge', icon: Wand2, color: 'purple' },
]

// ============================================================================
// MAIN PAGE
// ============================================================================

export default function HuntPage() {
  const { user, subscription, logout, checkAuth, domains } = useStore()
  const { toast, showToast, hideToast } = useToast()
  const [tab, setTab] = useState<HuntTab>('auctions')

  // Mobile Menu State
  const [menuOpen, setMenuOpen] = useState(false)

  // Check auth on mount
  useEffect(() => {
    checkAuth()
  }, [checkAuth])

  // Computed
  const availableDomains = domains?.filter((d) => d.is_available) || []
  const totalDomains = domains?.length || 0

  // Nav Items for Mobile Bottom Bar
  const mobileNavItems = [
    { href: '/terminal/hunt', label: 'Hunt', icon: Crosshair, active: true },
    { href: '/terminal/watchlist', label: 'Watch', icon: Eye, active: false },
    { href: '/terminal/portfolio', label: 'Portfolio', icon: Briefcase, active: false },
    { href: '/terminal/intel', label: 'Intel', icon: TrendingUp, active: false },
  ]

  // Full Navigation for Drawer
  const tierName = subscription?.tier_name || subscription?.tier || 'Scout'
  const TierIcon = tierName === 'Tycoon' ? Crown : tierName === 'Trader' ? TrendingUp : Zap

  const drawerNavSections = [
    {
      title: 'Discover',
      items: [
        { href: '/terminal/hunt', label: 'Hunt', icon: Crosshair },
        { href: '/terminal/intel', label: 'Intel', icon: TrendingUp },
      ],
    },
    {
      title: 'Manage',
      items: [
        { href: '/terminal/watchlist', label: 'Watchlist', icon: Eye },
        { href: '/terminal/portfolio', label: 'Portfolio', icon: Briefcase },
        { href: '/terminal/sniper', label: 'Sniper', icon: Target },
      ],
    },
    {
      title: 'Monetize',
      items: [
        { href: '/terminal/yield', label: 'Yield', icon: Coins, isNew: true },
        { href: '/terminal/listing', label: 'For Sale', icon: Tag },
      ],
    },
  ]

  const activeTab = TABS.find((t) => t.key === tab)!

  return (
    <div className="min-h-screen bg-[#020202]">
      {/* Desktop Sidebar */}
      <div className="hidden lg:block">
        <Sidebar />
      </div>

      {/* Main Content */}
      <main className="lg:pl-[240px]">
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* MOBILE HEADER */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <header
          className="lg:hidden sticky top-0 z-40 bg-[#020202]/95 backdrop-blur-md border-b border-white/[0.08]"
          style={{ paddingTop: 'env(safe-area-inset-top)' }}
        >
          <div className="px-4 py-3">
            {/* Top Row */}
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center gap-2">
                <Crosshair className="w-4 h-4 text-accent" />
                <span className="text-[10px] font-mono tracking-[0.2em] text-accent uppercase">Domain Hunt</span>
              </div>
              <div className="text-[10px] font-mono text-white/40">
                {totalDomains} tracked · {availableDomains.length} available
              </div>
            </div>

            {/* Tab Bar - Scrollable */}
            <div className="-mx-4 px-4 overflow-x-auto">
              <div className="flex gap-1 min-w-max pb-1">
                {TABS.map((t) => {
                  const isActive = tab === t.key
                  return (
                    <button
                      key={t.key}
                      onClick={() => setTab(t.key)}
                      className={clsx(
                        'flex items-center gap-1.5 px-3 py-2 border transition-all shrink-0',
                        isActive
                          ? t.color === 'accent'
                            ? 'border-accent/40 bg-accent/10 text-accent'
                            : t.color === 'blue'
                            ? 'border-blue-500/40 bg-blue-500/10 text-blue-400'
                            : t.color === 'orange'
                            ? 'border-orange-500/40 bg-orange-500/10 text-orange-400'
                            : t.color === 'purple'
                            ? 'border-purple-500/40 bg-purple-500/10 text-purple-400'
                            : 'border-white/40 bg-white/10 text-white'
                          : 'border-transparent text-white/40 active:bg-white/5'
                      )}
                    >
                      <t.icon className="w-3.5 h-3.5" />
                      <span className="text-[10px] font-bold uppercase tracking-wider font-mono">{t.shortLabel}</span>
                    </button>
                  )
                })}
              </div>
            </div>
          </div>
        </header>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* DESKTOP HEADER + TAB BAR */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="hidden lg:block px-10 pt-10 pb-6 border-b border-white/[0.08]">
          <div className="flex items-end justify-between gap-6 mb-6">
            <div>
              <div className="flex items-center gap-3 mb-3">
                <Crosshair className="w-5 h-5 text-accent" />
                <span className="text-[10px] font-mono tracking-[0.2em] text-accent uppercase">Discovery Hub</span>
              </div>
              <h1 className="font-display text-[2.5rem] leading-[1] tracking-[-0.02em] text-white">Domain Hunt</h1>
              <p className="text-white/40 text-sm font-mono mt-2 max-w-lg">
                Search domains, browse auctions, discover drops, ride trends, or generate brandables.
              </p>
            </div>

            <div className="flex gap-6">
              <div className="text-right">
                <div className="text-2xl font-bold text-accent font-mono">{totalDomains}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Tracked</div>
              </div>
              <div className="text-right">
                <div className="text-2xl font-bold text-white font-mono">{availableDomains.length}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Available</div>
              </div>
            </div>
          </div>

          {/* Desktop Tab Bar */}
          <div className="flex gap-2">
            {TABS.map((t) => {
              const isActive = tab === t.key
              const colorClasses: Record<string, { active: string; inactive: string }> = {
                accent: { active: 'border-accent bg-accent/10 text-accent', inactive: 'border-white/[0.08] text-white/50 hover:text-white hover:bg-white/[0.02]' },
                blue: { active: 'border-blue-500 bg-blue-500/10 text-blue-400', inactive: 'border-white/[0.08] text-white/50 hover:text-white hover:bg-white/[0.02]' },
                white: { active: 'border-white/40 bg-white/10 text-white', inactive: 'border-white/[0.08] text-white/50 hover:text-white hover:bg-white/[0.02]' },
                orange: { active: 'border-orange-500 bg-orange-500/10 text-orange-400', inactive: 'border-white/[0.08] text-white/50 hover:text-white hover:bg-white/[0.02]' },
                purple: { active: 'border-purple-500 bg-purple-500/10 text-purple-400', inactive: 'border-white/[0.08] text-white/50 hover:text-white hover:bg-white/[0.02]' },
              }
              const classes = colorClasses[t.color] || colorClasses.white

              return (
                <button
                  key={t.key}
                  onClick={() => setTab(t.key)}
                  className={clsx('flex items-center gap-2 px-4 py-2.5 border transition-all', isActive ? classes.active : classes.inactive)}
                >
                  <t.icon className="w-4 h-4" />
                  <span className="text-xs font-bold uppercase tracking-wider">{t.label}</span>
                </button>
              )
            })}
          </div>
        </section>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* TAB CONTENT */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <section className="px-4 lg:px-10 py-4 lg:py-6 pb-28 lg:pb-10">
          {tab === 'auctions' && <AuctionsTab showToast={showToast} />}
          {tab === 'drops' && <DropsTab showToast={showToast} />}
          {tab === 'search' && <SearchTab showToast={showToast} />}
          {tab === 'trends' && <TrendSurferTab showToast={showToast} />}
          {tab === 'forge' && <BrandableForgeTab showToast={showToast} />}
        </section>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* MOBILE BOTTOM NAV */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        <nav
          className="lg:hidden fixed bottom-0 left-0 right-0 z-50 bg-[#020202] border-t border-white/[0.08]"
          style={{ paddingBottom: 'env(safe-area-inset-bottom)' }}
        >
          <div className="flex items-stretch h-14">
            {mobileNavItems.map((item) => (
              <Link
                key={item.href}
                href={item.href}
                className={clsx(
                  'flex-1 flex flex-col items-center justify-center gap-0.5 relative transition-colors',
                  item.active ? 'text-accent' : 'text-white/40 active:text-white/80'
                )}
              >
                {item.active && <div className="absolute top-0 left-1/2 -translate-x-1/2 w-10 h-0.5 bg-accent" />}
                <item.icon className="w-5 h-5" />
                <span className="text-[9px] font-mono uppercase tracking-wider">{item.label}</span>
              </Link>
            ))}

            <button
              onClick={() => setMenuOpen(true)}
              className="flex-1 flex flex-col items-center justify-center gap-0.5 text-white/40 active:text-white/80 transition-all"
            >
              <Menu className="w-5 h-5" />
              <span className="text-[9px] font-mono uppercase tracking-wider">Menu</span>
            </button>
          </div>
        </nav>

        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {/* MOBILE DRAWER */}
        {/* ═══════════════════════════════════════════════════════════════════════ */}
        {menuOpen && (
          <div className="lg:hidden fixed inset-0 z-[100]">
            <div className="absolute inset-0 bg-black/80 animate-in fade-in duration-200" onClick={() => setMenuOpen(false)} />

            <div
              className="absolute top-0 right-0 bottom-0 w-[80%] max-w-[300px] bg-[#0A0A0A] border-l border-white/[0.08] animate-in slide-in-from-right duration-300 flex flex-col"
              style={{ paddingTop: 'env(safe-area-inset-top)', paddingBottom: 'env(safe-area-inset-bottom)' }}
            >
              <div className="flex items-center justify-between p-4 border-b border-white/[0.08]">
                <div className="flex items-center gap-3">
                  <Image src="/pounce-puma.png" alt="Pounce" width={28} height={28} className="object-contain" />
                  <div>
                    <h2 className="text-sm font-bold text-white tracking-wider">POUNCE</h2>
                    <p className="text-[9px] text-white/40 font-mono uppercase tracking-widest">Terminal v1.0</p>
                  </div>
                </div>
                <button
                  onClick={() => setMenuOpen(false)}
                  className="w-8 h-8 flex items-center justify-center border border-white/10 text-white/60 hover:text-white active:bg-white/5 transition-all"
                >
                  <X className="w-4 h-4" />
                </button>
              </div>

              <div className="flex-1 overflow-y-auto py-4">
                {drawerNavSections.map((section) => (
                  <div key={section.title} className="mb-4">
                    <div className="flex items-center gap-2 px-4 mb-2">
                      <div className="w-1 h-3 bg-accent" />
                      <span className="text-[9px] font-bold text-white/30 uppercase tracking-[0.2em]">{section.title}</span>
                    </div>
                    <div>
                      {section.items.map((item: any) => (
                        <Link
                          key={item.href}
                          href={item.href}
                          onClick={() => setMenuOpen(false)}
                          className="flex items-center gap-3 px-4 py-2.5 text-white/60 active:text-white active:bg-white/[0.03] transition-colors border-l-2 border-transparent active:border-accent"
                        >
                          <item.icon className="w-4 h-4 text-white/30" />
                          <span className="text-sm font-medium flex-1">{item.label}</span>
                          {item.isNew && <span className="px-1.5 py-0.5 text-[8px] font-bold bg-accent text-black">NEW</span>}
                        </Link>
                      ))}
                    </div>
                  </div>
                ))}

                <div className="pt-3 border-t border-white/[0.08] mx-4">
                  <Link
                    href="/terminal/settings"
                    onClick={() => setMenuOpen(false)}
                    className="flex items-center gap-3 py-2.5 text-white/50 active:text-white transition-colors"
                  >
                    <Settings className="w-4 h-4" />
                    <span className="text-sm font-medium">Settings</span>
                  </Link>

                  {user?.is_admin && (
                    <Link
                      href="/admin"
                      onClick={() => setMenuOpen(false)}
                      className="flex items-center gap-3 py-2.5 text-amber-500/70 active:text-amber-400 transition-colors"
                    >
                      <Shield className="w-4 h-4" />
                      <span className="text-sm font-medium">Admin</span>
                    </Link>
                  )}
                </div>
              </div>

              <div className="p-4 bg-white/[0.02] border-t border-white/[0.08]">
                <div className="flex items-center gap-3 mb-3">
                  <div className="w-8 h-8 bg-accent/10 border border-accent/20 flex items-center justify-center">
                    <TierIcon className="w-4 h-4 text-accent" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-bold text-white truncate">{user?.name || user?.email?.split('@')[0] || 'User'}</p>
                    <p className="text-[9px] font-mono text-white/40 uppercase tracking-wider">{tierName}</p>
                  </div>
                </div>

                {tierName === 'Scout' && (
                  <Link
                    href="/pricing"
                    onClick={() => setMenuOpen(false)}
                    className="flex items-center justify-center gap-2 w-full py-2.5 bg-accent text-black text-xs font-bold uppercase tracking-wider active:scale-[0.98] transition-all mb-2"
                  >
                    <Sparkles className="w-3 h-3" />
                    Upgrade
                  </Link>
                )}

                <button
                  onClick={() => {
                    logout()
                    setMenuOpen(false)
                  }}
                  className="flex items-center justify-center gap-2 w-full py-2 border border-white/10 text-white/40 text-[10px] font-mono uppercase tracking-wider active:bg-white/5 transition-all"
                >
                  <LogOut className="w-3 h-3" />
                  Sign out
                </button>
              </div>
            </div>
          </div>
        )}
      </main>

      {/* Toast */}
      {toast && <Toast message={toast.message} type={toast.type} onClose={hideToast} />}
    </div>
  )
}
