'use client'

import { useEffect, useState, useCallback } from 'react'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { Sidebar } from '@/components/Sidebar'
import {
  Plus,
  Target,
  Zap,
  Edit2,
  Trash2,
  Power,
  PowerOff,
  Bell,
  Loader2,
  X,
  AlertCircle,
  CheckCircle,
  DollarSign,
  Crown,
  Eye,
  Gavel,
  TrendingUp,
  Menu,
  Settings,
  Shield,
  LogOut,
  Sparkles,
  Coins,
  Tag,
  Briefcase
} from 'lucide-react'
import clsx from 'clsx'
import Link from 'next/link'
import Image from 'next/image'

// ============================================================================
// INTERFACES
// ============================================================================

interface SniperAlert {
  id: number
  name: string
  description: string | null
  tlds: string | null
  keywords: string | null
  exclude_keywords: string | null
  max_length: number | null
  min_length: number | null
  max_price: number | null
  min_price: number | null
  max_bids: number | null
  ending_within_hours: number | null
  platforms: string | null
  no_numbers: boolean
  no_hyphens: boolean
  exclude_chars: string | null
  notify_email: boolean
  notify_sms: boolean
  is_active: boolean
  matches_count: number
  notifications_sent: number
  last_matched_at: string | null
  created_at: string
}

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

export default function SniperAlertsPage() {
  const { subscription, user, logout, checkAuth } = useStore()
  const [alerts, setAlerts] = useState<SniperAlert[]>([])
  const [loading, setLoading] = useState(true)
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [editingAlert, setEditingAlert] = useState<SniperAlert | null>(null)
  const [deletingId, setDeletingId] = useState<number | null>(null)
  const [togglingId, setTogglingId] = useState<number | null>(null)
  
  // Mobile Menu
  const [menuOpen, setMenuOpen] = useState(false)

  const tier = subscription?.tier || 'scout'
  const alertLimits: Record<string, number> = { scout: 0, trader: 10, tycoon: 50 }
  const maxAlerts = alertLimits[tier] || 0
  // Limits match backend TIER_CONFIG.sniper_limit
  const canAddMore = alerts.length < maxAlerts

  const activeAlerts = alerts.filter(a => a.is_active).length
  const totalMatches = alerts.reduce((sum, a) => sum + a.matches_count, 0)
  const totalNotifications = alerts.reduce((sum, a) => sum + a.notifications_sent, 0)

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

  const loadAlerts = useCallback(async () => {
    setLoading(true)
    try {
      const data = await api.request<SniperAlert[]>('/sniper-alerts')
      setAlerts(data)
    } catch (err) {
      console.error('Failed to load alerts:', err)
    } finally {
      setLoading(false)
    }
  }, [])

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

  const handleToggle = async (id: number, currentStatus: boolean) => {
    setTogglingId(id)
    try {
      await api.request(`/sniper-alerts/${id}`, {
        method: 'PUT',
        body: JSON.stringify({ is_active: !currentStatus }),
      })
      await loadAlerts()
    } catch (err: any) {
      alert(err.message || 'Failed to toggle alert')
    } finally {
      setTogglingId(null)
    }
  }

  const handleDelete = async (id: number, name: string) => {
    if (!confirm(`Delete alert "${name}"?`)) return
    
    setDeletingId(id)
    try {
      await api.request(`/sniper-alerts/${id}`, { method: 'DELETE' })
      await loadAlerts()
    } catch (err: any) {
      alert(err.message || 'Failed to delete alert')
    } finally {
      setDeletingId(null)
    }
  }

  // Mobile Nav
  const mobileNavItems = [
    { href: '/terminal/hunt', label: 'Radar', icon: Target, active: false },
    { href: '/terminal/market', label: 'Market', icon: Gavel, active: false },
    { href: '/terminal/watchlist', label: 'Watch', icon: Eye, active: false },
    { href: '/terminal/intel', label: 'Intel', icon: TrendingUp, active: false },
  ]
  
  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: 'Radar', icon: Target },
      { href: '/terminal/market', label: 'Market', icon: Gavel },
      { 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, active: true },
    ]},
    { title: 'Monetize', items: [
      { href: '/terminal/yield', label: 'Yield', icon: Coins, isNew: true },
      { href: '/terminal/listing', label: 'For Sale', icon: Tag },
    ]}
  ]

  return (
    <div className="min-h-screen bg-[#020202]">
      <div className="hidden lg:block"><Sidebar /></div>
      
      <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">
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center gap-2">
                <div className="w-1.5 h-1.5 bg-accent animate-pulse" />
                <span className="text-[10px] font-mono tracking-[0.2em] text-accent uppercase">Sniper Alerts</span>
              </div>
              <div className="text-[10px] font-mono text-white/40">{alerts.length}/{maxAlerts}</div>
            </div>
            
            <div className="grid grid-cols-3 gap-2">
              <div className="bg-accent/[0.05] border border-accent/20 p-2">
                <div className="text-lg font-bold text-accent tabular-nums">{activeAlerts}</div>
                <div className="text-[9px] font-mono text-accent/60 uppercase tracking-wider">Active</div>
              </div>
              <div className="bg-white/[0.02] border border-white/[0.08] p-2">
                <div className="text-lg font-bold text-white tabular-nums">{totalMatches}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Matches</div>
              </div>
              <div className="bg-white/[0.02] border border-white/[0.08] p-2">
                <div className="text-lg font-bold text-white tabular-nums">{totalNotifications}</div>
                <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Sent</div>
              </div>
            </div>
          </div>
        </header>

        {/* DESKTOP HEADER */}
        <section className="hidden lg:block px-10 pt-10 pb-6">
          <div className="flex items-end justify-between gap-6">
            <div className="space-y-3">
              <div className="flex items-center gap-2">
                <div className="w-1.5 h-1.5 bg-accent animate-pulse" />
                <span className="text-[10px] font-mono tracking-[0.2em] text-accent uppercase">Sniper Alerts</span>
              </div>
              <h1 className="font-display text-[2.5rem] leading-[1] tracking-[-0.02em]">
                <span className="text-white">Sniper</span>
                <span className="text-white/30 ml-3 font-mono text-[2rem]">{alerts.length}/{maxAlerts}</span>
              </h1>
              <p className="text-sm text-white/40 font-mono mt-2 max-w-lg">
                Set up keyword alerts. Get notified when matching domains appear in auctions or zone file drops.
              </p>
            </div>
            
            <div className="flex items-center gap-6">
              <div className="flex gap-8">
                <div className="text-right">
                  <div className="text-2xl font-bold text-accent font-mono">{activeAlerts}</div>
                  <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Active</div>
                </div>
                <div className="text-right">
                  <div className="text-2xl font-bold text-white font-mono">{totalMatches}</div>
                  <div className="text-[9px] font-mono text-white/30 uppercase tracking-wider">Matches</div>
                </div>
              </div>
              
              <button
                onClick={() => setShowCreateModal(true)}
                disabled={!canAddMore}
                className={clsx(
                  "flex items-center gap-2 px-4 py-2.5 text-xs font-bold uppercase tracking-wider transition-colors",
                  canAddMore ? "bg-accent text-black hover:bg-white" : "bg-white/10 text-white/40 cursor-not-allowed"
                )}
              >
                <Plus className="w-4 h-4" />
                New Alert
              </button>
            </div>
          </div>
        </section>

        {/* ADD BUTTON MOBILE */}
        <section className="lg:hidden px-4 py-3 border-b border-white/[0.08]">
          <button
            onClick={() => setShowCreateModal(true)}
            disabled={!canAddMore}
            className={clsx(
              "w-full flex items-center justify-center gap-2 py-3 text-xs font-bold uppercase tracking-wider transition-colors",
              canAddMore ? "bg-accent text-black" : "bg-white/10 text-white/40"
            )}
          >
            <Plus className="w-4 h-4" />
            New Alert
          </button>
        </section>

        {/* ALERTS LIST */}
        <section className="px-4 lg:px-10 py-4 pb-28 lg:pb-10">
          {loading ? (
            <div className="flex items-center justify-center py-20">
              <Loader2 className="w-6 h-6 text-accent animate-spin" />
            </div>
          ) : alerts.length === 0 ? (
            <div className="text-center py-16 border border-dashed border-white/[0.08]">
              <Target className="w-8 h-8 text-white/10 mx-auto mb-3" />
              <p className="text-white/40 text-sm font-mono mb-2">No alerts yet</p>
              <p className="text-white/25 text-xs font-mono">Create your first sniper alert</p>
            </div>
          ) : (
            <div className="space-y-px bg-white/[0.04] border border-white/[0.08]">
              {alerts.map((alert) => (
                <div key={alert.id} className="bg-[#020202] hover:bg-white/[0.02] transition-all p-4">
                  <div className="flex items-start justify-between gap-4">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-2 flex-wrap">
                        <h3 className="text-sm font-bold text-white font-mono">{alert.name}</h3>
                        {alert.is_active ? (
                          <span className="px-1.5 py-0.5 text-[9px] font-mono bg-accent/10 text-accent border border-accent/20 flex items-center gap-1">
                            <div className="w-1 h-1 bg-accent animate-pulse" />
                            Active
                          </span>
                        ) : (
                          <span className="px-1.5 py-0.5 text-[9px] font-mono bg-white/5 text-white/40 border border-white/10">Paused</span>
                        )}
                      </div>

                      <div className="flex flex-wrap gap-1 mb-2">
                        {alert.tlds && <span className="px-1.5 py-0.5 text-[9px] font-mono bg-blue-400/10 text-blue-400 border border-blue-400/20">{alert.tlds}</span>}
                        {alert.keywords && <span className="px-1.5 py-0.5 text-[9px] font-mono bg-accent/10 text-accent border border-accent/20">+{alert.keywords}</span>}
                        {(alert.min_price || alert.max_price) && (
                          <span className="px-1.5 py-0.5 text-[9px] font-mono bg-white/5 text-white/50 border border-white/10 flex items-center gap-0.5">
                            <DollarSign className="w-3 h-3" />
                            {alert.min_price || 0}-{alert.max_price || '∞'}
                          </span>
                        )}
                      </div>

                      <div className="flex items-center gap-3 text-[10px] text-white/30 font-mono">
                        <span className="flex items-center gap-1"><Zap className="w-3 h-3" />{alert.matches_count}</span>
                        <span className="flex items-center gap-1"><Bell className="w-3 h-3" />{alert.notifications_sent}</span>
                      </div>
                    </div>

                    <div className="flex items-center gap-1 shrink-0">
                      <button
                        onClick={() => handleToggle(alert.id, alert.is_active)}
                        disabled={togglingId === alert.id}
                        className={clsx(
                          "w-8 h-8 flex items-center justify-center border transition-colors",
                          alert.is_active ? "bg-accent/10 border-accent/20 text-accent" : "bg-white/5 border-white/10 text-white/40"
                        )}
                      >
                        {togglingId === alert.id ? <Loader2 className="w-4 h-4 animate-spin" /> : alert.is_active ? <Power className="w-4 h-4" /> : <PowerOff className="w-4 h-4" />}
                      </button>
                      <button onClick={() => setEditingAlert(alert)} className="w-8 h-8 flex items-center justify-center border bg-white/5 border-white/10 text-white/40 hover:text-white">
                        <Edit2 className="w-4 h-4" />
                      </button>
                      <button
                        onClick={() => handleDelete(alert.id, alert.name)}
                        disabled={deletingId === alert.id}
                        className="w-8 h-8 flex items-center justify-center border bg-white/5 border-white/10 text-white/40 hover:text-rose-400"
                      >
                        {deletingId === alert.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <Trash2 className="w-4 h-4" />}
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}

          {!canAddMore && (
            <div className="mt-6 p-6 border border-white/[0.08] bg-white/[0.02] text-center">
              <Crown className="w-6 h-6 text-amber-400 mx-auto mb-3" />
              <h3 className="text-sm font-bold text-white mb-1">Alert Limit Reached</h3>
              <p className="text-xs font-mono text-white/40 mb-4">Upgrade for more alerts</p>
              <Link href="/pricing" className="inline-flex items-center gap-2 px-4 py-2 bg-amber-400 text-black text-xs font-bold uppercase tracking-wider">
                <Sparkles className="w-3 h-3" />Upgrade
              </Link>
            </div>
          )}
        </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", item.active ? "text-accent" : "text-white/40")}>
                {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">
              <Menu className="w-5 h-5" />
              <span className="text-[9px] font-mono uppercase tracking-wider">Menu</span>
            </button>
          </div>
        </nav>

        {/* DRAWER */}
        {menuOpen && (
          <div className="lg:hidden fixed inset-0 z-[100]">
            <div className="absolute inset-0 bg-black/80" 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] 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">POUNCE</h2>
                    <p className="text-[9px] text-white/40 font-mono uppercase">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">
                  <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>
                    {section.items.map((item: any) => (
                      <Link key={item.href} href={item.href} onClick={() => setMenuOpen(false)} className={clsx("flex items-center gap-3 px-4 py-2.5 border-l-2 border-transparent", item.active ? "text-accent border-accent bg-white/[0.02]" : "text-white/60")}>
                        <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 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">
                    <Settings className="w-4 h-4" /><span className="text-sm">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">
                      <Shield className="w-4 h-4" /><span className="text-sm">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">{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 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">
                  <LogOut className="w-3 h-3" />Sign out
                </button>
              </div>
            </div>
          </div>
        )}
      </main>

      {/* MODALS */}
      {(showCreateModal || editingAlert) && (
        <CreateEditModal
          alert={editingAlert}
          onClose={() => { setShowCreateModal(false); setEditingAlert(null) }}
          onSuccess={() => { loadAlerts(); setShowCreateModal(false); setEditingAlert(null) }}
        />
      )}
    </div>
  )
}

// ============================================================================
// CREATE/EDIT MODAL
// ============================================================================

function CreateEditModal({ alert, onClose, onSuccess }: {
  alert: SniperAlert | null
  onClose: () => void
  onSuccess: () => void
}) {
  const isEditing = !!alert
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  
  const [form, setForm] = useState({
    name: alert?.name || '',
    description: alert?.description || '',
    tlds: alert?.tlds || '',
    keywords: alert?.keywords || '',
    exclude_keywords: alert?.exclude_keywords || '',
    min_length: alert?.min_length?.toString() || '',
    max_length: alert?.max_length?.toString() || '',
    min_price: alert?.min_price?.toString() || '',
    max_price: alert?.max_price?.toString() || '',
    max_bids: alert?.max_bids?.toString() || '',
    ending_within_hours: alert?.ending_within_hours?.toString() || '',
    platforms: alert?.platforms || '',
    no_numbers: alert?.no_numbers || false,
    no_hyphens: alert?.no_hyphens || false,
    exclude_chars: alert?.exclude_chars || '',
    notify_email: alert?.notify_email ?? true,
  })

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    setError(null)

    try {
      const payload = {
        name: form.name,
        description: form.description || null,
        tlds: form.tlds || null,
        keywords: form.keywords || null,
        exclude_keywords: form.exclude_keywords || null,
        min_length: form.min_length ? parseInt(form.min_length) : null,
        max_length: form.max_length ? parseInt(form.max_length) : null,
        min_price: form.min_price ? parseFloat(form.min_price) : null,
        max_price: form.max_price ? parseFloat(form.max_price) : null,
        max_bids: form.max_bids ? parseInt(form.max_bids) : null,
        ending_within_hours: form.ending_within_hours ? parseInt(form.ending_within_hours) : null,
        platforms: form.platforms || null,
        no_numbers: form.no_numbers,
        no_hyphens: form.no_hyphens,
        exclude_chars: form.exclude_chars || null,
        notify_email: form.notify_email,
      }

      if (isEditing && alert) {
        await api.request(`/sniper-alerts/${alert.id}`, { method: 'PUT', body: JSON.stringify(payload) })
      } else {
        await api.request('/sniper-alerts', { method: 'POST', body: JSON.stringify(payload) })
      }
      onSuccess()
    } catch (err: any) {
      setError(err.message || 'Failed to save')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="fixed inset-0 z-[110] bg-black/80 flex items-center justify-center p-4 overflow-y-auto" onClick={onClose}>
      <div className="w-full max-w-lg bg-[#0A0A0A] border border-white/[0.08] my-8" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between p-4 border-b border-white/[0.08]">
          <div className="flex items-center gap-2">
            <Target className="w-4 h-4 text-accent" />
            <span className="text-xs font-mono text-accent uppercase tracking-wider">{isEditing ? 'Edit' : 'Create'} Alert</span>
          </div>
          <button onClick={onClose} className="w-8 h-8 flex items-center justify-center border border-white/10 text-white/40">
            <X className="w-4 h-4" />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="p-4 space-y-4 max-h-[70vh] overflow-y-auto">
          {error && (
            <div className="p-3 bg-rose-500/10 border border-rose-500/20 flex items-center gap-2 text-rose-400 text-xs">
              <AlertCircle className="w-4 h-4" />{error}
            </div>
          )}

          <div>
            <label className="block text-[9px] font-mono text-white/40 uppercase mb-1.5">Alert Name *</label>
            <input type="text" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required
              className="w-full px-3 py-2.5 bg-white/5 border border-white/10 text-white text-sm font-mono placeholder:text-white/20 outline-none focus:border-accent/50" placeholder="e.g. Premium 4L .com" />
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-[9px] font-mono text-white/40 uppercase mb-1.5">TLDs</label>
              <input type="text" value={form.tlds} onChange={(e) => setForm({ ...form, tlds: e.target.value })}
                className="w-full px-3 py-2.5 bg-white/5 border border-white/10 text-white text-sm font-mono placeholder:text-white/20 outline-none focus:border-accent/50" placeholder="com,io,ai" />
            </div>
            <div>
              <label className="block text-[9px] font-mono text-white/40 uppercase mb-1.5">Platforms</label>
              <input type="text" value={form.platforms} onChange={(e) => setForm({ ...form, platforms: e.target.value })}
                className="w-full px-3 py-2.5 bg-white/5 border border-white/10 text-white text-sm font-mono placeholder:text-white/20 outline-none focus:border-accent/50" placeholder="godaddy,sedo" />
            </div>
          </div>

          <div>
            <label className="block text-[9px] font-mono text-white/40 uppercase mb-1.5">Must Contain</label>
            <input type="text" value={form.keywords} onChange={(e) => setForm({ ...form, keywords: e.target.value })}
              className="w-full px-3 py-2.5 bg-white/5 border border-white/10 text-white text-sm font-mono placeholder:text-white/20 outline-none focus:border-accent/50" placeholder="crypto,web3,ai" />
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-[9px] font-mono text-white/40 uppercase mb-1.5">Min Price</label>
              <input type="number" value={form.min_price} onChange={(e) => setForm({ ...form, min_price: e.target.value })} min="0"
                className="w-full px-3 py-2.5 bg-white/5 border border-white/10 text-white text-sm font-mono placeholder:text-white/20 outline-none focus:border-accent/50" placeholder="0" />
            </div>
            <div>
              <label className="block text-[9px] font-mono text-white/40 uppercase mb-1.5">Max Price</label>
              <input type="number" value={form.max_price} onChange={(e) => setForm({ ...form, max_price: e.target.value })} min="0"
                className="w-full px-3 py-2.5 bg-white/5 border border-white/10 text-white text-sm font-mono placeholder:text-white/20 outline-none focus:border-accent/50" placeholder="10000" />
            </div>
          </div>

          {/* Sources info */}
          <div className="p-3 bg-accent/5 border border-accent/20">
            <div className="text-[9px] font-mono text-accent uppercase mb-2">Monitors</div>
            <div className="flex flex-wrap gap-2">
              <span className="px-2 py-1 text-[10px] font-mono bg-white/5 border border-white/10 text-white/60 flex items-center gap-1.5">
                <Gavel className="w-3 h-3" />
                Auctions
              </span>
              <span className="px-2 py-1 text-[10px] font-mono bg-white/5 border border-white/10 text-white/60 flex items-center gap-1.5">
                <Zap className="w-3 h-3" />
                Zone Drops
              </span>
            </div>
          </div>

          <div className="space-y-2">
            <label className="flex items-center gap-3 p-2.5 border border-white/[0.06] cursor-pointer hover:bg-white/[0.02]">
              <input type="checkbox" checked={form.notify_email} onChange={(e) => setForm({ ...form, notify_email: e.target.checked })} className="w-4 h-4" />
              <Bell className="w-4 h-4 text-accent" />
              <span className="text-sm text-white/60">Email notifications</span>
            </label>
          </div>

          <div className="flex gap-3 pt-2">
            <button type="button" onClick={onClose} className="flex-1 py-2.5 border border-white/10 text-white/60 text-xs font-mono uppercase">Cancel</button>
            <button type="submit" disabled={loading || !form.name} className="flex-1 flex items-center justify-center gap-2 py-2.5 bg-accent text-black text-xs font-bold uppercase disabled:opacity-50">
              {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <CheckCircle className="w-4 h-4" />}
              {isEditing ? 'Update' : 'Create'}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}

