'use client'

import { useEffect, useState } from 'react'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { Header } from '@/components/Header'
import { Footer } from '@/components/Footer'
import {
  Search,
  Shield,
  DollarSign,
  X,
  Lock,
  Sparkles,
  ChevronUp,
  ChevronDown,
  ExternalLink,
  Eye,
} from 'lucide-react'
import Link from 'next/link'
import clsx from 'clsx'

interface Listing {
  domain: string
  slug: string
  title: string | null
  description: string | null
  asking_price: number | null
  currency: string
  price_type: string
  pounce_score: number | null
  estimated_value: number | null
  is_verified: boolean
  allow_offers: boolean
  public_url: string
  seller_verified: boolean
}

export default function BrowseListingsPage() {
  const { isAuthenticated, checkAuth, isLoading: authLoading } = useStore()
  const [listings, setListings] = useState<Listing[]>([])
  const [loading, setLoading] = useState(true)
  const [searchQuery, setSearchQuery] = useState('')
  const [minPrice, setMinPrice] = useState('')
  const [maxPrice, setMaxPrice] = useState('')
  const [verifiedOnly, setVerifiedOnly] = useState(false)
  const [sortBy, setSortBy] = useState<'newest' | 'price_asc' | 'price_desc' | 'popular'>('newest')

  useEffect(() => {
    loadListings()
  }, [sortBy, verifiedOnly])

  useEffect(() => {
    checkAuth()
  }, [checkAuth])

  const loadListings = async () => {
    setLoading(true)
    try {
      const params = new URLSearchParams()
      params.append('sort_by', sortBy)
      if (verifiedOnly) params.append('verified_only', 'true')
      params.append('limit', '50')
      
      const data = await api.request<Listing[]>(`/listings?${params.toString()}`)
      setListings(data)
    } catch (error) {
      console.error('Failed to load listings:', error)
    } finally {
      setLoading(false)
    }
  }

  const filteredListings = listings.filter(listing => {
    if (searchQuery && !listing.domain.toLowerCase().includes(searchQuery.toLowerCase())) {
      return false
    }
    if (minPrice && listing.asking_price && listing.asking_price < parseFloat(minPrice)) {
      return false
    }
    if (maxPrice && listing.asking_price && listing.asking_price > parseFloat(maxPrice)) {
      return false
    }
    return true
  })

  const formatPrice = (price: number | null, currency: string) => {
    if (!price) return 'Make Offer'
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency,
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
    }).format(price)
  }

  const getScoreColor = (score: number) => {
    if (score >= 80) return 'text-accent bg-accent/10'
    if (score >= 60) return 'text-amber-400 bg-amber-500/10'
    return 'text-foreground-muted bg-foreground/5'
  }

  return (
    <div className="min-h-screen bg-background relative overflow-hidden">
      {/* Background Effects */}
      <div className="fixed inset-0 pointer-events-none">
        <div className="absolute top-[-20%] left-1/2 -translate-x-1/2 w-[1200px] h-[800px] bg-accent/[0.03] rounded-full blur-[120px]" />
        <div className="absolute bottom-[-10%] right-[-10%] w-[600px] h-[600px] bg-accent/[0.02] rounded-full blur-[100px]" />
      </div>

      <Header />

      <main className="relative pt-32 sm:pt-40 pb-20 sm:pb-28 px-4 sm:px-6">
        <div className="max-w-7xl mx-auto">
          {/* Hero Header */}
          <div className="text-center mb-16 sm:mb-20 animate-fade-in">
            <span className="text-sm font-semibold text-accent uppercase tracking-wider">Marketplace</span>
            <h1 className="mt-4 font-display text-[2.5rem] sm:text-[3.5rem] md:text-[4.5rem] lg:text-[5rem] leading-[0.95] tracking-[-0.03em] text-foreground">
              Premium Domains. Direct.
            </h1>
            <p className="mt-5 text-lg sm:text-xl text-foreground-muted max-w-2xl mx-auto">
              Browse verified domains from trusted sellers. No middlemen, no hassle.
            </p>
          </div>

          {/* Search & Filters */}
          <div className="mb-8 animate-slide-up">
            <div className="flex flex-wrap gap-3">
              <div className="relative flex-1 min-w-[200px] max-w-md">
                <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-foreground-subtle" />
                <input
                  type="text"
                  placeholder="Search domains..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full pl-12 pr-10 py-3 bg-background-secondary/50 border border-border rounded-xl
                             text-body text-foreground placeholder:text-foreground-subtle
                             focus:outline-none focus:ring-2 focus:ring-accent/30 focus:border-accent
                             transition-all duration-300"
                />
                {searchQuery && (
                  <button
                    onClick={() => setSearchQuery('')}
                    className="absolute right-4 top-1/2 -translate-y-1/2 p-1 text-foreground-subtle hover:text-foreground"
                  >
                    <X className="w-4 h-4" />
                  </button>
                )}
              </div>
              
              <div className="relative">
                <DollarSign className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-foreground-subtle" />
                <input
                  type="number"
                  placeholder="Min"
                  value={minPrice}
                  onChange={(e) => setMinPrice(e.target.value)}
                  className="w-24 pl-9 pr-2 py-3 bg-background-secondary/50 border border-border rounded-xl
                             text-body text-foreground placeholder:text-foreground-subtle
                             focus:outline-none focus:ring-2 focus:ring-accent/30 focus:border-accent"
                />
              </div>
              
              <div className="relative">
                <DollarSign className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-foreground-subtle" />
                <input
                  type="number"
                  placeholder="Max"
                  value={maxPrice}
                  onChange={(e) => setMaxPrice(e.target.value)}
                  className="w-24 pl-9 pr-2 py-3 bg-background-secondary/50 border border-border rounded-xl
                             text-body text-foreground placeholder:text-foreground-subtle
                             focus:outline-none focus:ring-2 focus:ring-accent/30 focus:border-accent"
                />
              </div>
              
              <button
                onClick={() => setVerifiedOnly(!verifiedOnly)}
                className={clsx(
                  "flex items-center gap-2 px-4 py-3 rounded-xl border transition-all",
                  verifiedOnly
                    ? "bg-accent text-background border-accent"
                    : "bg-background-secondary/50 text-foreground-muted border-border hover:border-accent"
                )}
              >
                <Shield className="w-4 h-4" />
                Verified Only
              </button>
              
              <select
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value as typeof sortBy)}
                className="px-4 py-3 bg-background-secondary/50 border border-border rounded-xl
                           text-body text-foreground cursor-pointer focus:outline-none focus:ring-2 focus:ring-accent/30"
              >
                <option value="newest">Newest First</option>
                <option value="price_asc">Price: Low to High</option>
                <option value="price_desc">Price: High to Low</option>
                <option value="popular">Most Viewed</option>
              </select>
            </div>
          </div>

          {/* Contact gate hint (consistent with /buy/[slug]) */}
          {!authLoading && !isAuthenticated && (
            <div className="mb-8 p-4 border border-accent/20 bg-accent/5 rounded-2xl animate-slide-up">
              <div className="flex items-start gap-3">
                <div className="w-10 h-10 bg-accent/10 border border-accent/20 rounded-xl flex items-center justify-center text-accent shrink-0">
                  <Lock className="w-5 h-5" />
                </div>
                <div className="flex-1">
                  <p className="text-sm font-semibold text-foreground">Contact requires login</p>
                  <p className="text-sm text-foreground-muted mt-1">
                    Listing details are public. To protect sellers from spam, inquiries are only available for logged-in accounts.
                  </p>
                  <div className="mt-3 flex flex-wrap gap-3">
                    <Link
                      href="/login?redirect=/buy"
                      className="inline-flex items-center gap-2 px-4 py-2 bg-accent text-background font-medium rounded-xl hover:bg-accent-hover transition-all"
                    >
                      Login
                    </Link>
                    <Link
                      href="/register?redirect=/buy"
                      className="inline-flex items-center gap-2 px-4 py-2 border border-border bg-background-secondary/30 text-foreground font-medium rounded-xl hover:border-accent/40 transition-all"
                    >
                      Register
                    </Link>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Listings Grid */}
          {loading ? (
            <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
              {Array.from({ length: 6 }).map((_, idx) => (
                <div key={idx} className="animate-pulse p-6 bg-background-secondary/30 border border-border rounded-2xl">
                  <div className="h-8 w-40 bg-background-tertiary rounded mb-4" />
                  <div className="h-4 w-24 bg-background-tertiary rounded mb-6" />
                  <div className="h-10 w-full bg-background-tertiary rounded" />
                </div>
              ))}
            </div>
          ) : filteredListings.length === 0 ? (
            <div className="text-center py-20">
              <Sparkles className="w-16 h-16 text-foreground-subtle mx-auto mb-6" />
              <h2 className="text-xl font-medium text-foreground mb-2">No Listings Found</h2>
              <p className="text-foreground-muted mb-8">
                {searchQuery 
                  ? `No domains match "${searchQuery}"`
                  : 'Be the first to list your domain!'}
              </p>
              <Link
                href="/terminal/listing"
                className="inline-flex items-center gap-2 px-6 py-3 bg-accent text-background font-medium rounded-xl hover:bg-accent-hover transition-all"
              >
                <Sparkles className="w-5 h-5" />
                List Your Domain
              </Link>
            </div>
          ) : (
            <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4 animate-slide-up">
              {filteredListings.map((listing) => (
                <Link
                  key={listing.slug}
                  href={`/buy/${listing.slug}`}
                  className="group p-6 bg-background-secondary/30 border border-border rounded-2xl
                           hover:border-accent/50 hover:bg-background-secondary/50 transition-all duration-300"
                >
                  {/* Header */}
                  <div className="flex items-start justify-between mb-4">
                    <div className="flex-1 min-w-0">
                      <h3 className="font-mono text-lg font-medium text-foreground group-hover:text-accent transition-colors truncate">
                        {listing.domain}
                      </h3>
                      {listing.title && (
                        <p className="text-sm text-foreground-muted truncate mt-1">{listing.title}</p>
                      )}
                    </div>
                    {listing.is_verified && (
                      <div className="shrink-0 ml-2 w-8 h-8 bg-accent/10 rounded-lg flex items-center justify-center">
                        <Shield className="w-4 h-4 text-accent" />
                      </div>
                    )}
                  </div>
                  
                  {/* Score & Price */}
                  <div className="flex items-end justify-between">
                    {listing.pounce_score && (
                      <div className={clsx("px-2 py-1 rounded text-sm font-medium", getScoreColor(listing.pounce_score))}>
                        Score: {listing.pounce_score}
                      </div>
                    )}
                    <div className="text-right">
                      <p className="text-xl font-display text-foreground">
                        {formatPrice(listing.asking_price, listing.currency)}
                      </p>
                      {listing.price_type === 'negotiable' && (
                        <p className="text-xs text-accent">Negotiable</p>
                      )}
                    </div>
                  </div>
                  
                  {/* View CTA */}
                  <div className="mt-4 pt-4 border-t border-border/50 flex items-center justify-between">
                    <div className="text-sm text-foreground-muted">
                      <span className="flex items-center gap-1">
                      <Eye className="w-3 h-3" />
                      View Details
                    </span>
                      {!isAuthenticated && (
                        <span className="mt-1 flex items-center gap-1 text-xs text-foreground-subtle">
                          <Lock className="w-3 h-3" />
                          Login to contact
                        </span>
                      )}
                    </div>
                    <ExternalLink className="w-4 h-4 text-foreground-subtle group-hover:text-accent transition-colors" />
                  </div>
                </Link>
              ))}
            </div>
          )}

          {/* CTA for Sellers */}
          <div className="mt-16 p-8 bg-gradient-to-r from-accent/10 to-accent/5 border border-accent/20 rounded-2xl text-center animate-slide-up">
            <Sparkles className="w-10 h-10 text-accent mx-auto mb-4" />
            <h2 className="text-2xl font-display text-foreground mb-2">Got a domain to sell?</h2>
            <p className="text-foreground-muted mb-6 max-w-xl mx-auto">
              List your domain on Pounce and reach serious buyers. 
              DNS verification ensures only real owners can list.
            </p>
            <Link
              href="/terminal/listing"
              className="inline-flex items-center gap-2 px-6 py-3 bg-accent text-background font-medium rounded-xl hover:bg-accent-hover transition-all"
            >
              List Your Domain
            </Link>
          </div>
        </div>
      </main>

      <Footer />
    </div>
  )
}

