"use client"

import { cn } from '@/lib/utils'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { 
  CheckCircle, 
  Clock, 
  Loader2, 
  AlertCircle, 
  Search,
  FileCheck,
  ArrowRight
} from 'lucide-react'

interface StatusStep {
  id: string
  label: string
  description: string
  icon: React.ReactNode
  color: string
  completed: boolean
  active: boolean
  timestamp?: string
  notes?: string
}

interface StatusWorkflowProps {
  currentStatus: string
  statusLog: Array<{
    status: string
    timestamp: string
    message?: string
    adminName?: string
  }>
  className?: string
}

const statusFlowConfig = {
  PENDING: {
    order: 1,
    label: 'Menunggu Verifikasi',
    description: 'Pengajuan telah diterima dan menunggu verifikasi awal',
    icon: <Clock className="w-5 h-5" />,
    color: 'bg-yellow-100 text-yellow-800 border-yellow-200'
  },
  IN_PROGRESS: {
    order: 2,
    label: 'Sedang Diproses',
    description: 'Pengajuan sedang dalam proses penanganan',
    icon: <Loader2 className="w-5 h-5 animate-spin" />,
    color: 'bg-amber-100 text-amber-800 border-amber-200'
  },
  REVIEWING: {
    order: 3,
    label: 'Sedang Ditinjau',
    description: 'Dokumen sedang ditinjau oleh petugas berwenang',
    icon: <Search className="w-5 h-5" />,
    color: 'bg-purple-100 text-purple-800 border-purple-200'
  },
  NEED_REVISION: {
    order: 2.5,
    label: 'Perlu Revisi',
    description: 'Pengajuan memerlukan perbaikan atau tambahan dokumen',
    icon: <AlertCircle className="w-5 h-5" />,
    color: 'bg-orange-100 text-orange-800 border-orange-200'
  },
  COMPLETED: {
    order: 4,
    label: 'Selesai',
    description: 'Pengajuan telah selesai diproses',
    icon: <CheckCircle className="w-5 h-5" />,
    color: 'bg-green-100 text-green-800 border-green-200'
  }
}

export function StatusWorkflow({ currentStatus, statusLog, className }: StatusWorkflowProps) {
  const getStatusStep = (status: string): StatusStep => {
    const config = statusFlowConfig[status as keyof typeof statusFlowConfig]
    const logEntry = statusLog.find(log => log.status === status)
    
    return {
      id: status,
      label: config.label,
      description: config.description,
      icon: config.icon,
      color: config.color,
      completed: statusFlowConfig[currentStatus as keyof typeof statusFlowConfig]?.order >= config.order,
      active: status === currentStatus,
      timestamp: logEntry?.timestamp,
      notes: logEntry?.message
    }
  }

  const orderedSteps = [
    'PENDING',
    'IN_PROGRESS', 
    'REVIEWING',
    'COMPLETED'
  ].map(status => getStatusStep(status))

  // Add NEED_REVISION if it exists in the log
  const hasRevision = statusLog.some(log => log.status === 'NEED_REVISION')
  if (hasRevision) {
    const revisionStep = getStatusStep('NEED_REVISION')
    const insertIndex = orderedSteps.findIndex(step => step.id === 'REVIEWING')
    if (insertIndex > -1) {
      orderedSteps.splice(insertIndex, 0, revisionStep)
    }
  }

  return (
    <Card className={cn("w-full", className)}>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <FileCheck className="w-5 h-5" />
          Alur Proses Pengajuan
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="space-y-4">
          {/* Progress Steps */}
          <div className="relative">
            {/* Progress Line */}
            <div className="absolute left-6 top-8 bottom-8 w-0.5 bg-gray-200">
              <div 
                className="w-full bg-amber-600 transition-all duration-500"
                style={{
                  height: `${(orderedSteps.filter(step => step.completed).length / orderedSteps.length) * 100}%`
                }}
              />
            </div>

            {/* Steps */}
            <div className="space-y-6">
              {orderedSteps.map((step, index) => (
                <div key={step.id} className="relative flex items-start gap-4">
                  {/* Step Circle */}
                  <div className={cn(
                    "relative z-10 flex h-12 w-12 items-center justify-center rounded-full border-2 transition-all duration-300",
                    step.completed 
                      ? "bg-amber-600 border-amber-600 text-white" 
                      : step.active
                      ? "bg-white border-amber-600 text-amber-600 ring-4 ring-amber-100"
                      : "bg-white border-gray-300 text-gray-400"
                  )}>
                    {step.completed ? (
                      <CheckCircle className="w-6 h-6" />
                    ) : (
                      step.icon
                    )}
                  </div>

                  {/* Step Content */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1">
                      <h3 className={cn(
                        "font-semibold text-sm",
                        step.completed || step.active ? "text-gray-900" : "text-gray-500"
                      )}>
                        {step.label}
                      </h3>
                      {step.active && (
                        <Badge variant="secondary" className="text-xs">
                          Saat Ini
                        </Badge>
                      )}
                    </div>
                    
                    <p className={cn(
                      "text-xs mb-2",
                      step.completed || step.active ? "text-gray-600" : "text-gray-400"
                    )}>
                      {step.description}
                    </p>

                    {/* Step Details */}
                    {step.timestamp && (
                      <div className="bg-gray-50 rounded-lg p-3 space-y-1">
                        <div className="flex items-center gap-2 text-xs text-gray-600">
                          <Clock className="w-3 h-3" />
                          <span>{new Date(step.timestamp).toLocaleString('id-ID', {
                            day: 'numeric',
                            month: 'short',
                            year: 'numeric',
                            hour: '2-digit',
                            minute: '2-digit'
                          })}</span>
                        </div>
                        {step.notes && (
                          <div className="text-xs text-gray-700 bg-white rounded p-2 border-l-2 border-amber-200">
                            <span className="font-medium">Catatan:</span> {step.notes}
                          </div>
                        )}
                      </div>
                    )}
                  </div>

                  {/* Arrow for next step */}
                  {index < orderedSteps.length - 1 && (
                    <div className="absolute left-6 top-12 transform -translate-x-1/2">
                      <ArrowRight className={cn(
                        "w-4 h-4 transition-colors duration-300",
                        step.completed ? "text-amber-600" : "text-gray-300"
                      )} />
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>

          {/* Current Status Summary */}
          <div className="bg-amber-50 border border-amber-200 rounded-lg p-4">
            <div className="flex items-center gap-3">
              {getStatusStep(currentStatus).icon}
              <div>
                <h4 className="font-semibold text-amber-900">
                  Status Saat Ini: {getStatusStep(currentStatus).label}
                </h4>
                <p className="text-sm text-amber-700">
                  {getStatusStep(currentStatus).description}
                </p>
              </div>
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  )
}