'use client'

import { useMemo, useEffect, useState, useRef } from 'react'
import { CheckCircle, Circle, Loader2 } from 'lucide-react'
import { OrderStatus } from '@/types/api'
import { cn } from '@/lib/utils'

interface OrderTimelineProps {
  status: OrderStatus
  timestamps: {
    createdAt?: Date | null
    serverReadyAt?: Date | null
    dnsVerifiedAt?: Date | null
    provisioningStartedAt?: Date | null
    completedAt?: Date | null
  }
  className?: string
}

interface TimelineStage {
  key: string
  label: string
  shortLabel: string
  status: OrderStatus
}

const STAGES: TimelineStage[] = [
  { key: 'payment_confirmed', label: 'Payment Confirmed', shortLabel: 'Payment', status: OrderStatus.PAYMENT_CONFIRMED },
  { key: 'awaiting_server', label: 'Server Ordered', shortLabel: 'Server', status: OrderStatus.AWAITING_SERVER },
  { key: 'dns_pending', label: 'DNS Pending', shortLabel: 'DNS', status: OrderStatus.DNS_PENDING },
  { key: 'dns_ready', label: 'DNS Ready', shortLabel: 'DNS Ready', status: OrderStatus.DNS_READY },
  { key: 'provisioning', label: 'Provisioning', shortLabel: 'Provision', status: OrderStatus.PROVISIONING },
  { key: 'fulfilled', label: 'Fulfilled', shortLabel: 'Complete', status: OrderStatus.FULFILLED },
]

const STATUS_ORDER = STAGES.map((s) => s.status)

export function OrderTimeline({ status, timestamps, className }: OrderTimelineProps) {
  const [mounted, setMounted] = useState(false)

  // Trigger mount animation
  useEffect(() => {
    const timer = setTimeout(() => setMounted(true), 50)
    return () => clearTimeout(timer)
  }, [])

  // Get current index, handling special statuses
  const getCurrentIndex = () => {
    // Handle SERVER_READY - treat as between AWAITING_SERVER and DNS_PENDING
    if (status === OrderStatus.SERVER_READY) {
      return STATUS_ORDER.indexOf(OrderStatus.AWAITING_SERVER)
    }
    // Handle EMAIL_CONFIGURED - treat as completed/fulfilled
    if (status === OrderStatus.EMAIL_CONFIGURED) {
      return STATUS_ORDER.indexOf(OrderStatus.FULFILLED)
    }
    // Handle FAILED - show progress up to where it failed
    if (status === OrderStatus.FAILED) {
      return STATUS_ORDER.indexOf(OrderStatus.PROVISIONING)
    }
    return STATUS_ORDER.indexOf(status)
  }

  const currentIndex = getCurrentIndex()

  return (
    <div className={cn('w-full', className)}>
      {/* Horizontal timeline */}
      <div className="relative">
        {/* Progress bar background - inset by half circle width (20px = w-5) on each side */}
        <div className="absolute top-5 left-5 right-5 h-1 bg-gray-200 rounded-full" />

        {/* Progress bar filled portion - starts at same inset, width is percentage of line length */}
        <div
          className={cn(
            'absolute top-5 left-5 h-1 rounded-full transition-all duration-500 ease-out',
            status === OrderStatus.FAILED ? 'bg-red-500' : 'bg-green-500'
          )}
          style={{
            width: `calc(${Math.max(0, (currentIndex / (STAGES.length - 1)) * 100)}% - ${(currentIndex / (STAGES.length - 1)) * 40}px)`,
          }}
        />

        {/* Stage nodes */}
        <div className="relative flex justify-between">
          {STAGES.map((stage, index) => {
            const isComplete = index < currentIndex ||
              (index === currentIndex && status !== OrderStatus.FAILED && status !== OrderStatus.PROVISIONING)
            const isCurrent = index === currentIndex
            const isPending = index > currentIndex
            const isProvisioning = isCurrent && status === OrderStatus.PROVISIONING
            const isFailed = status === OrderStatus.FAILED && isCurrent

            return (
              <div
                key={stage.key}
                className={cn(
                  'flex flex-col items-center',
                  mounted ? 'opacity-100' : 'opacity-0',
                  'transition-opacity duration-300'
                )}
                style={{
                  transitionDelay: `${index * 50}ms`,
                }}
              >
                {/* Circle node */}
                <div
                  className={cn(
                    'relative z-10 flex h-10 w-10 items-center justify-center rounded-full border-2 transition-all duration-300',
                    isComplete && 'border-green-500 bg-green-500 text-white',
                    isCurrent && !isComplete && !isFailed && 'border-blue-500 bg-blue-50',
                    isCurrent && isProvisioning && 'border-blue-500 bg-blue-100',
                    isFailed && 'border-red-500 bg-red-50',
                    isPending && 'border-gray-200 bg-white'
                  )}
                >
                  {isComplete ? (
                    <CheckCircle className="h-5 w-5" />
                  ) : isProvisioning ? (
                    <Loader2 className="h-5 w-5 animate-spin text-blue-500" />
                  ) : isFailed ? (
                    <span className="text-lg font-bold text-red-500">!</span>
                  ) : isCurrent ? (
                    <Circle className="h-4 w-4 fill-blue-500 text-blue-500" />
                  ) : (
                    <span className="text-sm font-medium text-gray-400">{index + 1}</span>
                  )}
                </div>

                {/* Label */}
                <p
                  className={cn(
                    'mt-2 text-xs font-medium text-center max-w-[80px] transition-colors duration-300',
                    isComplete && 'text-green-700',
                    isCurrent && !isComplete && !isFailed && 'text-blue-600',
                    isFailed && 'text-red-600',
                    isPending && 'text-gray-400'
                  )}
                >
                  {stage.shortLabel}
                </p>
              </div>
            )
          })}
        </div>
      </div>
    </div>
  )
}

export default OrderTimeline
