'use client'

import { useEffect, useState, useCallback } from 'react'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { TerminalLayout } from '@/components/TerminalLayout'
import {
  Plus,
  Target,
  Zap,
  Edit2,
  Trash2,
  Power,
  PowerOff,
  Eye,
  Bell,
  MessageSquare,
  Loader2,
  X,
  AlertCircle,
  CheckCircle,
  TrendingUp,
  Filter,
  Clock,
  DollarSign,
  Hash,
  Tag,
  Crown,
  Activity
} from 'lucide-react'
import clsx from 'clsx'
import Link from 'next/link'

// ============================================================================
// SHARED COMPONENTS
// ============================================================================

const StatCard = ({ label, value, subValue, icon: Icon, highlight, trend }: {
  label: string
  value: string | number
  subValue?: string
  icon: any
  highlight?: boolean
  trend?: 'up' | 'down' | 'neutral' | 'active'
}) => (
  <div className={clsx(
    "bg-zinc-900/40 border p-4 relative overflow-hidden group hover:border-white/10 transition-colors h-full",
    highlight ? "border-emerald-500/30" : "border-white/5"
  )}>
    <div className="absolute top-0 right-0 p-4 opacity-10 group-hover:opacity-20 transition-opacity">
      <Icon className="w-16 h-16" />
    </div>
    <div className="relative z-10">
      <div className="flex items-center gap-2 text-zinc-400 mb-1">
        <Icon className={clsx("w-4 h-4", (highlight || trend === 'active' || trend === 'up') && "text-emerald-400")} />
        <span className="text-xs font-medium uppercase tracking-wider">{label}</span>
      </div>
      <div className="flex items-baseline gap-2">
        <span className="text-2xl font-bold text-white tracking-tight">{value}</span>
        {subValue && <span className="text-xs text-zinc-500 font-medium">{subValue}</span>}
      </div>
      {highlight && (
        <div className="mt-2 text-[10px] font-medium px-1.5 py-0.5 w-fit rounded border text-emerald-400 border-emerald-400/20 bg-emerald-400/5">
          ● LIVE
        </div>
      )}
    </div>
  </div>
)

// ============================================================================
// 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 } = 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)

  // Tier-based limits
  const tier = subscription?.tier || 'scout'
  const alertLimits: Record<string, number> = { scout: 2, trader: 10, tycoon: 50 }
  const maxAlerts = alertLimits[tier] || 2
  const canAddMore = alerts.length < maxAlerts
  const isTycoon = tier === 'tycoon'

  // Stats
  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)

  // Load alerts
  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])

  // Toggle alert active status
  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)
    }
  }

  // Delete alert
  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)
    }
  }

  return (
    <TerminalLayout>
      <div className="relative min-h-screen">
        {/* Ambient Background Glow */}
        <div className="fixed inset-0 pointer-events-none">
          <div className="absolute top-0 left-1/4 w-96 h-96 bg-emerald-500/5 rounded-full blur-3xl" />
          <div className="absolute top-1/3 right-1/4 w-96 h-96 bg-blue-500/5 rounded-full blur-3xl" />
        </div>

        {/* Content */}
        <div className="relative z-10 space-y-8">
          {/* Header */}
          <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            <div>
              <div className="flex items-center gap-3">
                <div className="h-8 w-1 bg-emerald-500 rounded-full shadow-[0_0_10px_rgba(16,185,129,0.5)]" />
                <h1 className="text-3xl font-bold tracking-tight text-white">Sniper Alerts</h1>
              </div>
              <p className="text-zinc-400 mt-1 max-w-2xl">
                Get notified when domains matching your exact criteria hit the market. Set it, forget it, and pounce when the time is right.
              </p>
            </div>

            <button
              onClick={() => setShowCreateModal(true)}
              disabled={!canAddMore}
              className="px-4 py-2 bg-emerald-500 text-white font-medium rounded-lg hover:bg-emerald-400 transition-all shadow-lg shadow-emerald-500/20 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 whitespace-nowrap"
            >
              <Plus className="w-4 h-4" /> New Alert
            </button>
          </div>

          {/* Stats */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <StatCard 
              label="Active Alerts" 
              value={activeAlerts}
              subValue={`/ ${maxAlerts} slots`}
              icon={Target}
              trend="active"
              highlight={activeAlerts > 0}
            />
            <StatCard 
              label="Total Matches" 
              value={totalMatches}
              subValue="All time"
              icon={Zap}
              trend={totalMatches > 0 ? 'up' : 'neutral'}
            />
            <StatCard 
              label="Notifications" 
              value={totalNotifications}
              subValue="Sent"
              icon={Bell}
              trend={totalNotifications > 0 ? 'up' : 'neutral'}
            />
            <StatCard 
              label="Monitoring" 
              value={alerts.length}
              subValue="Total alerts"
              icon={Activity}
              trend="neutral"
            />
          </div>

          {/* Alerts List */}
          <div className="bg-zinc-900/40 border border-white/5 rounded-xl overflow-hidden backdrop-blur-sm">
            {/* Header */}
            <div className="px-6 py-4 bg-white/[0.02] border-b border-white/5 flex items-center justify-between">
              <h2 className="text-sm font-semibold text-zinc-400 uppercase tracking-wider flex items-center gap-2">
                <Filter className="w-4 h-4" />
                Your Alerts
              </h2>
              <span className="text-xs text-zinc-600">{alerts.length} / {maxAlerts}</span>
            </div>

            {/* Loading */}
            {loading && (
              <div className="flex items-center justify-center py-20">
                <Loader2 className="w-8 h-8 text-emerald-500 animate-spin" />
              </div>
            )}

            {/* Empty State */}
            {!loading && alerts.length === 0 && (
              <div className="flex flex-col items-center justify-center py-20 text-center px-4">
                <div className="w-16 h-16 rounded-full bg-white/5 flex items-center justify-center mb-4">
                  <Target className="w-8 h-8 text-zinc-600" />
                </div>
                <h3 className="text-lg font-bold text-white mb-2">No Alerts Yet</h3>
                <p className="text-sm text-zinc-500 max-w-md mb-6">
                  Create your first sniper alert to get notified when domains matching your criteria appear in auctions.
                </p>
                <button
                  onClick={() => setShowCreateModal(true)}
                  className="px-4 py-2 bg-emerald-500 text-white font-medium rounded-lg hover:bg-emerald-400 transition-all shadow-lg shadow-emerald-500/20 flex items-center gap-2"
                >
                  <Plus className="w-4 h-4" /> Create First Alert
                </button>
              </div>
            )}

            {/* Alerts Grid */}
            {!loading && alerts.length > 0 && (
              <div className="divide-y divide-white/5">
                {alerts.map((alert) => (
                  <div key={alert.id} className="p-6 hover:bg-white/[0.02] transition-colors group">
                    <div className="flex items-start justify-between gap-4">
                      {/* Alert Info */}
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-3 mb-2">
                          <h3 className="text-lg font-bold text-white truncate">{alert.name}</h3>
                          {alert.is_active ? (
                            <span className="px-2 py-0.5 rounded-full text-[10px] font-bold bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 flex items-center gap-1">
                              <div className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" />
                              ACTIVE
                            </span>
                          ) : (
                            <span className="px-2 py-0.5 rounded-full text-[10px] font-bold bg-zinc-800 text-zinc-500 border border-zinc-700">
                              PAUSED
                            </span>
                          )}
                          {isTycoon && alert.notify_sms && (
                            <span className="px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-500/10 text-amber-400 border border-amber-500/20 flex items-center gap-1">
                              <Crown className="w-3 h-3" />
                              SMS
                            </span>
                          )}
                        </div>
                        
                        {alert.description && (
                          <p className="text-sm text-zinc-400 mb-3">{alert.description}</p>
                        )}

                        {/* Criteria Pills */}
                        <div className="flex flex-wrap gap-2 mb-3">
                          {alert.tlds && (
                            <span className="px-2 py-1 rounded-lg bg-blue-500/10 text-blue-400 text-xs font-medium border border-blue-500/20">
                              {alert.tlds}
                            </span>
                          )}
                          {alert.keywords && (
                            <span className="px-2 py-1 rounded-lg bg-emerald-500/10 text-emerald-400 text-xs font-medium border border-emerald-500/20">
                              +{alert.keywords}
                            </span>
                          )}
                          {alert.exclude_keywords && (
                            <span className="px-2 py-1 rounded-lg bg-rose-500/10 text-rose-400 text-xs font-medium border border-rose-500/20">
                              -{alert.exclude_keywords}
                            </span>
                          )}
                          {(alert.min_length || alert.max_length) && (
                            <span className="px-2 py-1 rounded-lg bg-zinc-800 text-zinc-400 text-xs font-medium border border-zinc-700 flex items-center gap-1">
                              <Hash className="w-3 h-3" />
                              {alert.min_length || 1}-{alert.max_length || 63} chars
                            </span>
                          )}
                          {(alert.min_price || alert.max_price) && (
                            <span className="px-2 py-1 rounded-lg bg-zinc-800 text-zinc-400 text-xs font-medium border border-zinc-700 flex items-center gap-1">
                              <DollarSign className="w-3 h-3" />
                              {alert.min_price ? `$${alert.min_price}+` : ''}{alert.max_price ? ` - $${alert.max_price}` : ''}
                            </span>
                          )}
                          {alert.no_numbers && (
                            <span className="px-2 py-1 rounded-lg bg-zinc-800 text-zinc-400 text-xs font-medium border border-zinc-700">
                              No numbers
                            </span>
                          )}
                          {alert.no_hyphens && (
                            <span className="px-2 py-1 rounded-lg bg-zinc-800 text-zinc-400 text-xs font-medium border border-zinc-700">
                              No hyphens
                            </span>
                          )}
                        </div>

                        {/* Stats */}
                        <div className="flex items-center gap-4 text-xs text-zinc-500">
                          <span className="flex items-center gap-1">
                            <Zap className="w-3 h-3" />
                            {alert.matches_count} matches
                          </span>
                          <span className="flex items-center gap-1">
                            <Bell className="w-3 h-3" />
                            {alert.notifications_sent} sent
                          </span>
                          {alert.last_matched_at && (
                            <span className="flex items-center gap-1">
                              <Clock className="w-3 h-3" />
                              Last: {new Date(alert.last_matched_at).toLocaleDateString()}
                            </span>
                          )}
                        </div>
                      </div>

                      {/* Actions */}
                      <div className="flex items-center gap-2">
                        <button
                          onClick={() => handleToggle(alert.id, alert.is_active)}
                          disabled={togglingId === alert.id}
                          className={clsx(
                            "p-2 rounded-lg border transition-all",
                            alert.is_active
                              ? "bg-emerald-500/10 border-emerald-500/20 text-emerald-400 hover:bg-emerald-500/20"
                              : "bg-zinc-800/50 border-zinc-700 text-zinc-500 hover:bg-zinc-800"
                          )}
                          title={alert.is_active ? "Pause" : "Activate"}
                        >
                          {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="p-2 rounded-lg border bg-zinc-800/50 border-zinc-700 text-zinc-400 hover:text-white hover:bg-zinc-800 transition-all"
                          title="Edit"
                        >
                          <Edit2 className="w-4 h-4" />
                        </button>
                        
                        <button
                          onClick={() => handleDelete(alert.id, alert.name)}
                          disabled={deletingId === alert.id}
                          className="p-2 rounded-lg border bg-zinc-800/50 border-zinc-700 text-zinc-400 hover:text-rose-400 hover:border-rose-500/30 transition-all disabled:opacity-50"
                          title="Delete"
                        >
                          {deletingId === alert.id ? (
                            <Loader2 className="w-4 h-4 animate-spin" />
                          ) : (
                            <Trash2 className="w-4 h-4" />
                          )}
                        </button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Upgrade CTA */}
          {!canAddMore && (
            <div className="p-6 bg-gradient-to-br from-amber-900/20 to-black border border-amber-500/20 rounded-2xl text-center">
              <Crown className="w-12 h-12 text-amber-400 mx-auto mb-4" />
              <h3 className="text-xl font-bold text-white mb-2">Alert Limit Reached</h3>
              <p className="text-zinc-400 mb-4">
                You've created {maxAlerts} alerts. Upgrade to add more.
              </p>
              <div className="flex gap-4 justify-center text-sm">
                <div className="px-4 py-2 bg-white/5 rounded-lg">
                  <span className="text-zinc-500">Trader:</span> <span className="text-white font-bold">10 alerts</span>
                </div>
                <div className="px-4 py-2 bg-amber-500/10 border border-amber-500/20 rounded-lg">
                  <span className="text-zinc-500">Tycoon:</span> <span className="text-amber-400 font-bold">50 alerts + SMS</span>
                </div>
              </div>
              <Link
                href="/pricing"
                className="inline-flex items-center gap-2 px-6 py-3 bg-amber-500 text-white font-bold rounded-xl hover:bg-amber-400 transition-all shadow-lg shadow-amber-500/20 mt-4"
              >
                Upgrade Now
              </Link>
            </div>
          )}
        </div>

        {/* Create/Edit Modal */}
        {(showCreateModal || editingAlert) && (
          <CreateEditModal
            alert={editingAlert}
            onClose={() => {
              setShowCreateModal(false)
              setEditingAlert(null)
            }}
            onSuccess={() => {
              loadAlerts()
              setShowCreateModal(false)
              setEditingAlert(null)
            }}
            isTycoon={isTycoon}
          />
        )}
      </div>
    </TerminalLayout>
  )
}

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

function CreateEditModal({ alert, onClose, onSuccess, isTycoon }: {
  alert: SniperAlert | null
  onClose: () => void
  onSuccess: () => void
  isTycoon: boolean
}) {
  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,
    notify_sms: alert?.notify_sms || false,
  })

  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,
        notify_sms: form.notify_sms && isTycoon,
      }

      if (isEditing) {
        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 alert')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div 
      className="fixed inset-0 z-[100] bg-black/80 backdrop-blur-sm flex items-center justify-center p-4 overflow-y-auto"
      onClick={onClose}
    >
      <div 
        className="w-full max-w-2xl bg-[#0A0A0A] border border-white/10 rounded-2xl shadow-2xl my-8"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-white/5 bg-white/[0.02]">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg border bg-emerald-500/10 border-emerald-500/20">
              <Target className="w-5 h-5 text-emerald-400" />
            </div>
            <div>
              <h3 className="font-bold text-lg text-white">{isEditing ? 'Edit Alert' : 'Create Sniper Alert'}</h3>
              <p className="text-xs text-zinc-500">Set precise criteria for domain matching</p>
            </div>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-white/10 rounded-full text-zinc-500 hover:text-white transition-colors">
            <X className="w-5 h-5" />
          </button>
        </div>

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

          {/* Basic Info */}
          <div className="space-y-4">
            <h4 className="text-sm font-bold text-zinc-400 uppercase tracking-wider">Basic Info</h4>
            
            <div>
              <label className="block text-xs font-bold text-zinc-500 uppercase tracking-wider mb-2">Alert Name *</label>
              <input
                type="text"
                value={form.name}
                onChange={(e) => setForm({ ...form, name: e.target.value })}
                placeholder="e.g. Premium 4L .com domains"
                required
                className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder:text-zinc-600 focus:outline-none focus:border-emerald-500/50 transition-all"
              />
            </div>

            <div>
              <label className="block text-xs font-bold text-zinc-500 uppercase tracking-wider mb-2">Description</label>
              <textarea
                value={form.description}
                onChange={(e) => setForm({ ...form, description: e.target.value })}
                placeholder="Optional description"
                rows={2}
                className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder:text-zinc-600 focus:outline-none focus:border-emerald-500/50 transition-all resize-none"
              />
            </div>
          </div>

          {/* Filters */}
          <div className="space-y-4">
            <h4 className="text-sm font-bold text-zinc-400 uppercase tracking-wider">Criteria</h4>
            
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-bold text-zinc-500 uppercase tracking-wider mb-2">TLDs</label>
                <input
                  type="text"
                  value={form.tlds}
                  onChange={(e) => setForm({ ...form, tlds: e.target.value })}
                  placeholder="com,io,ai"
                  className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder:text-zinc-600 focus:outline-none focus:border-emerald-500/50 transition-all font-mono text-sm"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-zinc-500 uppercase tracking-wider mb-2">Platforms</label>
                <input
                  type="text"
                  value={form.platforms}
                  onChange={(e) => setForm({ ...form, platforms: e.target.value })}
                  placeholder="godaddy,sedo"
                  className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder:text-zinc-600 focus:outline-none focus:border-emerald-500/50 transition-all font-mono text-sm"
                />
              </div>
            </div>

            <div>
              <label className="block text-xs font-bold text-zinc-500 uppercase tracking-wider mb-2">Must Contain</label>
              <input
                type="text"
                value={form.keywords}
                onChange={(e) => setForm({ ...form, keywords: e.target.value })}
                placeholder="crypto,web3,ai"
                className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder:text-zinc-600 focus:outline-none focus:border-emerald-500/50 transition-all font-mono text-sm"
              />
            </div>

            <div>
              <label className="block text-xs font-bold text-zinc-500 uppercase tracking-wider mb-2">Must NOT Contain</label>
              <input
                type="text"
                value={form.exclude_keywords}
                onChange={(e) => setForm({ ...form, exclude_keywords: e.target.value })}
                placeholder="xxx,adult"
                className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder:text-zinc-600 focus:outline-none focus:border-emerald-500/50 transition-all font-mono text-sm"
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-bold text-zinc-500 uppercase tracking-wider mb-2">Min Length</label>
                <input
                  type="number"
                  value={form.min_length}
                  onChange={(e) => setForm({ ...form, min_length: e.target.value })}
                  placeholder="1"
                  min="1"
                  max="63"
                  className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder:text-zinc-600 focus:outline-none focus:border-emerald-500/50 transition-all"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-zinc-500 uppercase tracking-wider mb-2">Max Length</label>
                <input
                  type="number"
                  value={form.max_length}
                  onChange={(e) => setForm({ ...form, max_length: e.target.value })}
                  placeholder="63"
                  min="1"
                  max="63"
                  className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder:text-zinc-600 focus:outline-none focus:border-emerald-500/50 transition-all"
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-bold text-zinc-500 uppercase tracking-wider mb-2">Min Price (USD)</label>
                <input
                  type="number"
                  value={form.min_price}
                  onChange={(e) => setForm({ ...form, min_price: e.target.value })}
                  placeholder="0"
                  min="0"
                  step="0.01"
                  className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder:text-zinc-600 focus:outline-none focus:border-emerald-500/50 transition-all"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-zinc-500 uppercase tracking-wider mb-2">Max Price (USD)</label>
                <input
                  type="number"
                  value={form.max_price}
                  onChange={(e) => setForm({ ...form, max_price: e.target.value })}
                  placeholder="10000"
                  min="0"
                  step="0.01"
                  className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder:text-zinc-600 focus:outline-none focus:border-emerald-500/50 transition-all"
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-bold text-zinc-500 uppercase tracking-wider mb-2">Max Bids</label>
                <input
                  type="number"
                  value={form.max_bids}
                  onChange={(e) => setForm({ ...form, max_bids: e.target.value })}
                  placeholder="Low competition"
                  min="0"
                  className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder:text-zinc-600 focus:outline-none focus:border-emerald-500/50 transition-all"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-zinc-500 uppercase tracking-wider mb-2">Ending Within (hours)</label>
                <input
                  type="number"
                  value={form.ending_within_hours}
                  onChange={(e) => setForm({ ...form, ending_within_hours: e.target.value })}
                  placeholder="24"
                  min="1"
                  max="168"
                  className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder:text-zinc-600 focus:outline-none focus:border-emerald-500/50 transition-all"
                />
              </div>
            </div>

            <div className="space-y-3">
              <label className="flex items-center gap-3 cursor-pointer p-3 rounded-lg border border-white/5 hover:bg-white/5 transition-colors">
                <input
                  type="checkbox"
                  checked={form.no_numbers}
                  onChange={(e) => setForm({ ...form, no_numbers: e.target.checked })}
                  className="w-5 h-5 rounded border-white/20 bg-black text-emerald-500 focus:ring-emerald-500 focus:ring-offset-0"
                />
                <span className="text-sm text-zinc-300">No numbers in domain</span>
              </label>

              <label className="flex items-center gap-3 cursor-pointer p-3 rounded-lg border border-white/5 hover:bg-white/5 transition-colors">
                <input
                  type="checkbox"
                  checked={form.no_hyphens}
                  onChange={(e) => setForm({ ...form, no_hyphens: e.target.checked })}
                  className="w-5 h-5 rounded border-white/20 bg-black text-emerald-500 focus:ring-emerald-500 focus:ring-offset-0"
                />
                <span className="text-sm text-zinc-300">No hyphens in domain</span>
              </label>
            </div>

            <div>
              <label className="block text-xs font-bold text-zinc-500 uppercase tracking-wider mb-2">Exclude Characters</label>
              <input
                type="text"
                value={form.exclude_chars}
                onChange={(e) => setForm({ ...form, exclude_chars: e.target.value })}
                placeholder="q,x,z"
                className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder:text-zinc-600 focus:outline-none focus:border-emerald-500/50 transition-all font-mono text-sm"
              />
            </div>
          </div>

          {/* Notifications */}
          <div className="space-y-4">
            <h4 className="text-sm font-bold text-zinc-400 uppercase tracking-wider">Notifications</h4>
            
            <label className="flex items-center gap-3 cursor-pointer p-3 rounded-lg border border-white/5 hover:bg-white/5 transition-colors">
              <input
                type="checkbox"
                checked={form.notify_email}
                onChange={(e) => setForm({ ...form, notify_email: e.target.checked })}
                className="w-5 h-5 rounded border-white/20 bg-black text-emerald-500 focus:ring-emerald-500 focus:ring-offset-0"
              />
              <Bell className="w-4 h-4 text-emerald-400" />
              <span className="text-sm text-zinc-300 flex-1">Email notifications</span>
            </label>

            <label className={clsx(
              "flex items-center gap-3 cursor-pointer p-3 rounded-lg border transition-colors",
              isTycoon ? "border-amber-500/20 hover:bg-amber-500/5" : "border-white/5 opacity-50 cursor-not-allowed"
            )}>
              <input
                type="checkbox"
                checked={form.notify_sms}
                onChange={(e) => isTycoon && setForm({ ...form, notify_sms: e.target.checked })}
                disabled={!isTycoon}
                className="w-5 h-5 rounded border-white/20 bg-black text-amber-500 focus:ring-amber-500 focus:ring-offset-0 disabled:opacity-50"
              />
              <MessageSquare className="w-4 h-4 text-amber-400" />
              <span className="text-sm text-zinc-300 flex-1">SMS notifications</span>
              {!isTycoon && <Crown className="w-4 h-4 text-amber-400" />}
            </label>
          </div>

          {/* Actions */}
          <div className="flex gap-3 pt-4">
            <button
              type="button"
              onClick={onClose}
              className="flex-1 px-4 py-3 border border-white/10 text-zinc-400 rounded-xl hover:bg-white/5 hover:text-white transition-all font-medium"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={loading || !form.name}
              className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-emerald-500 text-white font-bold rounded-xl hover:bg-emerald-400 transition-all disabled:opacity-50 shadow-lg shadow-emerald-500/20"
            >
              {loading ? (
                <>
                  <Loader2 className="w-5 h-5 animate-spin" />
                  Saving...
                </>
              ) : (
                <>
                  <CheckCircle className="w-5 h-5" />
                  {isEditing ? 'Update Alert' : 'Create Alert'}
                </>
              )}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}

