'use client'

import { useState, useMemo } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import {
  OrderKanban,
  OrderPipelineCompact,
} from '@/components/admin/order-kanban'
import { CreateOrderDialog } from '@/components/admin/create-order-dialog'
import type { Order as OrderCardType, OrderStatus, OrderTier } from '@/components/admin/order-card'
import { useOrders } from '@/hooks/use-orders'
import { OrderStatus as ApiOrderStatus, SubscriptionTier } from '@/types/api'
import {
  Search,
  Filter,
  RefreshCw,
  LayoutGrid,
  List,
  Download,
  Plus,
  Loader2,
  AlertCircle,
  Package,
  X,
  Sparkles,
} from 'lucide-react'
import { exportOrdersToCsv } from '@/lib/csv-export'

// View modes
type ViewMode = 'kanban' | 'list'

// Filter options
interface FilterOptions {
  search: string
  tier: OrderTier | 'all'
  status: OrderStatus | 'all'
}

// Map API tier to component tier
function mapTier(tier: SubscriptionTier): OrderTier {
  return tier === 'HUB_DASHBOARD' ? 'hub-dashboard' : 'control-panel'
}

// Map API tier back for filtering
function mapTierToApi(tier: OrderTier | 'all'): SubscriptionTier | undefined {
  if (tier === 'all') return undefined
  return tier === 'hub-dashboard' ? SubscriptionTier.HUB_DASHBOARD : SubscriptionTier.ADVANCED
}

// Map API order to component order format
function mapApiOrderToCardOrder(apiOrder: {
  id: string
  domain: string
  tier: SubscriptionTier
  status: ApiOrderStatus
  serverIp: string | null
  failureReason: string | null
  createdAt: Date | string
  updatedAt: Date | string
  user: {
    id: string
    name: string | null
    email: string
    company: string | null
  }
}): OrderCardType {
  return {
    id: apiOrder.id,
    domain: apiOrder.domain,
    customerName: apiOrder.user.name || apiOrder.user.company || apiOrder.user.email,
    customerEmail: apiOrder.user.email,
    tier: mapTier(apiOrder.tier),
    status: apiOrder.status as OrderStatus,
    createdAt: new Date(apiOrder.createdAt),
    updatedAt: new Date(apiOrder.updatedAt),
    serverIp: apiOrder.serverIp || undefined,
    failureReason: apiOrder.failureReason || undefined,
  }
}

// Tier display config
const tierConfig: Record<OrderTier | 'all', { label: string; color: string }> = {
  'all': { label: 'All Tiers', color: '' },
  'hub-dashboard': { label: 'Hub Dashboard', color: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400' },
  'control-panel': { label: 'Control Panel', color: 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400' },
}

// Status display config
const statusConfig: Record<OrderStatus | 'all', { label: string; color: string }> = {
  'all': { label: 'All Statuses', color: '' },
  'PAYMENT_CONFIRMED': { label: 'Payment Confirmed', color: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400' },
  'AWAITING_SERVER': { label: 'Awaiting Server', color: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400' },
  'SERVER_READY': { label: 'Server Ready', color: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400' },
  'DNS_PENDING': { label: 'DNS Pending', color: 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400' },
  'DNS_READY': { label: 'DNS Ready', color: 'bg-teal-100 text-teal-700 dark:bg-teal-900/30 dark:text-teal-400' },
  'PROVISIONING': { label: 'Provisioning', color: 'bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400' },
  'FULFILLED': { label: 'Fulfilled', color: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400' },
  'EMAIL_CONFIGURED': { label: 'Complete', color: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400' },
  'FAILED': { label: 'Failed', color: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400' },
}

export default function OrdersPage() {
  const router = useRouter()
  const [viewMode, setViewMode] = useState<ViewMode>('kanban')
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
  const [filters, setFilters] = useState<FilterOptions>({
    search: '',
    tier: 'all',
    status: 'all',
  })

  // Fetch orders from API
  const {
    data,
    isLoading,
    isError,
    error,
    refetch,
    isFetching,
  } = useOrders({
    search: filters.search || undefined,
    tier: mapTierToApi(filters.tier),
    status: filters.status !== 'all' ? filters.status as ApiOrderStatus : undefined,
    limit: 100,
  })

  // Map API orders to component format
  const orders = useMemo(() => {
    if (!data?.orders) return []
    return data.orders.map(mapApiOrderToCardOrder)
  }, [data?.orders])

  // Check if any filters are active
  const hasActiveFilters = filters.search || filters.tier !== 'all' || filters.status !== 'all'

  // Handle order action
  const handleOrderAction = (order: OrderCardType, action: string) => {
    console.log(`Action "${action}" triggered for order:`, order)
    // Navigate to order detail page for actions
    router.push(`/admin/orders/${order.id}`)
  }

  // Handle view order details
  const handleViewDetails = (order: OrderCardType) => {
    router.push(`/admin/orders/${order.id}`)
  }

  // Handle refresh
  const handleRefresh = async () => {
    await refetch()
  }

  // Handle export
  const handleExport = () => {
    if (!data?.orders || data.orders.length === 0) {
      alert('No orders to export')
      return
    }
    exportOrdersToCsv(data.orders)
  }

  // Clear all filters
  const clearFilters = () => {
    setFilters({ search: '', tier: 'all', status: 'all' })
  }

  // Loading state
  if (isLoading) {
    return (
      <div className="flex flex-col h-full">
        {/* Hero header skeleton */}
        <div className="relative overflow-hidden rounded-2xl border bg-gradient-to-br from-card via-card to-muted/30 p-6 md:p-8 mb-6">
          <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">
            <div className="h-8 w-48 bg-muted/60 rounded animate-pulse mb-2" />
            <div className="h-4 w-64 bg-muted/40 rounded animate-pulse" />
          </div>
        </div>

        {/* Loading content */}
        <div className="flex-1 flex items-center justify-center">
          <div className="flex flex-col items-center 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>
            <div className="text-center">
              <p className="font-medium text-foreground">Loading orders...</p>
              <p className="text-sm text-muted-foreground">Fetching your order pipeline</p>
            </div>
          </div>
        </div>
      </div>
    )
  }

  // Error state
  if (isError) {
    return (
      <div className="flex flex-col h-full">
        {/* 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 mb-6">
          <div className="absolute top-0 right-0 -mt-16 -mr-16 h-64 w-64 rounded-full bg-gradient-to-br from-destructive/5 to-destructive/10 blur-3xl" />
          <div className="relative">
            <h1 className="text-2xl md:text-3xl font-bold tracking-tight">Order Pipeline</h1>
            <p className="text-muted-foreground mt-1">Manage and track customer provisioning orders</p>
          </div>
        </div>

        {/* Error content */}
        <div className="flex-1 flex items-center justify-center">
          <div className="rounded-xl border-2 border-dashed border-destructive/30 bg-destructive/5 p-8 max-w-md text-center">
            <div className="mx-auto w-fit p-4 rounded-full bg-destructive/10 mb-4">
              <AlertCircle className="h-8 w-8 text-destructive" />
            </div>
            <h3 className="font-semibold text-lg text-destructive">Failed to load orders</h3>
            <p className="text-sm text-muted-foreground mt-2 mb-6">
              {error instanceof Error ? error.message : 'An unexpected error occurred while fetching orders.'}
            </p>
            <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>
        </div>
      </div>
    )
  }

  return (
    <div className="flex flex-col h-full space-y-6">
      {/* 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 gap-4 sm:flex-row sm:items-center sm:justify-between">
          {/* Title section */}
          <div className="flex items-center gap-4">
            <div className="p-3 rounded-2xl bg-gradient-to-br from-primary/10 to-primary/5 border border-primary/20">
              <Package className="h-7 w-7 text-primary" />
            </div>
            <div>
              <h1 className="text-2xl md:text-3xl font-bold tracking-tight">Order Pipeline</h1>
              <p className="text-muted-foreground mt-0.5">Manage and track customer provisioning orders</p>
            </div>
          </div>

          {/* Action buttons */}
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={handleExport}
              className="gap-2 bg-background/50 hover:bg-background"
            >
              <Download className="h-4 w-4" />
              <span className="hidden sm:inline">Export</span>
            </Button>
            <Button
              size="sm"
              onClick={() => setIsCreateDialogOpen(true)}
              className="gap-2 shadow-lg shadow-primary/20"
            >
              <Plus className="h-4 w-4" />
              <span className="hidden sm:inline">New Order</span>
            </Button>
          </div>
        </div>
      </div>

      {/* Toolbar */}
      <div className="rounded-xl border bg-card/50 p-4">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
          {/* Search and filters */}
          <div className="flex flex-1 flex-col gap-3 sm:flex-row sm:items-center">
            {/* Search input */}
            <div className="relative flex-1 max-w-sm">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input
                placeholder="Search by domain, customer..."
                value={filters.search}
                onChange={(e) =>
                  setFilters((prev) => ({ ...prev, search: e.target.value }))
                }
                className="pl-9 bg-background border-muted-foreground/20 focus:border-primary"
              />
            </div>

            {/* Filter dropdowns */}
            <div className="flex items-center gap-2">
              {/* Tier filter */}
              <div className="relative">
                <select
                  value={filters.tier}
                  onChange={(e) =>
                    setFilters((prev) => ({
                      ...prev,
                      tier: e.target.value as OrderTier | 'all',
                    }))
                  }
                  className="h-10 appearance-none rounded-lg border border-muted-foreground/20 bg-background pl-3 pr-8 text-sm font-medium ring-offset-background focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 cursor-pointer hover:border-muted-foreground/40 transition-colors"
                >
                  <option value="all">All Tiers</option>
                  <option value="hub-dashboard">Hub Dashboard</option>
                  <option value="control-panel">Control Panel</option>
                </select>
                <Filter className="absolute right-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground pointer-events-none" />
              </div>

              {/* Status filter */}
              <div className="relative">
                <select
                  value={filters.status}
                  onChange={(e) =>
                    setFilters((prev) => ({
                      ...prev,
                      status: e.target.value as OrderStatus | 'all',
                    }))
                  }
                  className="h-10 appearance-none rounded-lg border border-muted-foreground/20 bg-background pl-3 pr-8 text-sm font-medium ring-offset-background focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 cursor-pointer hover:border-muted-foreground/40 transition-colors"
                >
                  <option value="all">All Statuses</option>
                  <option value="PAYMENT_CONFIRMED">Payment Confirmed</option>
                  <option value="AWAITING_SERVER">Awaiting Server</option>
                  <option value="SERVER_READY">Server Ready</option>
                  <option value="DNS_PENDING">DNS Pending</option>
                  <option value="DNS_READY">DNS Ready</option>
                  <option value="PROVISIONING">Provisioning</option>
                  <option value="FULFILLED">Fulfilled</option>
                  <option value="EMAIL_CONFIGURED">Complete</option>
                  <option value="FAILED">Failed</option>
                </select>
                <Filter className="absolute right-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground pointer-events-none" />
              </div>
            </div>
          </div>

          {/* View controls */}
          <div className="flex items-center gap-3">
            {/* Refresh button */}
            <Button
              variant="ghost"
              size="sm"
              onClick={handleRefresh}
              disabled={isFetching}
              className="gap-2 text-muted-foreground hover:text-foreground"
            >
              <RefreshCw
                className={`h-4 w-4 ${isFetching ? 'animate-spin' : ''}`}
              />
              <span className="hidden sm:inline">Refresh</span>
            </Button>

            {/* View toggle */}
            <div className="flex items-center p-1 bg-muted/50 rounded-lg">
              <button
                onClick={() => setViewMode('kanban')}
                className={`flex items-center gap-2 px-3 py-1.5 rounded-md text-sm font-medium transition-all ${
                  viewMode === 'kanban'
                    ? 'bg-background text-foreground shadow-sm'
                    : 'text-muted-foreground hover:text-foreground'
                }`}
              >
                <LayoutGrid className="h-4 w-4" />
                <span className="hidden sm:inline">Kanban</span>
              </button>
              <button
                onClick={() => setViewMode('list')}
                className={`flex items-center gap-2 px-3 py-1.5 rounded-md text-sm font-medium transition-all ${
                  viewMode === 'list'
                    ? 'bg-background text-foreground shadow-sm'
                    : 'text-muted-foreground hover:text-foreground'
                }`}
              >
                <List className="h-4 w-4" />
                <span className="hidden sm:inline">List</span>
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Active filters indicator */}
      {hasActiveFilters && (
        <div className="flex flex-wrap items-center gap-2">
          <div className="flex items-center gap-1.5 text-sm text-muted-foreground">
            <Sparkles className="h-4 w-4" />
            <span>
              Showing <span className="font-semibold text-foreground">{orders.length}</span> orders
              {data?.pagination && (
                <span> of <span className="font-semibold text-foreground">{data.pagination.total}</span></span>
              )}
            </span>
          </div>

          {/* Filter badges */}
          {filters.search && (
            <Badge variant="secondary" className="gap-1.5 pl-2 pr-1 py-1">
              <span>Search: {filters.search}</span>
              <button
                onClick={() => setFilters(prev => ({ ...prev, search: '' }))}
                className="ml-1 rounded-full p-0.5 hover:bg-muted-foreground/20"
              >
                <X className="h-3 w-3" />
              </button>
            </Badge>
          )}
          {filters.tier !== 'all' && (
            <Badge
              variant="secondary"
              className={`gap-1.5 pl-2 pr-1 py-1 ${tierConfig[filters.tier].color}`}
            >
              <span>{tierConfig[filters.tier].label}</span>
              <button
                onClick={() => setFilters(prev => ({ ...prev, tier: 'all' }))}
                className="ml-1 rounded-full p-0.5 hover:bg-black/10 dark:hover:bg-white/10"
              >
                <X className="h-3 w-3" />
              </button>
            </Badge>
          )}
          {filters.status !== 'all' && (
            <Badge
              variant="secondary"
              className={`gap-1.5 pl-2 pr-1 py-1 ${statusConfig[filters.status].color}`}
            >
              <span>{statusConfig[filters.status].label}</span>
              <button
                onClick={() => setFilters(prev => ({ ...prev, status: 'all' }))}
                className="ml-1 rounded-full p-0.5 hover:bg-black/10 dark:hover:bg-white/10"
              >
                <X className="h-3 w-3" />
              </button>
            </Badge>
          )}

          {/* Clear all button */}
          <Button
            variant="ghost"
            size="sm"
            onClick={clearFilters}
            className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground"
          >
            Clear all
          </Button>
        </div>
      )}

      {/* Empty state */}
      {orders.length === 0 && (
        <div className="flex-1 flex items-center justify-center">
          <div className="rounded-xl border-2 border-dashed border-muted-foreground/20 bg-muted/20 p-12 max-w-md text-center">
            <div className="mx-auto w-fit p-4 rounded-full bg-muted/60 mb-4">
              <Package className="h-10 w-10 text-muted-foreground/60" />
            </div>
            <h3 className="font-semibold text-lg">No orders found</h3>
            <p className="text-sm text-muted-foreground mt-2">
              {hasActiveFilters
                ? "No orders match your current filters. Try adjusting your search criteria."
                : "Get started by creating your first order."
              }
            </p>
            {hasActiveFilters ? (
              <Button
                variant="outline"
                onClick={clearFilters}
                className="mt-6 gap-2"
              >
                <X className="h-4 w-4" />
                Clear filters
              </Button>
            ) : (
              <Button
                onClick={() => setIsCreateDialogOpen(true)}
                className="mt-6 gap-2"
              >
                <Plus className="h-4 w-4" />
                Create your first order
              </Button>
            )}
          </div>
        </div>
      )}

      {/* Main content */}
      {orders.length > 0 && (
        <div className="flex-1 min-h-0">
          {viewMode === 'kanban' ? (
            <OrderKanban
              orders={orders}
              onAction={handleOrderAction}
              onViewDetails={handleViewDetails}
            />
          ) : (
            <OrderPipelineCompact
              orders={orders}
              onViewDetails={handleViewDetails}
            />
          )}
        </div>
      )}

      {/* Create Order Dialog */}
      <CreateOrderDialog
        open={isCreateDialogOpen}
        onOpenChange={setIsCreateDialogOpen}
        onSuccess={() => refetch()}
      />
    </div>
  )
}
