'use client'

import { useMemo } from 'react'
import { cn } from '@/lib/utils'
import { OrderCard, type Order, type OrderStatus } from './order-card'
import {
  CreditCard,
  Server,
  HardDrive,
  Globe,
  CheckCircle2,
  Zap,
  Package,
  Mail,
  AlertTriangle,
} from 'lucide-react'

// Column configuration
interface ColumnConfig {
  id: OrderStatus
  title: string
  icon: React.ElementType
  color: string
  bgColor: string
  borderColor: string
}

const columns: ColumnConfig[] = [
  {
    id: 'PAYMENT_CONFIRMED',
    title: 'Payment Confirmed',
    icon: CreditCard,
    color: 'text-blue-600',
    bgColor: 'bg-blue-50',
    borderColor: 'border-blue-200',
  },
  {
    id: 'AWAITING_SERVER',
    title: 'Awaiting Server',
    icon: Server,
    color: 'text-yellow-600',
    bgColor: 'bg-yellow-50',
    borderColor: 'border-yellow-200',
  },
  {
    id: 'SERVER_READY',
    title: 'Server Ready',
    icon: HardDrive,
    color: 'text-purple-600',
    bgColor: 'bg-purple-50',
    borderColor: 'border-purple-200',
  },
  {
    id: 'DNS_PENDING',
    title: 'DNS Pending',
    icon: Globe,
    color: 'text-orange-600',
    bgColor: 'bg-orange-50',
    borderColor: 'border-orange-200',
  },
  {
    id: 'DNS_READY',
    title: 'DNS Ready',
    icon: CheckCircle2,
    color: 'text-cyan-600',
    bgColor: 'bg-cyan-50',
    borderColor: 'border-cyan-200',
  },
  {
    id: 'PROVISIONING',
    title: 'Provisioning',
    icon: Zap,
    color: 'text-indigo-600',
    bgColor: 'bg-indigo-50',
    borderColor: 'border-indigo-200',
  },
  {
    id: 'FULFILLED',
    title: 'Fulfilled',
    icon: Package,
    color: 'text-green-600',
    bgColor: 'bg-green-50',
    borderColor: 'border-green-200',
  },
  {
    id: 'EMAIL_CONFIGURED',
    title: 'Complete',
    icon: Mail,
    color: 'text-emerald-600',
    bgColor: 'bg-emerald-50',
    borderColor: 'border-emerald-200',
  },
]

// Failed column is separate
const failedColumn: ColumnConfig = {
  id: 'FAILED',
  title: 'Failed',
  icon: AlertTriangle,
  color: 'text-red-600',
  bgColor: 'bg-red-50',
  borderColor: 'border-red-200',
}

interface KanbanColumnProps {
  column: ColumnConfig
  orders: Order[]
  onAction?: (order: Order, action: string) => void
  onViewDetails?: (order: Order) => void
}

function KanbanColumn({
  column,
  orders,
  onAction,
  onViewDetails,
}: KanbanColumnProps) {
  const Icon = column.icon

  return (
    <div className="flex flex-col w-72 shrink-0">
      {/* Column header */}
      <div
        className={cn(
          'flex items-center gap-2 px-3 py-2 rounded-t-lg border-b-2',
          column.bgColor,
          column.borderColor
        )}
      >
        <Icon className={cn('h-4 w-4', column.color)} />
        <h3 className={cn('font-medium text-sm', column.color)}>
          {column.title}
        </h3>
        <span
          className={cn(
            'ml-auto text-xs font-medium px-2 py-0.5 rounded-full',
            column.bgColor,
            column.color
          )}
        >
          {orders.length}
        </span>
      </div>

      {/* Column content */}
      <div
        className={cn(
          'flex-1 p-2 space-y-3 min-h-[200px] rounded-b-lg border border-t-0',
          'bg-gray-50/50',
          column.borderColor
        )}
      >
        {orders.length === 0 ? (
          <div className="flex items-center justify-center h-24 text-sm text-muted-foreground">
            No orders
          </div>
        ) : (
          orders.map((order) => (
            <OrderCard
              key={order.id}
              order={order}
              onAction={onAction}
              onViewDetails={onViewDetails}
            />
          ))
        )}
      </div>
    </div>
  )
}

interface OrderKanbanProps {
  orders: Order[]
  onAction?: (order: Order, action: string) => void
  onViewDetails?: (order: Order) => void
  showFailedColumn?: boolean
}

export function OrderKanban({
  orders,
  onAction,
  onViewDetails,
  showFailedColumn = true,
}: OrderKanbanProps) {
  // Group orders by status
  const ordersByStatus = useMemo(() => {
    const grouped: Record<OrderStatus, Order[]> = {
      PAYMENT_CONFIRMED: [],
      AWAITING_SERVER: [],
      SERVER_READY: [],
      DNS_PENDING: [],
      DNS_READY: [],
      PROVISIONING: [],
      FULFILLED: [],
      EMAIL_CONFIGURED: [],
      FAILED: [],
    }

    orders.forEach((order) => {
      if (grouped[order.status]) {
        grouped[order.status].push(order)
      }
    })

    // Sort orders within each column by creation date (newest first)
    Object.keys(grouped).forEach((status) => {
      grouped[status as OrderStatus].sort(
        (a, b) => b.createdAt.getTime() - a.createdAt.getTime()
      )
    })

    return grouped
  }, [orders])

  // Count of failed orders
  const failedCount = ordersByStatus.FAILED.length

  return (
    <div className="flex flex-col h-full">
      {/* Main Kanban board */}
      <div className="flex-1 overflow-x-auto pb-4">
        <div className="flex gap-4 min-w-max p-1">
          {/* Main pipeline columns */}
          {columns.map((column) => (
            <KanbanColumn
              key={column.id}
              column={column}
              orders={ordersByStatus[column.id]}
              onAction={onAction}
              onViewDetails={onViewDetails}
            />
          ))}

          {/* Failed column (separate) */}
          {showFailedColumn && (
            <div className="flex flex-col">
              {/* Separator */}
              <div className="flex items-center gap-2 mb-2">
                <div className="flex-1 border-t border-dashed border-gray-300" />
              </div>

              <KanbanColumn
                column={failedColumn}
                orders={ordersByStatus.FAILED}
                onAction={onAction}
                onViewDetails={onViewDetails}
              />
            </div>
          )}
        </div>
      </div>

      {/* Summary bar */}
      <div className="flex items-center gap-4 pt-4 border-t bg-white">
        <div className="flex items-center gap-6 text-sm">
          <div className="flex items-center gap-2">
            <span className="font-medium">Total:</span>
            <span className="text-muted-foreground">{orders.length} orders</span>
          </div>
          <div className="flex items-center gap-2">
            <span className="font-medium">In Progress:</span>
            <span className="text-muted-foreground">
              {orders.filter(
                (o) =>
                  o.status !== 'EMAIL_CONFIGURED' && o.status !== 'FAILED'
              ).length}
            </span>
          </div>
          <div className="flex items-center gap-2">
            <span className="font-medium">Completed:</span>
            <span className="text-green-600">
              {ordersByStatus.EMAIL_CONFIGURED.length}
            </span>
          </div>
          {failedCount > 0 && (
            <div className="flex items-center gap-2">
              <span className="font-medium">Failed:</span>
              <span className="text-red-600">{failedCount}</span>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

// Compact horizontal pipeline view (for smaller screens)
export function OrderPipelineCompact({
  orders,
  onViewDetails,
}: {
  orders: Order[]
  onViewDetails?: (order: Order) => void
}) {
  const ordersByStatus = useMemo(() => {
    const grouped: Record<OrderStatus, Order[]> = {
      PAYMENT_CONFIRMED: [],
      AWAITING_SERVER: [],
      SERVER_READY: [],
      DNS_PENDING: [],
      DNS_READY: [],
      PROVISIONING: [],
      FULFILLED: [],
      EMAIL_CONFIGURED: [],
      FAILED: [],
    }

    orders.forEach((order) => {
      if (grouped[order.status]) {
        grouped[order.status].push(order)
      }
    })

    return grouped
  }, [orders])

  return (
    <div className="space-y-4">
      {/* Pipeline summary */}
      <div className="flex items-center gap-1 overflow-x-auto pb-2">
        {columns.map((column, idx) => {
          const Icon = column.icon
          const count = ordersByStatus[column.id].length

          return (
            <div key={column.id} className="flex items-center">
              <div
                className={cn(
                  'flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium',
                  column.bgColor,
                  column.color
                )}
              >
                <Icon className="h-3.5 w-3.5" />
                <span className="hidden sm:inline">{column.title}</span>
                <span className="font-bold">{count}</span>
              </div>
              {idx < columns.length - 1 && (
                <div className="w-4 h-px bg-gray-300 mx-1" />
              )}
            </div>
          )
        })}
      </div>

      {/* Orders list grouped by status */}
      <div className="space-y-6">
        {columns.map((column) => {
          const columnOrders = ordersByStatus[column.id]
          if (columnOrders.length === 0) return null

          const Icon = column.icon

          return (
            <div key={column.id}>
              <div className="flex items-center gap-2 mb-2">
                <Icon className={cn('h-4 w-4', column.color)} />
                <h3 className="font-medium text-sm">{column.title}</h3>
                <span className="text-xs text-muted-foreground">
                  ({columnOrders.length})
                </span>
              </div>
              <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
                {columnOrders.map((order) => (
                  <OrderCard
                    key={order.id}
                    order={order}
                    onViewDetails={onViewDetails}
                  />
                ))}
              </div>
            </div>
          )
        })}

        {/* Failed orders */}
        {ordersByStatus.FAILED.length > 0 && (
          <div>
            <div className="flex items-center gap-2 mb-2">
              <AlertTriangle className="h-4 w-4 text-red-600" />
              <h3 className="font-medium text-sm text-red-600">Failed</h3>
              <span className="text-xs text-muted-foreground">
                ({ordersByStatus.FAILED.length})
              </span>
            </div>
            <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
              {ordersByStatus.FAILED.map((order) => (
                <OrderCard
                  key={order.id}
                  order={order}
                  onViewDetails={onViewDetails}
                />
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
