'use client'

import Link from 'next/link'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { useDashboardStats } from '@/hooks/use-stats'
import {
  ShoppingCart,
  Users,
  Server,
  TrendingUp,
  Clock,
  CheckCircle,
  AlertCircle,
  ArrowRight,
  Loader2,
  RefreshCw,
  LayoutDashboard,
  Activity,
} from 'lucide-react'

// Enhanced stats card with icon backgrounds and hover effects
function StatsCard({
  title,
  value,
  description,
  icon: Icon,
  isLoading,
  iconBgColor = 'bg-blue-100 dark:bg-blue-900/30',
  iconColor = 'text-blue-600 dark:text-blue-400',
}: {
  title: string
  value: string | number
  description: string
  icon: React.ElementType
  isLoading?: boolean
  iconBgColor?: string
  iconColor?: string
}) {
  return (
    <Card className="rounded-xl border bg-gradient-to-br from-card to-muted/20 hover:shadow-lg hover:border-muted-foreground/20 transition-all duration-200">
      <CardHeader className="flex flex-row items-center justify-between pb-2">
        <CardTitle className="text-sm font-medium text-muted-foreground">
          {title}
        </CardTitle>
        <div className={`p-2.5 rounded-lg ${iconBgColor}`}>
          <Icon className={`h-4 w-4 ${iconColor}`} />
        </div>
      </CardHeader>
      <CardContent>
        {isLoading ? (
          <div className="h-8 w-20 bg-muted animate-pulse rounded" />
        ) : (
          <div className="text-3xl font-bold tracking-tight tabular-nums">{value}</div>
        )}
        <p className="text-xs text-muted-foreground mt-1">{description}</p>
      </CardContent>
    </Card>
  )
}

// Enhanced order status badge with dot indicator
function OrderStatusBadge({ status }: { status: string }) {
  const statusConfig: Record<string, {
    label: string
    bgColor: string
    textColor: string
    borderColor: string
    dotColor: string
    pulse?: boolean
  }> = {
    PAYMENT_CONFIRMED: {
      label: 'Payment Confirmed',
      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'
    },
    AWAITING_SERVER: {
      label: 'Awaiting Server',
      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',
      pulse: true
    },
    SERVER_READY: {
      label: 'Server Ready',
      bgColor: 'bg-purple-50 dark:bg-purple-950/30',
      textColor: 'text-purple-700 dark:text-purple-400',
      borderColor: 'border-purple-200 dark:border-purple-800',
      dotColor: 'bg-purple-500'
    },
    DNS_PENDING: {
      label: 'DNS Pending',
      bgColor: 'bg-orange-50 dark:bg-orange-950/30',
      textColor: 'text-orange-700 dark:text-orange-400',
      borderColor: 'border-orange-200 dark:border-orange-800',
      dotColor: 'bg-orange-500',
      pulse: true
    },
    DNS_READY: {
      label: 'DNS Ready',
      bgColor: 'bg-cyan-50 dark:bg-cyan-950/30',
      textColor: 'text-cyan-700 dark:text-cyan-400',
      borderColor: 'border-cyan-200 dark:border-cyan-800',
      dotColor: 'bg-cyan-500'
    },
    PROVISIONING: {
      label: 'Provisioning',
      bgColor: 'bg-indigo-50 dark:bg-indigo-950/30',
      textColor: 'text-indigo-700 dark:text-indigo-400',
      borderColor: 'border-indigo-200 dark:border-indigo-800',
      dotColor: 'bg-indigo-500',
      pulse: true
    },
    FULFILLED: {
      label: 'Fulfilled',
      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'
    },
    EMAIL_CONFIGURED: {
      label: 'Complete',
      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'
    },
    FAILED: {
      label: 'Failed',
      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'
    },
  }

  const config = statusConfig[status] || {
    label: status,
    bgColor: 'bg-slate-50 dark:bg-slate-950/30',
    textColor: 'text-slate-700 dark:text-slate-400',
    borderColor: 'border-slate-200 dark:border-slate-800',
    dotColor: 'bg-slate-500'
  }

  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} ${config.pulse ? 'animate-pulse' : ''}`} />
      {config.label}
    </span>
  )
}

// Format time since
function formatTimeSince(date: Date | string): string {
  const now = new Date()
  const then = new Date(date)
  const diffMs = now.getTime() - then.getTime()
  const diffMins = Math.floor(diffMs / 60000)
  const diffHours = Math.floor(diffMins / 60)
  const diffDays = Math.floor(diffHours / 24)

  if (diffMins < 1) return 'Just now'
  if (diffMins < 60) return `${diffMins}m ago`
  if (diffHours < 24) return `${diffHours}h ago`
  if (diffDays < 7) return `${diffDays}d ago`
  return then.toLocaleDateString()
}

// Recent orders component with enhanced styling
function RecentOrders({ orders, isLoading }: {
  orders: Array<{
    id: string
    domain: string
    status: string
    createdAt: Date | string
    user: { name: string | null; email: string; company: string | null }
  }>
  isLoading: boolean
}) {
  return (
    <Card className="col-span-2 rounded-xl border bg-gradient-to-br from-card to-muted/10">
      <CardHeader className="flex flex-row items-center justify-between pb-4">
        <div className="flex items-center gap-3">
          <div className="p-2 rounded-lg bg-muted">
            <ShoppingCart className="h-4 w-4 text-muted-foreground" />
          </div>
          <div>
            <CardTitle className="text-lg tracking-tight">Recent Orders</CardTitle>
            <CardDescription>Latest customer provisioning orders</CardDescription>
          </div>
        </div>
        <Link href="/admin/orders">
          <Button variant="ghost" size="sm" className="gap-1.5 text-muted-foreground hover:text-foreground">
            View All <ArrowRight className="h-4 w-4" />
          </Button>
        </Link>
      </CardHeader>
      <CardContent>
        {isLoading ? (
          <div className="space-y-3">
            {[1, 2, 3, 4].map((i) => (
              <div key={i} className="flex items-center justify-between rounded-xl border bg-card p-4">
                <div className="space-y-2">
                  <div className="h-4 w-36 bg-muted animate-pulse rounded" />
                  <div className="h-3 w-24 bg-muted animate-pulse rounded" />
                </div>
                <div className="h-6 w-24 bg-muted animate-pulse rounded-full" />
              </div>
            ))}
          </div>
        ) : orders.length === 0 ? (
          <div className="text-center py-12 rounded-xl border-2 border-dashed border-muted-foreground/20 bg-muted/20">
            <ShoppingCart className="h-10 w-10 mx-auto text-muted-foreground/50 mb-3" />
            <p className="text-muted-foreground font-medium">No orders yet</p>
            <p className="text-sm text-muted-foreground/70 mt-1">
              Orders will appear here when customers place them
            </p>
          </div>
        ) : (
          <div className="space-y-3">
            {orders.map((order) => (
              <Link
                key={order.id}
                href={`/admin/orders/${order.id}`}
                className="group flex items-center justify-between rounded-xl border bg-card p-4 hover:bg-muted/30 hover:border-muted-foreground/20 hover:shadow-md transition-all"
              >
                <div className="space-y-1">
                  <p className="font-medium group-hover:text-primary transition-colors">{order.domain}</p>
                  <p className="text-sm text-muted-foreground">
                    {order.user.name || order.user.company || order.user.email}
                  </p>
                </div>
                <div className="flex items-center gap-4">
                  <span className="text-sm text-muted-foreground tabular-nums">
                    {formatTimeSince(order.createdAt)}
                  </span>
                  <OrderStatusBadge status={order.status} />
                </div>
              </Link>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  )
}

// Enhanced pipeline overview component
function PipelineOverview({ stats, isLoading }: {
  stats: {
    pending: number
    inProgress: number
    completed: number
    failed: number
  } | null
  isLoading: boolean
}) {
  const stages = [
    {
      name: 'Payment & Server',
      count: stats?.pending || 0,
      icon: Clock,
      iconBgColor: 'bg-amber-100 dark:bg-amber-900/30',
      iconColor: 'text-amber-600 dark:text-amber-400',
      barColor: 'bg-amber-500'
    },
    {
      name: 'Provisioning',
      count: stats?.inProgress || 0,
      icon: TrendingUp,
      iconBgColor: 'bg-indigo-100 dark:bg-indigo-900/30',
      iconColor: 'text-indigo-600 dark:text-indigo-400',
      barColor: 'bg-indigo-500'
    },
    {
      name: 'Completed',
      count: stats?.completed || 0,
      icon: CheckCircle,
      iconBgColor: 'bg-emerald-100 dark:bg-emerald-900/30',
      iconColor: 'text-emerald-600 dark:text-emerald-400',
      barColor: 'bg-emerald-500'
    },
    {
      name: 'Failed',
      count: stats?.failed || 0,
      icon: AlertCircle,
      iconBgColor: 'bg-red-100 dark:bg-red-900/30',
      iconColor: 'text-red-600 dark:text-red-400',
      barColor: 'bg-red-500'
    },
  ]

  const total = stages.reduce((acc, stage) => acc + stage.count, 0)

  return (
    <Card className="rounded-xl border bg-gradient-to-br from-card to-muted/10">
      <CardHeader className="pb-4">
        <div className="flex items-center gap-3">
          <div className="p-2 rounded-lg bg-muted">
            <Activity className="h-4 w-4 text-muted-foreground" />
          </div>
          <div>
            <CardTitle className="text-lg tracking-tight">Order Pipeline</CardTitle>
            <CardDescription>Orders by current stage</CardDescription>
          </div>
        </div>
      </CardHeader>
      <CardContent>
        <div className="space-y-4">
          {stages.map((stage) => {
            const percentage = total > 0 ? (stage.count / total) * 100 : 0
            return (
              <div key={stage.name} className="group">
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center gap-3">
                    <div className={`p-2 rounded-lg ${stage.iconBgColor} transition-transform group-hover:scale-110`}>
                      <stage.icon className={`h-4 w-4 ${stage.iconColor}`} />
                    </div>
                    <span className="text-sm font-medium">{stage.name}</span>
                  </div>
                  {isLoading ? (
                    <div className="h-5 w-10 bg-muted animate-pulse rounded" />
                  ) : (
                    <span className="font-bold tabular-nums text-lg">{stage.count}</span>
                  )}
                </div>
                {!isLoading && total > 0 && (
                  <div className="h-1.5 bg-muted/60 rounded-full overflow-hidden ml-11">
                    <div
                      className={`h-full ${stage.barColor} transition-all duration-500 ease-out rounded-full`}
                      style={{ width: `${percentage}%` }}
                    />
                  </div>
                )}
              </div>
            )
          })}
        </div>
        <div className="mt-6 pt-4 border-t">
          <Link href="/admin/orders">
            <Button variant="outline" className="w-full gap-2 hover:bg-muted/50">
              <TrendingUp className="h-4 w-4" />
              View Pipeline
            </Button>
          </Link>
        </div>
      </CardContent>
    </Card>
  )
}

export default function AdminDashboard() {
  const { data: stats, isLoading, isError, refetch, isFetching } = useDashboardStats()

  // Error state
  if (isError) {
    return (
      <div className="flex items-center justify-center h-[50vh]">
        <div className="flex flex-col items-center gap-4 text-center p-8 rounded-xl border-2 border-dashed border-destructive/20 bg-destructive/5">
          <div className="p-4 rounded-full bg-destructive/10">
            <AlertCircle className="h-8 w-8 text-destructive" />
          </div>
          <div>
            <p className="font-semibold text-destructive text-lg">Failed to load dashboard</p>
            <p className="text-sm text-muted-foreground mt-1">Could not fetch statistics</p>
          </div>
          <Button variant="outline" onClick={() => refetch()} disabled={isFetching} className="gap-2">
            <RefreshCw className={`h-4 w-4 ${isFetching ? 'animate-spin' : ''}`} />
            {isFetching ? 'Retrying...' : 'Retry'}
          </Button>
        </div>
      </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 decorative elements */}
        <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-primary/5 to-transparent blur-2xl" />

        <div className="relative flex flex-col sm:flex-row sm:items-center sm: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 border border-primary/20">
              <LayoutDashboard className="h-8 w-8 text-primary" />
            </div>
            <div>
              <h1 className="text-2xl md:text-3xl font-bold tracking-tight">Dashboard</h1>
              <p className="text-muted-foreground mt-1">
                Overview of your LetsBe Hub platform
              </p>
            </div>
          </div>
          <Button
            variant="outline"
            size="sm"
            onClick={() => refetch()}
            disabled={isFetching}
            className="shrink-0 gap-2"
          >
            <RefreshCw className={`h-4 w-4 ${isFetching ? 'animate-spin' : ''}`} />
            Refresh
          </Button>
        </div>
      </div>

      {/* Stats grid with enhanced cards */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <StatsCard
          title="Total Orders"
          value={stats?.orders.total || 0}
          description="All time orders"
          icon={ShoppingCart}
          isLoading={isLoading}
          iconBgColor="bg-blue-100 dark:bg-blue-900/30"
          iconColor="text-blue-600 dark:text-blue-400"
        />
        <StatsCard
          title="Active Customers"
          value={stats?.customers.active || 0}
          description="Verified customers"
          icon={Users}
          isLoading={isLoading}
          iconBgColor="bg-violet-100 dark:bg-violet-900/30"
          iconColor="text-violet-600 dark:text-violet-400"
        />
        <StatsCard
          title="Completed Deployments"
          value={stats?.orders.completed || 0}
          description="Successfully provisioned"
          icon={Server}
          isLoading={isLoading}
          iconBgColor="bg-emerald-100 dark:bg-emerald-900/30"
          iconColor="text-emerald-600 dark:text-emerald-400"
        />
        <StatsCard
          title="Pending Actions"
          value={stats?.orders.pending || 0}
          description="Orders needing attention"
          icon={Clock}
          isLoading={isLoading}
          iconBgColor="bg-amber-100 dark:bg-amber-900/30"
          iconColor="text-amber-600 dark:text-amber-400"
        />
      </div>

      {/* Main content grid */}
      <div className="grid gap-6 lg:grid-cols-3">
        <RecentOrders
          orders={stats?.recentOrders || []}
          isLoading={isLoading}
        />
        <PipelineOverview
          stats={stats?.orders ? {
            pending: stats.orders.pending,
            inProgress: stats.orders.inProgress,
            completed: stats.orders.completed,
            failed: stats.orders.failed,
          } : null}
          isLoading={isLoading}
        />
      </div>
    </div>
  )
}
