'use client'

import { useEffect, useState } from 'react'
import { useParams } from 'next/navigation'
import { api } from '@/lib/api'
import { Header } from '@/components/Header'
import { Footer } from '@/components/Footer'
import {
  Shield,
  CheckCircle,
  Clock,
  DollarSign,
  Mail,
  User,
  Building,
  Phone,
  MessageSquare,
  Send,
  Loader2,
  AlertCircle,
  Sparkles,
  TrendingUp,
  Globe,
  Calendar,
  ExternalLink,
} 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
  seller_member_since: string | null
}

export default function BuyDomainPage() {
  const params = useParams()
  const slug = params.slug as string

  const [listing, setListing] = useState<Listing | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  
  // Inquiry form state
  const [showForm, setShowForm] = useState(false)
  const [submitting, setSubmitting] = useState(false)
  const [submitted, setSubmitted] = useState(false)
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    company: '',
    message: '',
    offer_amount: '',
  })

  useEffect(() => {
    loadListing()
  }, [slug])

  const loadListing = async () => {
    setLoading(true)
    setError(null)
    try {
      const data = await api.request<Listing>(`/listings/${slug}`)
      setListing(data)
    } catch (err: any) {
      setError(err.message || 'Listing not found')
    } finally {
      setLoading(false)
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setSubmitting(true)
    
    try {
      await api.request(`/listings/${slug}/inquire`, {
        method: 'POST',
        body: JSON.stringify({
          ...formData,
          offer_amount: formData.offer_amount ? parseFloat(formData.offer_amount) : null,
        }),
      })
      setSubmitted(true)
    } catch (err: any) {
      setError(err.message || 'Failed to submit inquiry')
    } finally {
      setSubmitting(false)
    }
  }

  const formatPrice = (price: number, currency: string) => {
    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'
    if (score >= 60) return 'text-amber-400'
    return 'text-foreground-muted'
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="w-6 h-6 border-2 border-accent border-t-transparent rounded-full animate-spin" />
      </div>
    )
  }

  if (error || !listing) {
    return (
      <div className="min-h-screen bg-background">
        <Header />
        <main className="pt-32 pb-20 px-4">
          <div className="max-w-2xl mx-auto text-center">
            <AlertCircle className="w-16 h-16 text-foreground-muted mx-auto mb-6" />
            <h1 className="text-2xl font-display text-foreground mb-4">Domain Not Available</h1>
            <p className="text-foreground-muted mb-8">
              This listing may have been sold, removed, or doesn't exist.
            </p>
            <Link
              href="/buy"
              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"
            >
              Browse Listings
            </Link>
          </div>
        </main>
        <Footer />
      </div>
    )
  }

  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-5xl mx-auto">
          {/* Domain Hero */}
          <div className="text-center mb-12 sm:mb-16 animate-fade-in">
            {listing.is_verified && (
              <div className="inline-flex items-center gap-2 px-4 py-2 bg-accent/10 text-accent text-sm font-medium rounded-full mb-6">
                <Shield className="w-4 h-4" />
                Verified Owner
              </div>
            )}
            
            <h1 className="font-display text-[2.5rem] sm:text-[4rem] md:text-[5rem] lg:text-[6rem] leading-[0.95] tracking-[-0.03em] text-foreground mb-6">
              {listing.domain}
            </h1>
            
            {listing.title && (
              <p className="text-xl sm:text-2xl text-foreground-muted max-w-2xl mx-auto mb-8">
                {listing.title}
              </p>
            )}

            {/* Price Badge */}
            <div className="inline-flex items-center gap-4 px-6 py-4 bg-background-secondary/50 border border-border rounded-2xl">
              {listing.asking_price ? (
                <>
                  <span className="text-sm text-foreground-muted uppercase tracking-wider">
                    {listing.price_type === 'fixed' ? 'Price' : 'Asking'}
                  </span>
                  <span className="text-3xl sm:text-4xl font-display text-foreground">
                    {formatPrice(listing.asking_price, listing.currency)}
                  </span>
                  {listing.price_type === 'negotiable' && (
                    <span className="text-sm text-accent bg-accent/10 px-2 py-1 rounded">
                      Negotiable
                    </span>
                  )}
                </>
              ) : (
                <>
                  <DollarSign className="w-6 h-6 text-accent" />
                  <span className="text-2xl font-display text-foreground">Make an Offer</span>
                </>
              )}
            </div>
          </div>

          <div className="grid lg:grid-cols-3 gap-8">
            {/* Main Content */}
            <div className="lg:col-span-2 space-y-8">
              {/* Description */}
              {listing.description && (
                <div className="p-6 bg-background-secondary/30 border border-border rounded-2xl animate-slide-up">
                  <h2 className="text-lg font-medium text-foreground mb-4 flex items-center gap-2">
                    <MessageSquare className="w-5 h-5 text-accent" />
                    About This Domain
                  </h2>
                  <p className="text-foreground-muted whitespace-pre-line">
                    {listing.description}
                  </p>
                </div>
              )}

              {/* Pounce Valuation */}
              {listing.pounce_score && listing.estimated_value && (
                <div className="p-6 bg-gradient-to-br from-accent/10 to-accent/5 border border-accent/20 rounded-2xl animate-slide-up">
                  <h2 className="text-lg font-medium text-foreground mb-4 flex items-center gap-2">
                    <Sparkles className="w-5 h-5 text-accent" />
                    Pounce Valuation
                  </h2>
                  <div className="grid sm:grid-cols-2 gap-6">
                    <div>
                      <p className="text-sm text-foreground-muted mb-1">Domain Score</p>
                      <p className={clsx("text-4xl font-display", getScoreColor(listing.pounce_score))}>
                        {listing.pounce_score}
                        <span className="text-lg text-foreground-muted">/100</span>
                      </p>
                    </div>
                    <div>
                      <p className="text-sm text-foreground-muted mb-1">Estimated Value</p>
                      <p className="text-4xl font-display text-foreground">
                        {formatPrice(listing.estimated_value, listing.currency)}
                      </p>
                    </div>
                  </div>
                  <p className="mt-4 text-xs text-foreground-subtle">
                    Valuation based on domain length, TLD, keywords, and market data.
                  </p>
                </div>
              )}

              {/* Trust Indicators */}
              <div className="grid sm:grid-cols-3 gap-4 animate-slide-up">
                <div className="p-4 bg-background-secondary/30 border border-border rounded-xl flex items-center gap-3">
                  <div className="w-10 h-10 bg-accent/10 rounded-lg flex items-center justify-center">
                    <Shield className="w-5 h-5 text-accent" />
                  </div>
                  <div>
                    <p className="text-sm font-medium text-foreground">
                      {listing.is_verified ? 'Verified' : 'Pending'}
                    </p>
                    <p className="text-xs text-foreground-muted">Ownership</p>
                  </div>
                </div>
                
                <div className="p-4 bg-background-secondary/30 border border-border rounded-xl flex items-center gap-3">
                  <div className="w-10 h-10 bg-foreground/5 rounded-lg flex items-center justify-center">
                    <Globe className="w-5 h-5 text-foreground-muted" />
                  </div>
                  <div>
                    <p className="text-sm font-medium text-foreground">
                      .{listing.domain.split('.').pop()}
                    </p>
                    <p className="text-xs text-foreground-muted">Extension</p>
                  </div>
                </div>
                
                {listing.seller_member_since && (
                  <div className="p-4 bg-background-secondary/30 border border-border rounded-xl flex items-center gap-3">
                    <div className="w-10 h-10 bg-foreground/5 rounded-lg flex items-center justify-center">
                      <Calendar className="w-5 h-5 text-foreground-muted" />
                    </div>
                    <div>
                      <p className="text-sm font-medium text-foreground">
                        {new Date(listing.seller_member_since).getFullYear()}
                      </p>
                      <p className="text-xs text-foreground-muted">Member Since</p>
                    </div>
                  </div>
                )}
              </div>
            </div>

            {/* Sidebar - Contact Form */}
            <div className="lg:col-span-1">
              <div className="sticky top-32 p-6 bg-background-secondary/30 border border-border rounded-2xl animate-slide-up">
                {submitted ? (
                  <div className="text-center py-8">
                    <CheckCircle className="w-16 h-16 text-accent mx-auto mb-4" />
                    <h3 className="text-lg font-medium text-foreground mb-2">Inquiry Sent!</h3>
                    <p className="text-sm text-foreground-muted">
                      The seller will respond to your message directly.
                    </p>
                  </div>
                ) : showForm ? (
                  <form onSubmit={handleSubmit} className="space-y-4">
                    <h3 className="text-lg font-medium text-foreground mb-4">Contact Seller</h3>
                    
                    <div>
                      <label className="block text-sm text-foreground-muted mb-1">Name *</label>
                      <div className="relative">
                        <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-foreground-subtle" />
                        <input
                          type="text"
                          required
                          value={formData.name}
                          onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                          className="w-full pl-10 pr-4 py-3 bg-background border border-border rounded-xl text-foreground placeholder:text-foreground-subtle focus:outline-none focus:border-accent"
                          placeholder="Your name"
                        />
                      </div>
                    </div>
                    
                    <div>
                      <label className="block text-sm text-foreground-muted mb-1">Email *</label>
                      <div className="relative">
                        <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-foreground-subtle" />
                        <input
                          type="email"
                          required
                          value={formData.email}
                          onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                          className="w-full pl-10 pr-4 py-3 bg-background border border-border rounded-xl text-foreground placeholder:text-foreground-subtle focus:outline-none focus:border-accent"
                          placeholder="your@email.com"
                        />
                      </div>
                    </div>
                    
                    <div>
                      <label className="block text-sm text-foreground-muted mb-1">Phone</label>
                      <div className="relative">
                        <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-foreground-subtle" />
                        <input
                          type="tel"
                          value={formData.phone}
                          onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                          className="w-full pl-10 pr-4 py-3 bg-background border border-border rounded-xl text-foreground placeholder:text-foreground-subtle focus:outline-none focus:border-accent"
                          placeholder="+1 (555) 000-0000"
                        />
                      </div>
                    </div>
                    
                    <div>
                      <label className="block text-sm text-foreground-muted mb-1">Company</label>
                      <div className="relative">
                        <Building className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-foreground-subtle" />
                        <input
                          type="text"
                          value={formData.company}
                          onChange={(e) => setFormData({ ...formData, company: e.target.value })}
                          className="w-full pl-10 pr-4 py-3 bg-background border border-border rounded-xl text-foreground placeholder:text-foreground-subtle focus:outline-none focus:border-accent"
                          placeholder="Your company"
                        />
                      </div>
                    </div>
                    
                    {listing.allow_offers && (
                      <div>
                        <label className="block text-sm text-foreground-muted mb-1">Your Offer</label>
                        <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"
                            value={formData.offer_amount}
                            onChange={(e) => setFormData({ ...formData, offer_amount: e.target.value })}
                            className="w-full pl-10 pr-4 py-3 bg-background border border-border rounded-xl text-foreground placeholder:text-foreground-subtle focus:outline-none focus:border-accent"
                            placeholder="Amount in USD"
                          />
                        </div>
                      </div>
                    )}
                    
                    <div>
                      <label className="block text-sm text-foreground-muted mb-1">Message *</label>
                      <textarea
                        required
                        rows={4}
                        value={formData.message}
                        onChange={(e) => setFormData({ ...formData, message: e.target.value })}
                        className="w-full px-4 py-3 bg-background border border-border rounded-xl text-foreground placeholder:text-foreground-subtle focus:outline-none focus:border-accent resize-none"
                        placeholder="I'm interested in acquiring this domain..."
                      />
                    </div>
                    
                    <button
                      type="submit"
                      disabled={submitting}
                      className="w-full flex items-center justify-center gap-2 px-6 py-3 bg-accent text-background font-medium rounded-xl hover:bg-accent-hover transition-all disabled:opacity-50"
                    >
                      {submitting ? (
                        <>
                          <Loader2 className="w-5 h-5 animate-spin" />
                          Sending...
                        </>
                      ) : (
                        <>
                          <Send className="w-5 h-5" />
                          Send Inquiry
                        </>
                      )}
                    </button>
                    
                    <button
                      type="button"
                      onClick={() => setShowForm(false)}
                      className="w-full text-sm text-foreground-muted hover:text-foreground transition-colors"
                    >
                      Cancel
                    </button>
                  </form>
                ) : (
                  <div className="text-center">
                    <h3 className="text-lg font-medium text-foreground mb-2">Interested?</h3>
                    <p className="text-sm text-foreground-muted mb-6">
                      Contact the seller directly through Pounce.
                    </p>
                    <button
                      onClick={() => setShowForm(true)}
                      className="w-full flex items-center justify-center gap-2 px-6 py-3 bg-accent text-background font-medium rounded-xl hover:bg-accent-hover transition-all"
                    >
                      <Mail className="w-5 h-5" />
                      Contact Seller
                    </button>
                    
                    {listing.allow_offers && listing.asking_price && (
                      <p className="mt-4 text-xs text-foreground-subtle">
                        Price is negotiable. Make an offer!
                      </p>
                    )}
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Powered by Pounce */}
          <div className="mt-16 text-center animate-fade-in">
            <p className="text-sm text-foreground-subtle flex items-center justify-center gap-2">
              <img src="/pounce_puma.png" alt="Pounce" className="w-5 h-5 opacity-50" />
              Marketplace powered by Pounce
            </p>
          </div>
        </div>
      </main>

      <Footer />
    </div>
  )
}

