'use client'

import { useEffect, useState } from 'react'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { CommandCenterLayout } from '@/components/CommandCenterLayout'
import { Toast, useToast } from '@/components/Toast'
import {
  Plus,
  Trash2,
  RefreshCw,
  Loader2,
  Bell,
  BellOff,
  History,
  ExternalLink,
  MoreVertical,
  Search,
  Filter,
  ArrowUpRight,
} from 'lucide-react'
import clsx from 'clsx'
import Link from 'next/link'

interface DomainHistory {
  id: number
  status: string
  is_available: boolean
  checked_at: string
}

// Status indicator component with traffic light system
function StatusIndicator({ domain }: { domain: any }) {
  // Determine status based on domain data
  let status: 'available' | 'watching' | 'stable' = 'stable'
  let label = 'Stable'
  let description = 'Domain is registered and active'
  
  if (domain.is_available) {
    status = 'available'
    label = 'Available'
    description = 'Domain is available for registration!'
  } else if (domain.status === 'checking' || domain.status === 'pending') {
    status = 'watching'
    label = 'Watching'
    description = 'Monitoring for changes'
  }
  
  const colors = {
    available: 'bg-accent text-accent',
    watching: 'bg-amber-400 text-amber-400',
    stable: 'bg-foreground-muted text-foreground-muted',
  }
  
  return (
    <div className="flex items-center gap-3">
      <div className="relative">
        <span className={clsx(
          "block w-3 h-3 rounded-full",
          colors[status].split(' ')[0]
        )} />
        {status === 'available' && (
          <span className={clsx(
            "absolute inset-0 rounded-full animate-ping opacity-75",
            colors[status].split(' ')[0]
          )} />
        )}
      </div>
      <div>
        <p className={clsx(
          "text-sm font-medium",
          status === 'available' ? 'text-accent' : 
          status === 'watching' ? 'text-amber-400' : 'text-foreground-muted'
        )}>
          {label}
        </p>
        <p className="text-xs text-foreground-subtle hidden sm:block">{description}</p>
      </div>
    </div>
  )
}

export default function WatchlistPage() {
  const { domains, addDomain, deleteDomain, refreshDomain, subscription } = useStore()
  const { toast, showToast, hideToast } = useToast()
  
  const [newDomain, setNewDomain] = useState('')
  const [adding, setAdding] = useState(false)
  const [refreshingId, setRefreshingId] = useState<number | null>(null)
  const [deletingId, setDeletingId] = useState<number | null>(null)
  const [selectedDomainId, setSelectedDomainId] = useState<number | null>(null)
  const [domainHistory, setDomainHistory] = useState<DomainHistory[] | null>(null)
  const [loadingHistory, setLoadingHistory] = useState(false)
  const [togglingNotifyId, setTogglingNotifyId] = useState<number | null>(null)
  const [filterStatus, setFilterStatus] = useState<'all' | 'available' | 'watching'>('all')
  const [searchQuery, setSearchQuery] = useState('')

  // Filter domains
  const filteredDomains = domains?.filter(domain => {
    // Search filter
    if (searchQuery && !domain.name.toLowerCase().includes(searchQuery.toLowerCase())) {
      return false
    }
    // Status filter
    if (filterStatus === 'available' && !domain.is_available) return false
    if (filterStatus === 'watching' && domain.is_available) return false
    return true
  }) || []

  // Stats
  const availableCount = domains?.filter(d => d.is_available).length || 0
  const watchingCount = domains?.filter(d => !d.is_available).length || 0

  const handleAddDomain = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!newDomain.trim()) return
    
    setAdding(true)
    try {
      await addDomain(newDomain.trim())
      setNewDomain('')
      showToast(`Added ${newDomain.trim()} to watchlist`, 'success')
    } catch (err: any) {
      showToast(err.message || 'Failed to add domain', 'error')
    } finally {
      setAdding(false)
    }
  }

  const handleRefresh = async (id: number) => {
    setRefreshingId(id)
    try {
      await refreshDomain(id)
      showToast('Domain status refreshed', 'success')
    } catch (err: any) {
      showToast(err.message || 'Failed to refresh', 'error')
    } finally {
      setRefreshingId(null)
    }
  }

  const handleDelete = async (id: number, name: string) => {
    if (!confirm(`Remove ${name} from your watchlist?`)) return
    
    setDeletingId(id)
    try {
      await deleteDomain(id)
      showToast(`Removed ${name} from watchlist`, 'success')
    } catch (err: any) {
      showToast(err.message || 'Failed to remove', 'error')
    } finally {
      setDeletingId(null)
    }
  }

  const handleToggleNotify = async (id: number, currentState: boolean) => {
    setTogglingNotifyId(id)
    try {
      await api.updateDomainNotify(id, !currentState)
      showToast(
        !currentState ? 'Notifications enabled' : 'Notifications disabled',
        'success'
      )
    } catch (err: any) {
      showToast(err.message || 'Failed to update', 'error')
    } finally {
      setTogglingNotifyId(null)
    }
  }

  const loadHistory = async (domainId: number) => {
    if (selectedDomainId === domainId) {
      setSelectedDomainId(null)
      setDomainHistory(null)
      return
    }
    
    setSelectedDomainId(domainId)
    setLoadingHistory(true)
    try {
      const history = await api.getDomainHistory(domainId)
      setDomainHistory(history)
    } catch (err) {
      setDomainHistory([])
    } finally {
      setLoadingHistory(false)
    }
  }

  const domainLimit = subscription?.domain_limit || 5
  const domainsUsed = domains?.length || 0
  const canAddMore = domainsUsed < domainLimit

  return (
    <CommandCenterLayout
      title="Watchlist"
      subtitle={`${domainsUsed}/${domainLimit} domains tracked`}
    >
      {toast && <Toast message={toast.message} type={toast.type} onClose={hideToast} />}

      <div className="max-w-6xl mx-auto space-y-6">
        {/* Stats Cards */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
          <div className="p-5 bg-gradient-to-br from-background-secondary/60 to-background-secondary/30 border border-border/50 rounded-2xl">
            <p className="text-xs text-foreground-subtle uppercase tracking-wider mb-2">Total Watched</p>
            <p className="text-3xl font-display text-foreground">{domainsUsed}</p>
          </div>
          <div className="relative p-5 bg-gradient-to-br from-accent/15 to-accent/5 border border-accent/30 rounded-2xl overflow-hidden">
            <div className="absolute top-0 right-0 w-20 h-20 bg-accent/10 rounded-full blur-2xl" />
            <div className="relative">
              <p className="text-xs text-foreground-subtle uppercase tracking-wider mb-2">Available</p>
              <p className="text-3xl font-display text-accent">{availableCount}</p>
            </div>
          </div>
          <div className="p-5 bg-gradient-to-br from-background-secondary/60 to-background-secondary/30 border border-border/50 rounded-2xl">
            <p className="text-xs text-foreground-subtle uppercase tracking-wider mb-2">Watching</p>
            <p className="text-3xl font-display text-foreground">{watchingCount}</p>
          </div>
          <div className="p-5 bg-gradient-to-br from-background-secondary/60 to-background-secondary/30 border border-border/50 rounded-2xl">
            <p className="text-xs text-foreground-subtle uppercase tracking-wider mb-2">Limit</p>
            <p className="text-3xl font-display text-foreground">{domainLimit === -1 ? '∞' : domainLimit}</p>
          </div>
        </div>

        {/* Add Domain Form */}
        <form onSubmit={handleAddDomain} className="flex gap-3">
          <div className="flex-1 relative">
            <input
              type="text"
              value={newDomain}
              onChange={(e) => setNewDomain(e.target.value)}
              placeholder="Enter domain to track (e.g., dream.com)"
              disabled={!canAddMore}
              className={clsx(
                "w-full h-12 px-5 bg-background-secondary/50 border border-border/50 rounded-xl",
                "text-foreground placeholder:text-foreground-subtle",
                "focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent/30",
                "disabled:opacity-50 disabled:cursor-not-allowed",
                "shadow-[0_2px_8px_-2px_rgba(0,0,0,0.1)]"
              )}
            />
          </div>
          <button
            type="submit"
            disabled={adding || !newDomain.trim() || !canAddMore}
            className={clsx(
              "flex items-center gap-2 h-12 px-6 rounded-xl font-medium transition-all",
              "bg-gradient-to-r from-accent to-accent/80 text-background hover:shadow-[0_0_20px_-5px_rgba(16,185,129,0.4)]",
              "disabled:opacity-50 disabled:cursor-not-allowed"
            )}
          >
            {adding ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              <Plus className="w-4 h-4" />
            )}
            Add
          </button>
        </form>

        {!canAddMore && (
          <div className="flex items-center justify-between p-4 bg-amber-500/10 border border-amber-500/20 rounded-xl">
            <p className="text-sm text-amber-400">
              You've reached your domain limit. Upgrade to track more.
            </p>
            <Link
              href="/pricing"
              className="text-sm font-medium text-amber-400 hover:text-amber-300 flex items-center gap-1"
            >
              Upgrade <ArrowUpRight className="w-3 h-3" />
            </Link>
          </div>
        )}

        {/* Filters */}
        <div className="flex flex-col sm:flex-row gap-3 sm:items-center sm:justify-between">
          <div className="flex gap-2">
            <button
              onClick={() => setFilterStatus('all')}
              className={clsx(
                "px-4 py-2 text-sm rounded-lg transition-colors",
                filterStatus === 'all' 
                  ? "bg-foreground/10 text-foreground" 
                  : "text-foreground-muted hover:bg-foreground/5"
              )}
            >
              All ({domainsUsed})
            </button>
            <button
              onClick={() => setFilterStatus('available')}
              className={clsx(
                "px-4 py-2 text-sm rounded-lg transition-colors flex items-center gap-2",
                filterStatus === 'available' 
                  ? "bg-accent/10 text-accent" 
                  : "text-foreground-muted hover:bg-foreground/5"
              )}
            >
              <span className="w-2 h-2 rounded-full bg-accent" />
              Available ({availableCount})
            </button>
            <button
              onClick={() => setFilterStatus('watching')}
              className={clsx(
                "px-4 py-2 text-sm rounded-lg transition-colors flex items-center gap-2",
                filterStatus === 'watching' 
                  ? "bg-foreground/10 text-foreground" 
                  : "text-foreground-muted hover:bg-foreground/5"
              )}
            >
              <span className="w-2 h-2 rounded-full bg-foreground-muted" />
              Watching ({watchingCount})
            </button>
          </div>
          
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-foreground-muted" />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Search domains..."
              className="w-full sm:w-64 h-10 pl-9 pr-4 bg-background-secondary border border-border rounded-lg
                         text-sm text-foreground placeholder:text-foreground-subtle
                         focus:outline-none focus:border-accent"
            />
          </div>
        </div>

        {/* Domain List */}
        <div className="space-y-3">
          {filteredDomains.length === 0 ? (
            <div className="text-center py-16 bg-background-secondary/30 border border-border rounded-xl">
              {domainsUsed === 0 ? (
                <>
                  <div className="w-16 h-16 bg-foreground/5 rounded-2xl flex items-center justify-center mx-auto mb-4">
                    <Plus className="w-8 h-8 text-foreground-subtle" />
                  </div>
                  <p className="text-foreground-muted mb-2">Your watchlist is empty</p>
                  <p className="text-sm text-foreground-subtle">Add a domain above to start tracking</p>
                </>
              ) : (
                <>
                  <Filter className="w-8 h-8 text-foreground-subtle mx-auto mb-4" />
                  <p className="text-foreground-muted">No domains match your filters</p>
                </>
              )}
            </div>
          ) : (
            filteredDomains.map((domain) => (
              <div
                key={domain.id}
                className={clsx(
                  "group p-4 sm:p-5 rounded-xl border transition-all duration-200",
                  domain.is_available
                    ? "bg-accent/5 border-accent/20 hover:border-accent/40"
                    : "bg-background-secondary/50 border-border hover:border-foreground/20"
                )}
              >
                <div className="flex flex-col sm:flex-row sm:items-center gap-4">
                  {/* Domain Name + Status */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-3 mb-2">
                      <h3 className="text-lg font-semibold text-foreground truncate">
                        {domain.name}
                      </h3>
                      {domain.is_available && (
                        <span className="shrink-0 px-2 py-0.5 bg-accent/20 text-accent text-xs font-semibold rounded-full">
                          GRAB IT!
                        </span>
                      )}
                    </div>
                    <StatusIndicator domain={domain} />
                  </div>

                  {/* Actions */}
                  <div className="flex items-center gap-2 shrink-0">
                    {/* Notify Toggle */}
                    <button
                      onClick={() => handleToggleNotify(domain.id, domain.notify_on_available)}
                      disabled={togglingNotifyId === domain.id}
                      className={clsx(
                        "p-2 rounded-lg transition-colors",
                        domain.notify_on_available 
                          ? "bg-accent/10 text-accent hover:bg-accent/20" 
                          : "text-foreground-muted hover:bg-foreground/5"
                      )}
                      title={domain.notify_on_available ? "Disable alerts" : "Enable alerts"}
                    >
                      {togglingNotifyId === domain.id ? (
                        <Loader2 className="w-4 h-4 animate-spin" />
                      ) : domain.notify_on_available ? (
                        <Bell className="w-4 h-4" />
                      ) : (
                        <BellOff className="w-4 h-4" />
                      )}
                    </button>

                    {/* History */}
                    <button
                      onClick={() => loadHistory(domain.id)}
                      className={clsx(
                        "p-2 rounded-lg transition-colors",
                        selectedDomainId === domain.id
                          ? "bg-foreground/10 text-foreground"
                          : "text-foreground-muted hover:bg-foreground/5"
                      )}
                      title="View history"
                    >
                      <History className="w-4 h-4" />
                    </button>

                    {/* Refresh */}
                    <button
                      onClick={() => handleRefresh(domain.id)}
                      disabled={refreshingId === domain.id}
                      className="p-2 rounded-lg text-foreground-muted hover:bg-foreground/5 transition-colors"
                      title="Refresh status"
                    >
                      <RefreshCw className={clsx(
                        "w-4 h-4",
                        refreshingId === domain.id && "animate-spin"
                      )} />
                    </button>

                    {/* Delete */}
                    <button
                      onClick={() => handleDelete(domain.id, domain.name)}
                      disabled={deletingId === domain.id}
                      className="p-2 rounded-lg text-foreground-muted hover:text-red-400 hover:bg-red-400/10 transition-colors"
                      title="Remove"
                    >
                      {deletingId === domain.id ? (
                        <Loader2 className="w-4 h-4 animate-spin" />
                      ) : (
                        <Trash2 className="w-4 h-4" />
                      )}
                    </button>

                    {/* External Link (if available) */}
                    {domain.is_available && (
                      <a
                        href={`https://www.namecheap.com/domains/registration/results/?domain=${domain.name}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex items-center gap-2 px-4 py-2 bg-accent text-background rounded-lg 
                                   font-medium text-sm hover:bg-accent-hover transition-colors"
                      >
                        Register
                        <ExternalLink className="w-3 h-3" />
                      </a>
                    )}
                  </div>
                </div>

                {/* History Panel */}
                {selectedDomainId === domain.id && (
                  <div className="mt-4 pt-4 border-t border-border/50">
                    <h4 className="text-sm font-medium text-foreground-muted mb-3">Status History</h4>
                    {loadingHistory ? (
                      <div className="flex items-center gap-2 text-foreground-muted">
                        <Loader2 className="w-4 h-4 animate-spin" />
                        <span className="text-sm">Acquiring targets...</span>
                      </div>
                    ) : domainHistory && domainHistory.length > 0 ? (
                      <div className="space-y-2">
                        {domainHistory.slice(0, 5).map((entry) => (
                          <div 
                            key={entry.id}
                            className="flex items-center gap-3 text-sm"
                          >
                            <span className={clsx(
                              "w-2 h-2 rounded-full",
                              entry.is_available ? "bg-accent" : "bg-foreground-muted"
                            )} />
                            <span className="text-foreground-muted">
                              {new Date(entry.checked_at).toLocaleDateString()} at{' '}
                              {new Date(entry.checked_at).toLocaleTimeString()}
                            </span>
                            <span className="text-foreground">
                              {entry.is_available ? 'Available' : 'Registered'}
                            </span>
                          </div>
                        ))}
                      </div>
                    ) : (
                      <p className="text-sm text-foreground-subtle">No history available yet</p>
                    )}
                  </div>
                )}
              </div>
            ))
          )}
        </div>
      </div>
    </CommandCenterLayout>
  )
}

