'use client'

import { useEffect, useState, useMemo, useCallback } from 'react'
import { useSearchParams } from 'next/navigation'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { CommandCenterLayout } from '@/components/CommandCenterLayout'
import { PageContainer, StatCard, Badge, ActionButton } from '@/components/PremiumTable'
import {
  Plus,
  Shield,
  Eye,
  MessageSquare,
  ExternalLink,
  Loader2,
  Trash2,
  CheckCircle,
  AlertCircle,
  Copy,
  RefreshCw,
  DollarSign,
  X,
  Tag,
  Store,
  Sparkles,
} from 'lucide-react'
import Link from 'next/link'
import clsx from 'clsx'

interface Listing {
  id: number
  domain: string
  slug: string
  title: string | null
  description: string | null
  asking_price: number | null
  min_offer: number | null
  currency: string
  price_type: string
  pounce_score: number | null
  estimated_value: number | null
  verification_status: string
  is_verified: boolean
  status: string
  show_valuation: boolean
  allow_offers: boolean
  view_count: number
  inquiry_count: number
  public_url: string
  created_at: string
  published_at: string | null
}

interface VerificationInfo {
  verification_code: string
  dns_record_type: string
  dns_record_name: string
  dns_record_value: string
  instructions: string
  status: string
}

export default function MyListingsPage() {
  const { subscription } = useStore()
  const searchParams = useSearchParams()
  const prefillDomain = searchParams.get('domain')
  
  const [listings, setListings] = useState<Listing[]>([])
  const [loading, setLoading] = useState(true)
  
  // Modals - auto-open if domain is prefilled
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [showVerifyModal, setShowVerifyModal] = useState(false)
  const [selectedListing, setSelectedListing] = useState<Listing | null>(null)
  const [verificationInfo, setVerificationInfo] = useState<VerificationInfo | null>(null)
  const [verifying, setVerifying] = useState(false)
  const [creating, setCreating] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState<string | null>(null)
  
  // Create form
  const [newListing, setNewListing] = useState({
    domain: '',
    title: '',
    description: '',
    asking_price: '',
    price_type: 'negotiable',
    allow_offers: true,
  })

  const loadListings = useCallback(async () => {
    setLoading(true)
    try {
      const data = await api.request<Listing[]>('/listings/my')
      setListings(data)
    } catch (err: any) {
      console.error('Failed to load listings:', err)
    } finally {
      setLoading(false)
    }
  }, [])

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

  // Auto-open create modal if domain is prefilled from portfolio
  useEffect(() => {
    if (prefillDomain) {
      setNewListing(prev => ({ ...prev, domain: prefillDomain }))
      setShowCreateModal(true)
    }
  }, [prefillDomain])

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault()
    setCreating(true)
    setError(null)
    
    try {
      await api.request('/listings', {
        method: 'POST',
        body: JSON.stringify({
          domain: newListing.domain,
          title: newListing.title || null,
          description: newListing.description || null,
          asking_price: newListing.asking_price ? parseFloat(newListing.asking_price) : null,
          price_type: newListing.price_type,
          allow_offers: newListing.allow_offers,
        }),
      })
      setSuccess('Listing created! Now verify ownership to publish.')
      setShowCreateModal(false)
      setNewListing({ domain: '', title: '', description: '', asking_price: '', price_type: 'negotiable', allow_offers: true })
      loadListings()
    } catch (err: any) {
      setError(err.message)
    } finally {
      setCreating(false)
    }
  }

  const handleStartVerification = async (listing: Listing) => {
    setSelectedListing(listing)
    setVerifying(true)
    
    try {
      const info = await api.request<VerificationInfo>(`/listings/${listing.id}/verify-dns`, {
        method: 'POST',
      })
      setVerificationInfo(info)
      setShowVerifyModal(true)
    } catch (err: any) {
      setError(err.message)
    } finally {
      setVerifying(false)
    }
  }

  const handleCheckVerification = async () => {
    if (!selectedListing) return
    setVerifying(true)
    
    try {
      const result = await api.request<{ verified: boolean; message: string }>(
        `/listings/${selectedListing.id}/verify-dns/check`
      )
      
      if (result.verified) {
        setSuccess('Domain verified! You can now publish your listing.')
        setShowVerifyModal(false)
        loadListings()
      } else {
        setError(result.message)
      }
    } catch (err: any) {
      setError(err.message)
    } finally {
      setVerifying(false)
    }
  }

  const handlePublish = async (listing: Listing) => {
    try {
      await api.request(`/listings/${listing.id}`, {
        method: 'PUT',
        body: JSON.stringify({ status: 'active' }),
      })
      setSuccess('Listing published!')
      loadListings()
    } catch (err: any) {
      setError(err.message)
    }
  }

  const handleDelete = async (listing: Listing) => {
    if (!confirm(`Delete listing for ${listing.domain}?`)) return
    
    try {
      await api.request(`/listings/${listing.id}`, { method: 'DELETE' })
      setSuccess('Listing deleted')
      loadListings()
    } catch (err: any) {
      setError(err.message)
    }
  }

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text)
    setSuccess('Copied to clipboard!')
  }

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

  const getStatusBadge = (status: string, isVerified: boolean) => {
    if (status === 'active') return <Badge variant="success">Live</Badge>
    if (status === 'draft' && !isVerified) return <Badge variant="warning">Needs Verification</Badge>
    if (status === 'draft') return <Badge>Draft</Badge>
    if (status === 'sold') return <Badge variant="accent">Sold</Badge>
    return <Badge>{status}</Badge>
  }

  const tier = subscription?.tier || 'scout'
  const limits = { scout: 2, trader: 10, tycoon: 50 }
  const maxListings = limits[tier as keyof typeof limits] || 2

  return (
    <CommandCenterLayout
      title="My Listings"
      subtitle={`Manage your domains for sale • ${listings.length}/${maxListings} slots used`}
      actions={
        <div className="flex items-center gap-3">
          <Link
            href="/buy"
            className="flex items-center gap-2 px-4 py-2 text-foreground-muted text-sm font-medium 
                       border border-border rounded-lg hover:bg-foreground/5 transition-all"
          >
            <Store className="w-4 h-4" />
            Browse Marketplace
          </Link>
          <button
            onClick={() => setShowCreateModal(true)}
            disabled={listings.length >= maxListings}
            className="flex items-center gap-2 px-4 py-2 bg-accent text-background text-sm font-medium rounded-lg
                       hover:bg-accent-hover transition-all disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <Plus className="w-4 h-4" />
            List Domain
          </button>
        </div>
      }
    >
      <PageContainer>
        {/* Messages */}
        {error && (
          <div className="p-4 bg-red-500/10 border border-red-500/20 rounded-xl flex items-center gap-3">
            <AlertCircle className="w-5 h-5 text-red-400" />
            <p className="text-sm text-red-400 flex-1">{error}</p>
            <button onClick={() => setError(null)}><X className="w-4 h-4 text-red-400" /></button>
          </div>
        )}
        
        {success && (
          <div className="p-4 bg-accent/10 border border-accent/20 rounded-xl flex items-center gap-3">
            <CheckCircle className="w-5 h-5 text-accent" />
            <p className="text-sm text-accent flex-1">{success}</p>
            <button onClick={() => setSuccess(null)}><X className="w-4 h-4 text-accent" /></button>
          </div>
        )}

        {/* Stats */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          <StatCard title="My Listings" value={`${listings.length}/${maxListings}`} icon={Tag} />
          <StatCard 
            title="Published" 
            value={listings.filter(l => l.status === 'active').length} 
            icon={CheckCircle} 
            accent 
          />
          <StatCard 
            title="Total Views" 
            value={listings.reduce((sum, l) => sum + l.view_count, 0)} 
            icon={Eye} 
          />
          <StatCard 
            title="Inquiries" 
            value={listings.reduce((sum, l) => sum + l.inquiry_count, 0)} 
            icon={MessageSquare} 
          />
        </div>

        {/* Listings */}
        {loading ? (
          <div className="flex items-center justify-center py-20">
            <Loader2 className="w-6 h-6 text-accent animate-spin" />
          </div>
        ) : listings.length === 0 ? (
          <div className="text-center py-16 bg-background-secondary/30 border border-border rounded-2xl">
            <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 Yet</h2>
            <p className="text-foreground-muted mb-6 max-w-md mx-auto">
              Create your first listing to sell a domain on the Pounce marketplace.
            </p>
            <button
              onClick={() => setShowCreateModal(true)}
              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"
            >
              <Plus className="w-5 h-5" />
              Create Listing
            </button>
          </div>
        ) : (
          <div className="space-y-4">
            {listings.map((listing) => (
              <div
                key={listing.id}
                className="p-5 bg-background-secondary/30 border border-border rounded-2xl hover:border-border-hover transition-all"
              >
                <div className="flex flex-wrap items-start gap-4">
                  {/* Domain Info */}
                  <div className="flex-1 min-w-[200px]">
                    <div className="flex items-center gap-3 mb-2">
                      <h3 className="font-mono text-lg font-medium text-foreground">{listing.domain}</h3>
                      {getStatusBadge(listing.status, listing.is_verified)}
                      {listing.is_verified && (
                        <div className="w-6 h-6 bg-accent/10 rounded flex items-center justify-center" title="Verified">
                          <Shield className="w-3 h-3 text-accent" />
                        </div>
                      )}
                    </div>
                    {listing.title && (
                      <p className="text-sm text-foreground-muted">{listing.title}</p>
                    )}
                  </div>
                  
                  {/* Price */}
                  <div className="text-right">
                    <p className="text-xl font-semibold text-foreground">
                      {formatPrice(listing.asking_price, listing.currency)}
                    </p>
                    {listing.pounce_score && (
                      <p className="text-xs text-foreground-muted">Score: {listing.pounce_score}</p>
                    )}
                  </div>
                  
                  {/* Stats */}
                  <div className="flex items-center gap-4 text-sm text-foreground-muted">
                    <span className="flex items-center gap-1">
                      <Eye className="w-4 h-4" /> {listing.view_count}
                    </span>
                    <span className="flex items-center gap-1">
                      <MessageSquare className="w-4 h-4" /> {listing.inquiry_count}
                    </span>
                  </div>
                  
                  {/* Actions */}
                  <div className="flex items-center gap-2">
                    {!listing.is_verified && (
                      <button
                        onClick={() => handleStartVerification(listing)}
                        disabled={verifying}
                        className="flex items-center gap-1.5 px-3 py-2 bg-amber-500/10 text-amber-400 text-sm font-medium rounded-lg hover:bg-amber-500/20 transition-all"
                      >
                        <Shield className="w-4 h-4" />
                        Verify
                      </button>
                    )}
                    
                    {listing.is_verified && listing.status === 'draft' && (
                      <button
                        onClick={() => handlePublish(listing)}
                        className="flex items-center gap-1.5 px-3 py-2 bg-accent text-background text-sm font-medium rounded-lg hover:bg-accent-hover transition-all"
                      >
                        <CheckCircle className="w-4 h-4" />
                        Publish
                      </button>
                    )}
                    
                    {listing.status === 'active' && (
                      <Link
                        href={`/buy/${listing.slug}`}
                        target="_blank"
                        className="flex items-center gap-1.5 px-3 py-2 bg-foreground/5 text-foreground-muted text-sm font-medium rounded-lg hover:bg-foreground/10 transition-all"
                      >
                        <ExternalLink className="w-4 h-4" />
                        View
                      </Link>
                    )}
                    
                    <button
                      onClick={() => handleDelete(listing)}
                      className="p-2 text-foreground-subtle hover:text-red-400 transition-colors"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </PageContainer>

      {/* Create Modal */}
      {showCreateModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm">
          <div className="w-full max-w-lg bg-background-secondary border border-border rounded-2xl p-6">
            <h2 className="text-xl font-semibold text-foreground mb-6">List Domain for Sale</h2>
            
            <form onSubmit={handleCreate} className="space-y-4">
              <div>
                <label className="block text-sm text-foreground-muted mb-1">Domain *</label>
                <input
                  type="text"
                  required
                  value={newListing.domain}
                  onChange={(e) => setNewListing({ ...newListing, domain: e.target.value })}
                  placeholder="example.com"
                  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"
                />
              </div>
              
              <div>
                <label className="block text-sm text-foreground-muted mb-1">Headline</label>
                <input
                  type="text"
                  value={newListing.title}
                  onChange={(e) => setNewListing({ ...newListing, title: e.target.value })}
                  placeholder="Perfect for AI startups"
                  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"
                />
              </div>
              
              <div>
                <label className="block text-sm text-foreground-muted mb-1">Description</label>
                <textarea
                  rows={3}
                  value={newListing.description}
                  onChange={(e) => setNewListing({ ...newListing, description: e.target.value })}
                  placeholder="Tell potential buyers about this domain..."
                  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"
                />
              </div>
              
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm text-foreground-muted mb-1">Asking Price (USD)</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={newListing.asking_price}
                      onChange={(e) => setNewListing({ ...newListing, asking_price: e.target.value })}
                      placeholder="Leave empty for 'Make Offer'"
                      className="w-full pl-9 pr-4 py-3 bg-background border border-border rounded-xl text-foreground placeholder:text-foreground-subtle focus:outline-none focus:border-accent"
                    />
                  </div>
                </div>
                
                <div>
                  <label className="block text-sm text-foreground-muted mb-1">Price Type</label>
                  <select
                    value={newListing.price_type}
                    onChange={(e) => setNewListing({ ...newListing, price_type: e.target.value })}
                    className="w-full px-4 py-3 bg-background border border-border rounded-xl text-foreground focus:outline-none focus:border-accent"
                  >
                    <option value="negotiable">Negotiable</option>
                    <option value="fixed">Fixed Price</option>
                    <option value="make_offer">Make Offer Only</option>
                  </select>
                </div>
              </div>
              
              <label className="flex items-center gap-3 cursor-pointer">
                <input
                  type="checkbox"
                  checked={newListing.allow_offers}
                  onChange={(e) => setNewListing({ ...newListing, allow_offers: e.target.checked })}
                  className="w-5 h-5 rounded border-border text-accent focus:ring-accent"
                />
                <span className="text-sm text-foreground">Allow buyers to make offers</span>
              </label>
              
              <div className="flex gap-3 pt-4">
                <button
                  type="button"
                  onClick={() => setShowCreateModal(false)}
                  className="flex-1 px-4 py-3 border border-border text-foreground-muted rounded-xl hover:bg-foreground/5 transition-all"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={creating}
                  className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-accent text-background font-medium rounded-xl hover:bg-accent-hover transition-all disabled:opacity-50"
                >
                  {creating ? <Loader2 className="w-5 h-5 animate-spin" /> : <Plus className="w-5 h-5" />}
                  {creating ? 'Creating...' : 'Create'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Verification Modal */}
      {showVerifyModal && verificationInfo && selectedListing && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm">
          <div className="w-full max-w-xl bg-background-secondary border border-border rounded-2xl p-6">
            <h2 className="text-xl font-semibold text-foreground mb-2">Verify Domain Ownership</h2>
            <p className="text-sm text-foreground-muted mb-6">
              Add a DNS TXT record to prove you own <strong>{selectedListing.domain}</strong>
            </p>
            
            <div className="space-y-4">
              <div className="p-4 bg-background rounded-xl border border-border">
                <p className="text-sm text-foreground-muted mb-2">Record Type</p>
                <p className="font-mono text-foreground">{verificationInfo.dns_record_type}</p>
              </div>
              
              <div className="p-4 bg-background rounded-xl border border-border">
                <p className="text-sm text-foreground-muted mb-2">Name / Host</p>
                <div className="flex items-center justify-between">
                  <p className="font-mono text-foreground">{verificationInfo.dns_record_name}</p>
                  <button 
                    onClick={() => copyToClipboard(verificationInfo.dns_record_name)}
                    className="p-2 text-foreground-subtle hover:text-accent transition-colors"
                  >
                    <Copy className="w-4 h-4" />
                  </button>
                </div>
              </div>
              
              <div className="p-4 bg-background rounded-xl border border-border">
                <p className="text-sm text-foreground-muted mb-2">Value</p>
                <div className="flex items-center justify-between">
                  <p className="font-mono text-sm text-foreground break-all">{verificationInfo.dns_record_value}</p>
                  <button 
                    onClick={() => copyToClipboard(verificationInfo.dns_record_value)}
                    className="p-2 text-foreground-subtle hover:text-accent transition-colors shrink-0"
                  >
                    <Copy className="w-4 h-4" />
                  </button>
                </div>
              </div>
              
              <div className="p-4 bg-accent/5 border border-accent/20 rounded-xl">
                <p className="text-sm text-foreground-muted whitespace-pre-line">
                  {verificationInfo.instructions}
                </p>
              </div>
            </div>
            
            <div className="flex gap-3 mt-6">
              <button
                onClick={() => setShowVerifyModal(false)}
                className="flex-1 px-4 py-3 border border-border text-foreground-muted rounded-xl hover:bg-foreground/5 transition-all"
              >
                Close
              </button>
              <button
                onClick={handleCheckVerification}
                disabled={verifying}
                className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-accent text-background font-medium rounded-xl hover:bg-accent-hover transition-all disabled:opacity-50"
              >
                {verifying ? <Loader2 className="w-5 h-5 animate-spin" /> : <RefreshCw className="w-5 h-5" />}
                {verifying ? 'Checking...' : 'Check Verification'}
              </button>
            </div>
          </div>
        </div>
      )}
    </CommandCenterLayout>
  )
}
