'use client'

import { useState } 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 {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog'
import { Label } from '@/components/ui/label'
import { useEnterpriseClients, useCreateEnterpriseClient, useAllClientsErrorSummary } from '@/hooks/use-enterprise-clients'
import {
  Search,
  Plus,
  Building2,
  Server,
  AlertTriangle,
  Mail,
  Phone,
  ExternalLink,
  Loader2,
  AlertCircle,
  RefreshCw,
  Users,
  Activity,
  CheckCircle2,
  Zap,
} from 'lucide-react'
import type { ClientErrorSummary } from '@/lib/api/admin'
import type { EnterpriseClientWithDetails } from '@/types/api'
import { EnterpriseErrorSummaryWidget } from '@/components/admin/enterprise-error-summary-widget'

// Stats card component
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>
    </Card>
  )
}

// Client card component
function ClientCard({
  client,
  errorSummary,
}: {
  client: EnterpriseClientWithDetails
  errorSummary?: ClientErrorSummary
}) {
  const activeServers = client.servers?.filter(s => s.isActive).length || 0
  const errorCount = client.statsOverview?.unacknowledgedErrors || 0
  const hasCrashes = (errorSummary?.crashes24h ?? 0) > 0
  const hasCritical = (errorSummary?.criticalErrors24h ?? 0) > 0
  const hasIssues = hasCrashes || hasCritical

  return (
    <Link href={`/admin/enterprise-clients/${client.id}`}>
      <Card className={`group hover:shadow-lg hover:border-primary/50 transition-all cursor-pointer ${hasIssues ? 'border-red-200 dark:border-red-900' : ''}`}>
        <CardContent className="p-6">
          <div className="flex items-start justify-between">
            <div className="flex items-start gap-4">
              <div className={`flex h-12 w-12 items-center justify-center rounded-xl transition-colors ${hasIssues ? 'bg-gradient-to-br from-red-100 to-red-200 dark:from-red-900/30 dark:to-red-800/30' : 'bg-gradient-to-br from-primary/10 to-primary/20 group-hover:from-primary/20 group-hover:to-primary/30'}`}>
                <Building2 className={`h-6 w-6 ${hasIssues ? 'text-red-600 dark:text-red-400' : 'text-primary'}`} />
              </div>
              <div className="space-y-1">
                <div className="flex items-center gap-2">
                  <h3 className="font-semibold group-hover:text-primary transition-colors">
                    {client.name}
                  </h3>
                  {/* Pulsing indicator for critical issues */}
                  {hasIssues && (
                    <span className="relative flex h-2 w-2">
                      <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75"></span>
                      <span className="relative inline-flex rounded-full h-2 w-2 bg-red-500"></span>
                    </span>
                  )}
                </div>
                {client.companyName && (
                  <p className="text-sm text-muted-foreground">{client.companyName}</p>
                )}
                <div className="flex items-center gap-2 text-xs text-muted-foreground">
                  <Mail className="h-3 w-3" />
                  {client.contactEmail}
                </div>
              </div>
            </div>
            <div className="flex flex-col items-end gap-2">
              <div className="flex items-center gap-2">
                {!client.isActive && (
                  <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400">
                    Inactive
                  </span>
                )}
                <ExternalLink className="h-4 w-4 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity" />
              </div>
              {/* Crash and Critical Error Badges */}
              {hasIssues && (
                <div className="flex flex-wrap gap-1 justify-end">
                  {hasCrashes && (
                    <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400 animate-pulse">
                      <AlertCircle className="h-2.5 w-2.5" />
                      {errorSummary?.crashes24h} crashed
                    </span>
                  )}
                  {hasCritical && (
                    <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400">
                      <Zap className="h-2.5 w-2.5" />
                      {errorSummary?.criticalErrors24h} critical
                    </span>
                  )}
                </div>
              )}
            </div>
          </div>

          <div className="mt-6 grid grid-cols-3 gap-4 pt-4 border-t">
            <div className="space-y-1">
              <div className="flex items-center gap-1.5 text-muted-foreground">
                <Server className="h-3.5 w-3.5" />
                <span className="text-xs">Servers</span>
              </div>
              <p className="text-lg font-semibold tabular-nums">
                {activeServers}
                {client._count?.servers !== activeServers && (
                  <span className="text-sm font-normal text-muted-foreground">
                    /{client._count?.servers}
                  </span>
                )}
              </p>
            </div>
            <div className="space-y-1">
              <div className="flex items-center gap-1.5 text-muted-foreground">
                <Activity className="h-3.5 w-3.5" />
                <span className="text-xs">CPU Avg</span>
              </div>
              <p className="text-lg font-semibold tabular-nums">
                {client.statsOverview?.avgCpuPercent != null
                  ? `${client.statsOverview.avgCpuPercent}%`
                  : '-'}
              </p>
            </div>
            <div className="space-y-1">
              <div className="flex items-center gap-1.5 text-muted-foreground">
                <AlertTriangle className="h-3.5 w-3.5" />
                <span className="text-xs">Errors</span>
              </div>
              <p className={`text-lg font-semibold tabular-nums ${errorCount > 0 ? 'text-red-600' : ''}`}>
                {errorCount}
              </p>
            </div>
          </div>
        </CardContent>
      </Card>
    </Link>
  )
}

// Add client dialog
function AddClientDialog({
  open,
  onOpenChange
}: {
  open: boolean
  onOpenChange: (open: boolean) => void
}) {
  const [formData, setFormData] = useState({
    name: '',
    companyName: '',
    contactEmail: '',
    contactPhone: '',
    notes: ''
  })

  const createClient = useCreateEnterpriseClient()

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    try {
      await createClient.mutateAsync({
        name: formData.name,
        companyName: formData.companyName || undefined,
        contactEmail: formData.contactEmail,
        contactPhone: formData.contactPhone || undefined,
        notes: formData.notes || undefined
      })
      setFormData({ name: '', companyName: '', contactEmail: '', contactPhone: '', notes: '' })
      onOpenChange(false)
    } catch {
      // Error handled by mutation
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>Add Enterprise Client</DialogTitle>
          <DialogDescription>
            Add a new enterprise client to manage their infrastructure.
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit}>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label htmlFor="name">Client Name *</Label>
              <Input
                id="name"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                placeholder="Acme Corp"
                required
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="companyName">Company Name</Label>
              <Input
                id="companyName"
                value={formData.companyName}
                onChange={(e) => setFormData({ ...formData, companyName: e.target.value })}
                placeholder="Acme Corporation Ltd."
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="contactEmail">Contact Email *</Label>
              <Input
                id="contactEmail"
                type="email"
                value={formData.contactEmail}
                onChange={(e) => setFormData({ ...formData, contactEmail: e.target.value })}
                placeholder="admin@acme.com"
                required
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="contactPhone">Contact Phone</Label>
              <Input
                id="contactPhone"
                type="tel"
                value={formData.contactPhone}
                onChange={(e) => setFormData({ ...formData, contactPhone: e.target.value })}
                placeholder="+1 555-1234"
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="notes">Notes</Label>
              <Input
                id="notes"
                value={formData.notes}
                onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
                placeholder="Additional notes..."
              />
            </div>
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
            <Button type="submit" disabled={createClient.isPending}>
              {createClient.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Add Client
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}

// Empty state
function EmptyState({ onAddClient }: { onAddClient: () => 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">
          <Building2 className="h-12 w-12 text-muted-foreground/60" />
        </div>
      </div>
      <h3 className="mt-6 font-semibold text-lg">No enterprise clients yet</h3>
      <p className="mt-2 text-sm text-muted-foreground text-center max-w-sm">
        Get started by adding your first enterprise client to manage their infrastructure.
      </p>
      <Button onClick={onAddClient} className="mt-4 gap-2">
        <Plus className="h-4 w-4" />
        Add Enterprise Client
      </Button>
    </div>
  )
}

export default function EnterpriseClientsPage() {
  const [search, setSearch] = useState('')
  const [showAddDialog, setShowAddDialog] = useState(false)

  const { data: clients, isLoading, isError, error, refetch, isFetching } = useEnterpriseClients()
  const { data: errorSummary } = useAllClientsErrorSummary()

  // Create a map of client error summaries for quick lookup
  const errorSummaryMap = new Map(
    errorSummary?.clients.map((c) => [c.clientId, c]) ?? []
  )

  // Filter clients by search
  const filteredClients = clients?.filter((client) => {
    if (!search) return true
    const searchLower = search.toLowerCase()
    return (
      client.name.toLowerCase().includes(searchLower) ||
      client.companyName?.toLowerCase().includes(searchLower) ||
      client.contactEmail.toLowerCase().includes(searchLower)
    )
  }) || []

  // Calculate stats
  const stats = {
    total: clients?.length || 0,
    active: clients?.filter(c => c.isActive).length || 0,
    totalServers: clients?.reduce((acc, c) => acc + (c._count?.servers || 0), 0) || 0,
    totalErrors: clients?.reduce((acc, c) => acc + (c.statsOverview?.unacknowledgedErrors || 0), 0) || 0
  }

  // 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 enterprise clients...</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 enterprise clients</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">
        <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">
              <Building2 className="h-8 w-8 text-primary" />
            </div>
            <div>
              <h1 className="text-2xl md:text-3xl font-bold tracking-tight">Enterprise Clients</h1>
              <p className="text-muted-foreground mt-1">
                Manage enterprise infrastructure and server monitoring
              </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 Client
            </Button>
          </div>
        </div>
      </div>

      {/* Stats cards and Error Summary Widget */}
      <div className="grid gap-4 lg:grid-cols-3">
        {/* Stats cards - spans 2 columns on large screens */}
        <div className="lg:col-span-2 grid gap-4 sm:grid-cols-2">
          <StatsCard
            title="Total Clients"
            value={stats.total}
            icon={Building2}
            iconBg="bg-blue-100 dark:bg-blue-900/30"
            iconColor="text-blue-600 dark:text-blue-400"
            subtitle="Enterprise clients"
          />
          <StatsCard
            title="Active"
            value={stats.active}
            icon={CheckCircle2}
            iconBg="bg-emerald-100 dark:bg-emerald-900/30"
            iconColor="text-emerald-600 dark:text-emerald-400"
            subtitle="Currently active"
          />
          <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 clients"
          />
          <StatsCard
            title="Open Errors"
            value={stats.totalErrors}
            icon={AlertTriangle}
            iconBg={stats.totalErrors > 0 ? "bg-red-100 dark:bg-red-900/30" : "bg-slate-100 dark:bg-slate-900/30"}
            iconColor={stats.totalErrors > 0 ? "text-red-600 dark:text-red-400" : "text-slate-600 dark:text-slate-400"}
            subtitle="Unacknowledged"
          />
        </div>

        {/* System Health Widget */}
        <div className="lg:col-span-1">
          <EnterpriseErrorSummaryWidget />
        </div>
      </div>

      {/* Client list */}
      <Card>
        <CardHeader className="border-b bg-muted/30">
          <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
            <div>
              <CardTitle className="text-lg">All Clients</CardTitle>
              <CardDescription>
                {filteredClients.length} client{filteredClients.length !== 1 ? 's' : ''} found
              </CardDescription>
            </div>
            <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 clients..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="pl-10 w-full sm:w-72 bg-background"
              />
            </div>
          </div>
        </CardHeader>
        <CardContent className="p-4 md:p-6">
          {filteredClients.length === 0 ? (
            search ? (
              <div className="text-center py-12">
                <p className="text-muted-foreground">No clients match your search.</p>
              </div>
            ) : (
              <EmptyState onAddClient={() => setShowAddDialog(true)} />
            )
          ) : (
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
              {filteredClients.map((client) => (
                <ClientCard
                  key={client.id}
                  client={client}
                  errorSummary={errorSummaryMap.get(client.id)}
                />
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Add Client Dialog */}
      <AddClientDialog open={showAddDialog} onOpenChange={setShowAddDialog} />
    </div>
  )
}
