'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 { useCustomers } from '@/hooks/use-customers'
import { AddCustomerDialog } from '@/components/admin/AddCustomerDialog'
import { UserStatus as ApiUserStatus } from '@/types/api'
import {
  Search,
  Plus,
  MoreHorizontal,
  User,
  Mail,
  Building2,
  Calendar,
  Server,
  ExternalLink,
  ChevronLeft,
  ChevronRight,
  Loader2,
  AlertCircle,
  RefreshCw,
  Users,
  UserCheck,
  Clock,
  Zap,
  UserX,
} from 'lucide-react'

type UserStatus = 'ACTIVE' | 'SUSPENDED' | 'PENDING_VERIFICATION'
type SubscriptionStatus = 'TRIAL' | 'ACTIVE' | 'CANCELED' | 'PAST_DUE'

interface Customer {
  id: string
  name: string
  email: string
  company: string | null
  status: UserStatus
  subscription: {
    plan: string
    tier: string
    status: SubscriptionStatus
    tokensUsed: number
    tokenLimit: number
  } | null
  activeServers: number
  createdAt: string
}

// Status badge component with dot indicator and animations
function UserStatusBadge({ status }: { status: UserStatus }) {
  const statusConfig: Record<UserStatus, {
    label: string
    bgColor: string
    textColor: string
    borderColor: string
    dotColor: string
    animate: boolean
  }> = {
    ACTIVE: {
      label: 'Active',
      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',
      animate: true
    },
    SUSPENDED: {
      label: 'Suspended',
      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',
      animate: false
    },
    PENDING_VERIFICATION: {
      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',
      animate: true
    },
  }

  const config = statusConfig[status]

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

function SubscriptionBadge({ status }: { status: SubscriptionStatus }) {
  const statusConfig: Record<SubscriptionStatus, {
    label: string
    bgColor: string
    textColor: string
    borderColor: string
    dotColor: string
  }> = {
    TRIAL: {
      label: 'Trial',
      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'
    },
    ACTIVE: {
      label: 'Active',
      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'
    },
    CANCELED: {
      label: 'Canceled',
      bgColor: 'bg-slate-50 dark:bg-slate-950/30',
      textColor: 'text-slate-600 dark:text-slate-400',
      borderColor: 'border-slate-200 dark:border-slate-700',
      dotColor: 'bg-slate-400'
    },
    PAST_DUE: {
      label: 'Past Due',
      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]

  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.label}
    </span>
  )
}

// Token usage progress bar with gradient colors based on threshold
function TokenUsageBar({ used, limit }: { used: number; limit: number }) {
  const percentage = limit > 0 ? Math.min((used / limit) * 100, 100) : 0

  // Determine gradient based on usage threshold
  const getGradientClass = () => {
    if (percentage > 90) return 'bg-gradient-to-r from-red-500 to-red-600'
    if (percentage > 75) return 'bg-gradient-to-r from-amber-500 to-orange-500'
    if (percentage > 50) return 'bg-gradient-to-r from-blue-500 to-blue-600'
    return 'bg-gradient-to-r from-emerald-500 to-emerald-600'
  }

  return (
    <div className="space-y-1.5">
      <div className="flex items-center justify-between text-xs">
        <span className="text-muted-foreground">{used.toLocaleString()}</span>
        <span className="font-medium tabular-nums">{percentage.toFixed(0)}%</span>
      </div>
      <div className="h-2 bg-muted/60 rounded-full overflow-hidden ring-1 ring-inset ring-black/5">
        <div
          className={`h-full ${getGradientClass()} transition-all duration-500 ease-out rounded-full`}
          style={{ width: `${percentage}%` }}
        />
      </div>
      <div className="text-xs text-muted-foreground text-right">
        of {limit.toLocaleString()}
      </div>
    </div>
  )
}

// Customer card-style row component
function CustomerRow({ customer }: { customer: Customer }) {
  return (
    <div className="group relative flex items-center justify-between p-4 rounded-xl border bg-card hover:bg-muted/30 hover:border-muted-foreground/20 hover:shadow-md transition-all">
      {/* Customer Info */}
      <div className="flex items-center gap-4 min-w-0 flex-1">
        <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br from-primary/10 to-primary/20 group-hover:from-primary/20 group-hover:to-primary/30 transition-colors">
          <User className="h-6 w-6 text-primary" />
        </div>
        <div className="min-w-0">
          <Link
            href={`/admin/customers/${customer.id}`}
            className="font-semibold hover:text-primary transition-colors block truncate"
          >
            {customer.name}
          </Link>
          <div className="flex items-center gap-2 text-sm text-muted-foreground mt-0.5">
            <Mail className="h-3.5 w-3.5 flex-shrink-0" />
            <span className="truncate">{customer.email}</span>
          </div>
          {customer.company && (
            <div className="flex items-center gap-2 text-xs text-muted-foreground mt-1">
              <Building2 className="h-3 w-3 flex-shrink-0" />
              <span className="truncate">{customer.company}</span>
            </div>
          )}
        </div>
      </div>

      {/* Status */}
      <div className="hidden md:flex items-center justify-center px-4">
        <UserStatusBadge status={customer.status} />
      </div>

      {/* Subscription */}
      <div className="hidden lg:block px-4 min-w-[140px]">
        {customer.subscription ? (
          <div className="space-y-1">
            <div className="flex items-center gap-2">
              <span className="font-medium capitalize text-sm">{customer.subscription.plan.toLowerCase()}</span>
              <SubscriptionBadge status={customer.subscription.status} />
            </div>
            <span className="text-xs text-muted-foreground capitalize">
              {customer.subscription.tier.replace('_', ' ').toLowerCase()}
            </span>
          </div>
        ) : (
          <span className="text-sm text-muted-foreground">No subscription</span>
        )}
      </div>

      {/* Token Usage */}
      <div className="hidden xl:block px-4 w-36">
        {customer.subscription && customer.subscription.tokenLimit > 0 ? (
          <TokenUsageBar
            used={customer.subscription.tokensUsed}
            limit={customer.subscription.tokenLimit}
          />
        ) : (
          <span className="text-sm text-muted-foreground">-</span>
        )}
      </div>

      {/* Servers & Date */}
      <div className="hidden sm:flex items-center gap-6 px-4">
        <div className="flex items-center gap-2 text-sm">
          <div className="p-1.5 rounded-lg bg-muted">
            <Server className="h-3.5 w-3.5 text-muted-foreground" />
          </div>
          <span className="font-medium tabular-nums">{customer.activeServers}</span>
        </div>
        <div className="flex items-center gap-2 text-xs text-muted-foreground">
          <Calendar className="h-3.5 w-3.5" />
          {new Date(customer.createdAt).toLocaleDateString()}
        </div>
      </div>

      {/* Actions */}
      <div className="flex items-center gap-1 pl-4 opacity-70 group-hover:opacity-100 transition-opacity">
        <Link href={`/admin/customers/${customer.id}`}>
          <Button variant="ghost" size="sm" className="h-9 w-9 p-0">
            <ExternalLink className="h-4 w-4" />
          </Button>
        </Link>
        <Button variant="ghost" size="sm" className="h-9 w-9 p-0">
          <MoreHorizontal className="h-4 w-4" />
        </Button>
      </div>
    </div>
  )
}

// Stats card component with colored icon backgrounds
function StatsCard({
  title,
  value,
  icon: Icon,
  iconBg,
  iconColor,
  subtitle
}: {
  title: string
  value: number | string
  icon: typeof Users
  iconBg: string
  iconColor: string
  subtitle?: string
}) {
  return (
    <Card className="relative overflow-hidden hover:shadow-lg transition-shadow">
      <CardContent className="p-6">
        <div className="flex items-start justify-between">
          <div className="space-y-1">
            <p className="text-sm font-medium text-muted-foreground">{title}</p>
            <p className="text-3xl font-bold tabular-nums">{value}</p>
            {subtitle && (
              <p className="text-xs text-muted-foreground">{subtitle}</p>
            )}
          </div>
          <div className={`p-3 rounded-xl ${iconBg}`}>
            <Icon className={`h-5 w-5 ${iconColor}`} />
          </div>
        </div>
      </CardContent>
      {/* Decorative gradient */}
      <div className={`absolute bottom-0 left-0 right-0 h-1 ${iconBg.replace('bg-', 'bg-gradient-to-r from-').replace('/10', '-500/50').replace('/30', '-600/50')} opacity-50`} />
    </Card>
  )
}

// Filter pill toggle component
function FilterPill({
  label,
  isActive,
  onClick,
  count
}: {
  label: string
  isActive: boolean
  onClick: () => void
  count?: number
}) {
  return (
    <button
      onClick={onClick}
      className={`inline-flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all ${
        isActive
          ? 'bg-primary text-primary-foreground shadow-md'
          : 'bg-muted/50 text-muted-foreground hover:bg-muted hover:text-foreground'
      }`}
    >
      {label}
      {count !== undefined && (
        <span className={`text-xs px-1.5 py-0.5 rounded-full ${
          isActive
            ? 'bg-primary-foreground/20'
            : 'bg-muted-foreground/20'
        }`}>
          {count}
        </span>
      )}
    </button>
  )
}

// Empty state component
function EmptyState({
  hasFilters,
  onClearFilters
}: {
  hasFilters: boolean
  onClearFilters: () => void
}) {
  return (
    <div className="flex flex-col items-center justify-center py-16 px-4">
      <div className="relative">
        <div className="absolute inset-0 bg-muted/30 rounded-full blur-2xl" />
        <div className="relative p-6 rounded-full bg-muted/50">
          <UserX className="h-12 w-12 text-muted-foreground/60" />
        </div>
      </div>
      <h3 className="mt-6 font-semibold text-lg">No customers found</h3>
      <p className="mt-2 text-sm text-muted-foreground text-center max-w-sm">
        {hasFilters
          ? "We couldn't find any customers matching your current filters. Try adjusting your search criteria."
          : "You haven't added any customers yet. Get started by adding your first customer."
        }
      </p>
      {hasFilters && (
        <Button
          variant="outline"
          onClick={onClearFilters}
          className="mt-4"
        >
          Clear all filters
        </Button>
      )}
    </div>
  )
}

export default function CustomersPage() {
  const [search, setSearch] = useState('')
  const [statusFilter, setStatusFilter] = useState<string>('all')
  const [currentPage, setCurrentPage] = useState(1)
  const [showAddDialog, setShowAddDialog] = useState(false)
  const itemsPerPage = 10

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

  // Map API customers to component format
  const customers = useMemo<Customer[]>(() => {
    if (!data?.customers) return []
    return data.customers.map((c) => ({
      id: c.id,
      name: c.name || c.email,
      email: c.email,
      company: c.company,
      status: c.status as UserStatus,
      subscription: c.subscriptions?.[0] ? {
        plan: c.subscriptions[0].plan,
        tier: c.subscriptions[0].tier,
        status: c.subscriptions[0].status as SubscriptionStatus,
        tokensUsed: 0, // Not included in list response
        tokenLimit: 0, // Not included in list response
      } : null,
      activeServers: c._count?.orders || 0,
      createdAt: String(c.createdAt),
    }))
  }, [data?.customers])

  // Calculate stats from API data
  const stats = useMemo(() => ({
    total: data?.pagination?.total || 0,
    active: customers.filter((c) => c.status === 'ACTIVE').length,
    trial: customers.filter((c) => c.subscription?.status === 'TRIAL').length,
    totalServers: customers.reduce((acc, c) => acc + c.activeServers, 0),
  }), [customers, data?.pagination?.total])

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

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

  // Loading state
  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center h-[50vh] 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 customers...</p>
      </div>
    )
  }

  // Error state
  if (isError) {
    return (
      <div className="flex flex-col items-center justify-center h-[50vh] 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">Failed to load customers</p>
          <p className="text-sm text-muted-foreground mt-1">
            {error instanceof Error ? error.message : 'An 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...' : 'Retry'}
        </Button>
      </div>
    )
  }

  return (
    <div className="space-y-8">
      {/* Hero Header */}
      <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 decoration */}
        <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/20 border-2 border-primary/10">
              <Users className="h-8 w-8 text-primary" />
            </div>
            <div>
              <h1 className="text-2xl md:text-3xl font-bold tracking-tight">Customers</h1>
              <p className="text-muted-foreground mt-1">
                Manage customer accounts and subscriptions
              </p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => refetch()}
              disabled={isFetching}
              className="gap-2"
            >
              <RefreshCw className={`h-4 w-4 ${isFetching ? 'animate-spin' : ''}`} />
              Refresh
            </Button>
            <Button onClick={() => setShowAddDialog(true)} className="gap-2 shadow-md">
              <Plus className="h-4 w-4" />
              Add Customer
            </Button>
          </div>
        </div>
      </div>

      {/* Stats cards */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <StatsCard
          title="Total Customers"
          value={stats.total}
          icon={Users}
          iconBg="bg-blue-100 dark:bg-blue-900/30"
          iconColor="text-blue-600 dark:text-blue-400"
          subtitle="All registered users"
        />
        <StatsCard
          title="Active"
          value={stats.active}
          icon={UserCheck}
          iconBg="bg-emerald-100 dark:bg-emerald-900/30"
          iconColor="text-emerald-600 dark:text-emerald-400"
          subtitle="Currently active"
        />
        <StatsCard
          title="On Trial"
          value={stats.trial}
          icon={Clock}
          iconBg="bg-amber-100 dark:bg-amber-900/30"
          iconColor="text-amber-600 dark:text-amber-400"
          subtitle="Trial subscriptions"
        />
        <StatsCard
          title="Total Servers"
          value={stats.totalServers}
          icon={Server}
          iconBg="bg-violet-100 dark:bg-violet-900/30"
          iconColor="text-violet-600 dark:text-violet-400"
          subtitle="Across all customers"
        />
      </div>

      {/* Filters and list */}
      <Card className="overflow-hidden">
        <CardHeader className="border-b bg-muted/30">
          <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
            <div>
              <CardTitle className="text-lg">All Customers</CardTitle>
              <CardDescription>
                {data?.pagination?.total || 0} customer{(data?.pagination?.total || 0) !== 1 ? 's' : ''} found
              </CardDescription>
            </div>
            <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
              {/* 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 customers..."
                  value={search}
                  onChange={(e) => {
                    setSearch(e.target.value)
                    setCurrentPage(1)
                  }}
                  className="pl-10 w-full sm:w-72 bg-background"
                />
              </div>
              {/* Status filter pills */}
              <div className="flex items-center gap-2 overflow-x-auto pb-1 sm:pb-0">
                <FilterPill
                  label="All"
                  isActive={statusFilter === 'all'}
                  onClick={() => { setStatusFilter('all'); setCurrentPage(1) }}
                />
                <FilterPill
                  label="Active"
                  isActive={statusFilter === 'ACTIVE'}
                  onClick={() => { setStatusFilter('ACTIVE'); setCurrentPage(1) }}
                />
                <FilterPill
                  label="Suspended"
                  isActive={statusFilter === 'SUSPENDED'}
                  onClick={() => { setStatusFilter('SUSPENDED'); setCurrentPage(1) }}
                />
                <FilterPill
                  label="Pending"
                  isActive={statusFilter === 'PENDING_VERIFICATION'}
                  onClick={() => { setStatusFilter('PENDING_VERIFICATION'); setCurrentPage(1) }}
                />
              </div>
            </div>
          </div>
        </CardHeader>
        <CardContent className="p-4 md:p-6">
          {customers.length === 0 ? (
            <EmptyState hasFilters={hasFilters} onClearFilters={clearFilters} />
          ) : (
            <>
              {/* Customer list */}
              <div className="space-y-3">
                {customers.map((customer) => (
                  <CustomerRow key={customer.id} customer={customer} />
                ))}
              </div>

              {/* Enhanced Pagination */}
              {totalPages > 1 && (
                <div className="mt-6 flex flex-col sm:flex-row items-center justify-between gap-4 pt-6 border-t">
                  <p className="text-sm text-muted-foreground">
                    Showing <span className="font-medium">{(currentPage - 1) * itemsPerPage + 1}</span> to{' '}
                    <span className="font-medium">
                      {Math.min(currentPage * itemsPerPage, data?.pagination?.total || 0)}
                    </span>{' '}
                    of <span className="font-medium">{data?.pagination?.total || 0}</span> customers
                  </p>
                  <div className="flex items-center gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setCurrentPage(currentPage - 1)}
                      disabled={currentPage === 1}
                      className="gap-1.5 h-9 px-4"
                    >
                      <ChevronLeft className="h-4 w-4" />
                      Previous
                    </Button>

                    {/* Page numbers */}
                    <div className="hidden sm:flex items-center gap-1">
                      {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                        let pageNum: number
                        if (totalPages <= 5) {
                          pageNum = i + 1
                        } else if (currentPage <= 3) {
                          pageNum = i + 1
                        } else if (currentPage >= totalPages - 2) {
                          pageNum = totalPages - 4 + i
                        } else {
                          pageNum = currentPage - 2 + i
                        }
                        return (
                          <Button
                            key={pageNum}
                            variant={currentPage === pageNum ? 'default' : 'ghost'}
                            size="sm"
                            onClick={() => setCurrentPage(pageNum)}
                            className={`h-9 w-9 p-0 ${currentPage === pageNum ? 'shadow-md' : ''}`}
                          >
                            {pageNum}
                          </Button>
                        )
                      })}
                    </div>

                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setCurrentPage(currentPage + 1)}
                      disabled={currentPage === totalPages}
                      className="gap-1.5 h-9 px-4"
                    >
                      Next
                      <ChevronRight className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              )}
            </>
          )}
        </CardContent>
      </Card>

      {/* Add Customer Dialog */}
      <AddCustomerDialog
        open={showAddDialog}
        onOpenChange={setShowAddDialog}
      />
    </div>
  )
}
