'use client'

import { useState, useMemo } from 'react'
import Link from 'next/link'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { useServers, ServerStatus } from '@/hooks/use-servers'
import {
  Search,
  Server,
  Globe,
  User,
  Calendar,
  RefreshCw,
  ExternalLink,
  ChevronLeft,
  ChevronRight,
  Loader2,
  AlertCircle,
  CheckCircle,
  XCircle,
  Clock,
  Cpu,
  Package,
  Filter,
  ServerCrash,
  Zap,
  Activity,
} from 'lucide-react'

// Status configuration with enhanced styling
const statusConfig: Record<ServerStatus, {
  label: string
  bgColor: string
  textColor: string
  borderColor: string
  dotColor: string
  iconBg: string
  iconColor: string
  cardGradient: string
  icon: typeof CheckCircle
}> = {
  online: {
    label: 'Online',
    bgColor: 'bg-emerald-50 dark:bg-emerald-950/30',
    textColor: 'text-emerald-700 dark:text-emerald-400',
    borderColor: 'border-emerald-200 dark:border-emerald-800',
    dotColor: 'bg-emerald-500',
    iconBg: 'bg-emerald-100 dark:bg-emerald-900/50',
    iconColor: 'text-emerald-600 dark:text-emerald-400',
    cardGradient: 'from-emerald-50/50 via-card to-card dark:from-emerald-950/20',
    icon: CheckCircle,
  },
  provisioning: {
    label: 'Provisioning',
    bgColor: 'bg-blue-50 dark:bg-blue-950/30',
    textColor: 'text-blue-700 dark:text-blue-400',
    borderColor: 'border-blue-200 dark:border-blue-800',
    dotColor: 'bg-blue-500',
    iconBg: 'bg-blue-100 dark:bg-blue-900/50',
    iconColor: 'text-blue-600 dark:text-blue-400',
    cardGradient: 'from-blue-50/50 via-card to-card dark:from-blue-950/20',
    icon: Clock,
  },
  offline: {
    label: 'Offline',
    bgColor: 'bg-red-50 dark:bg-red-950/30',
    textColor: 'text-red-700 dark:text-red-400',
    borderColor: 'border-red-200 dark:border-red-800',
    dotColor: 'bg-red-500',
    iconBg: 'bg-red-100 dark:bg-red-900/50',
    iconColor: 'text-red-600 dark:text-red-400',
    cardGradient: 'from-red-50/50 via-card to-card dark:from-red-950/20',
    icon: XCircle,
  },
  pending: {
    label: 'Pending',
    bgColor: 'bg-amber-50 dark:bg-amber-950/30',
    textColor: 'text-amber-700 dark:text-amber-400',
    borderColor: 'border-amber-200 dark:border-amber-800',
    dotColor: 'bg-amber-500',
    iconBg: 'bg-amber-100 dark:bg-amber-900/50',
    iconColor: 'text-amber-600 dark:text-amber-400',
    cardGradient: 'from-amber-50/50 via-card to-card dark:from-amber-950/20',
    icon: Clock,
  },
}

// Enhanced status badge component with dot indicator and pulse animation
function ServerStatusBadge({ status }: { status: ServerStatus }) {
  const config = statusConfig[status]

  return (
    <span className={`inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium border ${config.bgColor} ${config.textColor} ${config.borderColor}`}>
      <span className={`h-1.5 w-1.5 rounded-full ${config.dotColor} ${status === 'online' ? 'animate-pulse' : ''} ${status === 'provisioning' ? 'animate-pulse' : ''}`} />
      {config.label}
    </span>
  )
}

// Tool chip component with improved styling
function ToolChip({ tool }: { tool: string }) {
  // Tool-specific colors
  const getToolColor = (toolName: string) => {
    const name = toolName.toLowerCase()
    if (name.includes('nextcloud')) return 'bg-blue-100 text-blue-700 border-blue-200 dark:bg-blue-900/30 dark:text-blue-300 dark:border-blue-800'
    if (name.includes('keycloak')) return 'bg-purple-100 text-purple-700 border-purple-200 dark:bg-purple-900/30 dark:text-purple-300 dark:border-purple-800'
    if (name.includes('minio')) return 'bg-rose-100 text-rose-700 border-rose-200 dark:bg-rose-900/30 dark:text-rose-300 dark:border-rose-800'
    if (name.includes('poste')) return 'bg-emerald-100 text-emerald-700 border-emerald-200 dark:bg-emerald-900/30 dark:text-emerald-300 dark:border-emerald-800'
    if (name.includes('portainer')) return 'bg-cyan-100 text-cyan-700 border-cyan-200 dark:bg-cyan-900/30 dark:text-cyan-300 dark:border-cyan-800'
    return 'bg-slate-100 text-slate-700 border-slate-200 dark:bg-slate-800 dark:text-slate-300 dark:border-slate-700'
  }

  return (
    <span className={`px-2 py-0.5 text-xs font-medium rounded-md border ${getToolColor(tool)}`}>
      {tool}
    </span>
  )
}

// Enhanced Server card component
function ServerCard({ server }: { server: {
  id: string
  domain: string
  tier: string
  serverStatus: ServerStatus
  serverIp: string
  sshPort: number
  tools: string[]
  createdAt: Date | string
  customer: {
    id: string
    name: string | null
    email: string
    company: string | null
  }
}}) {
  const config = statusConfig[server.serverStatus]
  const StatusIcon = config.icon

  return (
    <Card className={`group relative overflow-hidden border hover:shadow-lg hover:border-muted-foreground/20 transition-all duration-300 bg-gradient-to-br ${config.cardGradient}`}>
      {/* Subtle gradient overlay on hover */}
      <div className="absolute inset-0 bg-gradient-to-br from-primary/0 to-primary/0 group-hover:from-primary/[0.02] group-hover:to-primary/[0.04] transition-all duration-300" />

      <CardContent className="relative pt-6">
        {/* Header with icon and status */}
        <div className="flex items-start justify-between mb-4">
          <div className="flex items-center gap-3">
            <div className={`flex h-12 w-12 items-center justify-center rounded-xl ${config.iconBg} ring-1 ring-inset ring-black/5 group-hover:scale-105 transition-transform duration-300`}>
              <Server className={`h-6 w-6 ${config.iconColor}`} />
            </div>
            <div className="min-w-0">
              <div className="flex items-center gap-2 flex-wrap">
                <Link href={`/admin/servers/${server.id}`} className="hover:underline">
                  <h3 className="font-semibold text-base truncate group-hover:text-primary transition-colors">
                    {server.domain}
                  </h3>
                </Link>
              </div>
              <p className="text-sm text-muted-foreground font-mono truncate">{server.serverIp}</p>
            </div>
          </div>
          <Link href={`/admin/servers/${server.id}`}>
            <Button
              variant="ghost"
              size="icon"
              className="h-9 w-9 opacity-70 group-hover:opacity-100 group-hover:bg-primary/10 transition-all"
            >
              <ExternalLink className="h-4 w-4" />
            </Button>
          </Link>
        </div>

        {/* Status badge */}
        <div className="mb-4">
          <ServerStatusBadge status={server.serverStatus} />
        </div>

        {/* Server details grid */}
        <div className="grid grid-cols-2 gap-3 text-sm mb-4">
          <div className="flex items-center gap-2 p-2 rounded-lg bg-muted/30">
            <User className="h-4 w-4 text-muted-foreground shrink-0" />
            <div className="min-w-0">
              <p className="font-medium truncate">{server.customer.name || server.customer.email}</p>
              {server.customer.company && (
                <p className="text-xs text-muted-foreground truncate">{server.customer.company}</p>
              )}
            </div>
          </div>
          <div className="flex items-center gap-2 p-2 rounded-lg bg-muted/30">
            <Globe className="h-4 w-4 text-muted-foreground shrink-0" />
            <span className="capitalize truncate">{server.tier.replace('_', ' ').toLowerCase()}</span>
          </div>
          <div className="flex items-center gap-2 p-2 rounded-lg bg-muted/30">
            <Cpu className="h-4 w-4 text-muted-foreground shrink-0" />
            <span className="truncate">SSH: {server.sshPort}</span>
          </div>
          <div className="flex items-center gap-2 p-2 rounded-lg bg-muted/30">
            <Calendar className="h-4 w-4 text-muted-foreground shrink-0" />
            <span className="truncate">{new Date(server.createdAt).toLocaleDateString()}</span>
          </div>
        </div>

        {/* Tools section */}
        <div className="pt-3 border-t border-border/50">
          <div className="flex items-center gap-2 mb-2">
            <Package className="h-4 w-4 text-muted-foreground" />
            <span className="text-sm font-medium">Tools ({server.tools.length})</span>
          </div>
          <div className="flex flex-wrap gap-1.5">
            {server.tools.slice(0, 4).map((tool) => (
              <ToolChip key={tool} tool={tool} />
            ))}
            {server.tools.length > 4 && (
              <span className="px-2 py-0.5 text-xs font-medium rounded-md bg-muted text-muted-foreground">
                +{server.tools.length - 4} more
              </span>
            )}
          </div>
        </div>
      </CardContent>
    </Card>
  )
}

// Stats card component
function StatsCard({
  icon: Icon,
  value,
  label,
  iconBg,
  iconColor,
  trend
}: {
  icon: typeof Server
  value: number
  label: string
  iconBg: string
  iconColor: string
  trend?: 'up' | 'down' | 'neutral'
}) {
  return (
    <Card className="relative overflow-hidden hover:shadow-md transition-all duration-300">
      <div className="absolute top-0 right-0 -mt-4 -mr-4 h-24 w-24 rounded-full bg-gradient-to-br from-primary/5 to-transparent blur-2xl" />
      <CardContent className="relative pt-6">
        <div className="flex items-center gap-4">
          <div className={`p-3 rounded-xl ${iconBg} ring-1 ring-inset ring-black/5`}>
            <Icon className={`h-6 w-6 ${iconColor}`} />
          </div>
          <div>
            <div className="text-3xl font-bold tabular-nums">{value}</div>
            <p className="text-sm text-muted-foreground">{label}</p>
          </div>
        </div>
      </CardContent>
    </Card>
  )
}

// Empty state component with illustration
function EmptyState({
  hasFilters,
  onClearFilters
}: {
  hasFilters: boolean
  onClearFilters: () => void
}) {
  return (
    <div className="flex flex-col items-center justify-center py-16 px-4">
      {/* Illustration */}
      <div className="relative mb-6">
        <div className="absolute inset-0 bg-gradient-to-br from-primary/10 to-primary/5 rounded-full blur-2xl" />
        <div className="relative flex items-center justify-center h-24 w-24 rounded-2xl bg-muted/60 ring-1 ring-inset ring-black/5">
          <ServerCrash className="h-12 w-12 text-muted-foreground/60" />
        </div>
      </div>

      <h3 className="text-xl font-semibold text-center mb-2">No servers found</h3>
      <p className="text-muted-foreground text-center max-w-md mb-6">
        {hasFilters
          ? 'No servers match your current filters. Try adjusting your search criteria or clear the filters to see all servers.'
          : 'Servers will appear here once orders are provisioned. Create a new order to get started.'}
      </p>

      {hasFilters && (
        <Button variant="outline" onClick={onClearFilters} className="gap-2">
          <XCircle className="h-4 w-4" />
          Clear all filters
        </Button>
      )}
    </div>
  )
}

// Pagination component
function Pagination({
  currentPage,
  totalPages,
  onPageChange
}: {
  currentPage: number
  totalPages: number
  onPageChange: (page: number) => void
}) {
  const pages = useMemo(() => {
    const items: (number | 'ellipsis')[] = []
    const showEllipsisStart = currentPage > 3
    const showEllipsisEnd = currentPage < totalPages - 2

    if (totalPages <= 7) {
      // Show all pages
      for (let i = 1; i <= totalPages; i++) {
        items.push(i)
      }
    } else {
      // Always show first page
      items.push(1)

      if (showEllipsisStart) {
        items.push('ellipsis')
      }

      // Show pages around current
      const start = Math.max(2, currentPage - 1)
      const end = Math.min(totalPages - 1, currentPage + 1)

      for (let i = start; i <= end; i++) {
        if (!items.includes(i)) items.push(i)
      }

      if (showEllipsisEnd) {
        items.push('ellipsis')
      }

      // Always show last page
      if (!items.includes(totalPages)) items.push(totalPages)
    }

    return items
  }, [currentPage, totalPages])

  return (
    <div className="flex items-center justify-between pt-6 border-t">
      <p className="text-sm text-muted-foreground">
        Page <span className="font-medium">{currentPage}</span> of <span className="font-medium">{totalPages}</span>
      </p>

      <div className="flex items-center gap-1">
        <Button
          variant="outline"
          size="sm"
          onClick={() => onPageChange(currentPage - 1)}
          disabled={currentPage === 1}
          className="h-9 px-3"
        >
          <ChevronLeft className="h-4 w-4 mr-1" />
          Previous
        </Button>

        <div className="hidden sm:flex items-center gap-1 mx-2">
          {pages.map((page, idx) => (
            page === 'ellipsis' ? (
              <span key={`ellipsis-${idx}`} className="px-2 text-muted-foreground">...</span>
            ) : (
              <Button
                key={page}
                variant={currentPage === page ? 'default' : 'ghost'}
                size="sm"
                onClick={() => onPageChange(page)}
                className={`h-9 w-9 p-0 ${currentPage === page ? 'pointer-events-none' : ''}`}
              >
                {page}
              </Button>
            )
          ))}
        </div>

        <Button
          variant="outline"
          size="sm"
          onClick={() => onPageChange(currentPage + 1)}
          disabled={currentPage === totalPages}
          className="h-9 px-3"
        >
          Next
          <ChevronRight className="h-4 w-4 ml-1" />
        </Button>
      </div>
    </div>
  )
}

export default function ServersPage() {
  const [search, setSearch] = useState('')
  const [statusFilter, setStatusFilter] = useState<ServerStatus | 'all'>('all')
  const [currentPage, setCurrentPage] = useState(1)
  const itemsPerPage = 12

  // Fetch servers from API
  const {
    data,
    isLoading,
    isError,
    error,
    refetch,
    isFetching,
  } = useServers({
    search: search || undefined,
    status: statusFilter !== 'all' ? statusFilter : undefined,
    page: currentPage,
    limit: itemsPerPage,
  })

  // Calculate stats from data
  const stats = useMemo(() => {
    const servers = data?.servers || []
    return {
      total: data?.pagination?.total || 0,
      online: servers.filter((s) => s.serverStatus === 'online').length,
      provisioning: servers.filter((s) => s.serverStatus === 'provisioning').length,
      offline: servers.filter((s) => s.serverStatus === 'offline').length,
    }
  }, [data])

  const totalPages = data?.pagination?.totalPages || 1
  const hasFilters = Boolean(search || statusFilter !== 'all')

  const clearFilters = () => {
    setSearch('')
    setStatusFilter('all')
    setCurrentPage(1)
  }

  // Loading state
  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center py-24 gap-4">
        <div className="relative">
          <div className="absolute inset-0 bg-primary/20 rounded-full blur-xl animate-pulse" />
          <div className="relative p-4 rounded-full bg-muted">
            <Loader2 className="h-8 w-8 animate-spin text-primary" />
          </div>
        </div>
        <p className="text-sm text-muted-foreground">Loading servers...</p>
      </div>
    )
  }

  // Error state
  if (isError) {
    return (
      <div className="flex flex-col items-center justify-center py-24 gap-4">
        <div className="relative">
          <div className="absolute inset-0 bg-destructive/20 rounded-full blur-xl" />
          <div className="relative p-4 rounded-full bg-destructive/10">
            <AlertCircle className="h-8 w-8 text-destructive" />
          </div>
        </div>
        <div className="text-center">
          <p className="font-medium text-destructive mb-1">Failed to load servers</p>
          <p className="text-sm text-muted-foreground max-w-md">
            {error instanceof Error ? error.message : 'An unexpected error occurred'}
          </p>
        </div>
        <Button variant="outline" onClick={() => refetch()} disabled={isFetching} className="gap-2">
          <RefreshCw className={`h-4 w-4 ${isFetching ? 'animate-spin' : ''}`} />
          {isFetching ? 'Retrying...' : 'Try again'}
        </Button>
      </div>
    )
  }

  return (
    <div className="space-y-8">
      {/* Hero Header Section */}
      <div className="relative overflow-hidden rounded-2xl border bg-gradient-to-br from-card via-card to-muted/30 p-6 md:p-8">
        {/* Background decorations */}
        <div className="absolute top-0 right-0 -mt-16 -mr-16 h-64 w-64 rounded-full bg-gradient-to-br from-primary/5 to-primary/10 blur-3xl" />
        <div className="absolute bottom-0 left-0 -mb-16 -ml-16 h-48 w-48 rounded-full bg-gradient-to-tr from-emerald-500/5 to-transparent blur-2xl" />
        <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 h-32 w-32 rounded-full bg-gradient-to-br from-blue-500/5 to-transparent blur-2xl" />

        <div className="relative flex flex-col md:flex-row md:items-center md:justify-between gap-4">
          <div className="flex items-center gap-4">
            <div className="p-4 rounded-2xl bg-gradient-to-br from-primary/10 to-primary/5 ring-1 ring-inset ring-primary/10">
              <Server className="h-8 w-8 text-primary" />
            </div>
            <div>
              <h1 className="text-2xl md:text-3xl font-bold tracking-tight">Servers</h1>
              <p className="text-muted-foreground mt-1">
                Manage and monitor your deployed infrastructure
              </p>
            </div>
          </div>
          <Button
            variant="outline"
            size="sm"
            onClick={() => refetch()}
            disabled={isFetching}
            className="shrink-0 gap-2 self-start md:self-auto"
          >
            <RefreshCw className={`h-4 w-4 ${isFetching ? 'animate-spin' : ''}`} />
            Refresh
          </Button>
        </div>
      </div>

      {/* Stats Cards Grid */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <StatsCard
          icon={Server}
          value={stats.total}
          label="Total Servers"
          iconBg="bg-slate-100 dark:bg-slate-800"
          iconColor="text-slate-600 dark:text-slate-400"
        />
        <StatsCard
          icon={CheckCircle}
          value={stats.online}
          label="Online"
          iconBg="bg-emerald-100 dark:bg-emerald-900/50"
          iconColor="text-emerald-600 dark:text-emerald-400"
        />
        <StatsCard
          icon={Activity}
          value={stats.provisioning}
          label="Provisioning"
          iconBg="bg-blue-100 dark:bg-blue-900/50"
          iconColor="text-blue-600 dark:text-blue-400"
        />
        <StatsCard
          icon={XCircle}
          value={stats.offline}
          label="Offline"
          iconBg="bg-red-100 dark:bg-red-900/50"
          iconColor="text-red-600 dark:text-red-400"
        />
      </div>

      {/* Filters Section */}
      <Card className="border-0 shadow-sm">
        <CardHeader className="pb-4">
          <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
            <div>
              <CardTitle className="text-lg">All Servers</CardTitle>
              <CardDescription className="mt-1">
                {data?.pagination?.total || 0} server{(data?.pagination?.total || 0) !== 1 ? 's' : ''} found
                {hasFilters && ' with current filters'}
              </CardDescription>
            </div>
            <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3">
              {/* Search Input */}
              <div className="relative">
                <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <Input
                  type="search"
                  placeholder="Search by domain, IP..."
                  value={search}
                  onChange={(e) => {
                    setSearch(e.target.value)
                    setCurrentPage(1)
                  }}
                  className="pl-10 w-full sm:w-64 bg-muted/30 border-muted-foreground/20 focus:bg-background transition-colors"
                />
              </div>

              {/* Status Filter */}
              <div className="relative">
                <Filter className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground pointer-events-none" />
                <select
                  value={statusFilter}
                  onChange={(e) => {
                    setStatusFilter(e.target.value as ServerStatus | 'all')
                    setCurrentPage(1)
                  }}
                  className="h-10 w-full sm:w-auto pl-10 pr-8 rounded-md border border-muted-foreground/20 bg-muted/30 text-sm focus:outline-none focus:ring-2 focus:ring-ring focus:bg-background transition-colors appearance-none cursor-pointer"
                >
                  <option value="all">All Status</option>
                  <option value="online">Online</option>
                  <option value="provisioning">Provisioning</option>
                  <option value="offline">Offline</option>
                  <option value="pending">Pending</option>
                </select>
                <ChevronLeft className="absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 rotate-[270deg] text-muted-foreground pointer-events-none" />
              </div>
            </div>
          </div>
        </CardHeader>

        <CardContent>
          {data?.servers && data.servers.length > 0 ? (
            <>
              {/* Server Cards Grid */}
              <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
                {data.servers.map((server) => (
                  <ServerCard key={server.id} server={server} />
                ))}
              </div>

              {/* Pagination */}
              {totalPages > 1 && (
                <Pagination
                  currentPage={currentPage}
                  totalPages={totalPages}
                  onPageChange={setCurrentPage}
                />
              )}
            </>
          ) : (
            <EmptyState hasFilters={hasFilters} onClearFilters={clearFilters} />
          )}
        </CardContent>
      </Card>
    </div>
  )
}
