/**
 * Order Status Widget
 * 
 * Shows order tracking and status information.
 */

import { motion } from 'framer-motion'
import { Package, Truck, CheckCircle, Clock, AlertCircle, ExternalLink, MapPin } from 'lucide-react'
import { t } from '@/lib/i18n'

interface OrderItem {
  name: string
  quantity: number
  total: string
  image?: string
}

interface TrackingInfo {
  provider: string
  tracking_number: string
  tracking_link?: string
  date_shipped?: string
}

interface OrderStatusWidgetProps {
  config: {
    order: {
      id: number
      order_number: string
      status: string
      status_name: string
      status_color: string
      date: string
      total: string
      items: OrderItem[]
      items_count: number
      shipping?: {
        method: string
        address: string
      }
      tracking?: TrackingInfo
      order_url: string
    }
    is_rtl?: boolean
  }
  language?: string
  onTrack?: () => void
  onViewOrder?: () => void
}

const statusIcons: Record<string, React.ComponentType<{ className?: string }>> = {
  pending: Clock,
  processing: Package,
  'on-hold': AlertCircle,
  completed: CheckCircle,
  shipped: Truck,
}

export function OrderStatusWidget({ config, language, onTrack, onViewOrder }: OrderStatusWidgetProps) {
  const resolvedIsRtl = typeof config.is_rtl === 'boolean' ? config.is_rtl : language !== 'en'
  const { order } = config
  const StatusIcon = statusIcons[order.status] || Package

  // Progress steps
  const steps = [
    { key: 'received', label: t('Received'), done: true },
    { key: 'processing', label: t('Processing'), done: ['processing', 'completed', 'shipped'].includes(order.status) },
    { key: 'shipped', label: t('Shipped'), done: ['completed', 'shipped'].includes(order.status) },
    { key: 'delivered', label: t('Delivered'), done: order.status === 'completed' },
  ]

  return (
    <motion.div
      className="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden"
      initial={{ opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      dir={resolvedIsRtl ? 'rtl' : 'ltr'}
    >
      {/* Header */}
      <div 
        className="p-4"
        style={{ backgroundColor: `${order.status_color}15` }}
      >
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div 
              className="w-10 h-10 rounded-full flex items-center justify-center"
              style={{ backgroundColor: `${order.status_color}25` }}
            >
              <StatusIcon className="w-5 h-5" />
            </div>
            <div>
              <p className="font-semibold text-gray-800">
                {t('Order')} #{order.order_number}
              </p>
              <p className="text-sm" style={{ color: order.status_color }}>
                {order.status_name}
              </p>
            </div>
          </div>
          <p className="text-sm text-gray-500">{order.date}</p>
        </div>
      </div>

      {/* Progress Bar */}
      <div className="px-4 py-3 border-b border-gray-100">
        <div className="flex items-center justify-between">
          {steps.map((step, index) => (
            <div key={step.key} className="flex flex-col items-center relative flex-1">
              {/* Line before */}
              {index > 0 && (
                <div 
                  className={`absolute top-3 ${resolvedIsRtl ? 'right-1/2' : 'left-0'} w-full h-0.5 -z-10`}
                  style={{ 
                    backgroundColor: step.done ? order.status_color : '#e5e7eb',
                    [resolvedIsRtl ? 'right' : 'left']: '50%',
                    width: '100%'
                  }}
                />
              )}
              
              {/* Dot */}
              <motion.div 
                className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold z-10
                  ${step.done ? 'text-white' : 'bg-gray-200 text-gray-400'}
                `}
                style={step.done ? { backgroundColor: order.status_color } : {}}
                initial={{ scale: 0 }}
                animate={{ scale: 1 }}
                transition={{ delay: index * 0.1 }}
              >
                {step.done ? '✓' : index + 1}
              </motion.div>
              
              {/* Label */}
              <span className={`text-xs mt-1 ${step.done ? 'text-gray-700' : 'text-gray-400'}`}>
                {step.label}
              </span>
            </div>
          ))}
        </div>
      </div>

      {/* Order Items */}
      <div className="p-4 border-b border-gray-100">
        <p className="text-sm font-medium text-gray-700 mb-2">
          {order.items_count} {t('items')}
        </p>
        <div className="flex gap-2 overflow-x-auto pb-2">
          {order.items.slice(0, 4).map((item, index) => (
            <motion.div
              key={index}
              className="flex-shrink-0 w-16"
              initial={{ opacity: 0, scale: 0.9 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ delay: index * 0.05 }}
            >
              {item.image ? (
                <img 
                  src={item.image} 
                  alt={item.name}
                  className="w-16 h-16 rounded-lg object-cover border border-gray-100"
                />
              ) : (
                <div className="w-16 h-16 bg-gray-100 rounded-lg flex items-center justify-center">
                  <Package className="w-6 h-6 text-gray-400" />
                </div>
              )}
              {item.quantity > 1 && (
                <span className="block text-center text-xs text-gray-500 mt-1">
                  ×{item.quantity}
                </span>
              )}
            </motion.div>
          ))}
          {order.items.length > 4 && (
            <div className="flex-shrink-0 w-16 h-16 bg-gray-100 rounded-lg flex items-center justify-center">
              <span className="text-sm font-medium text-gray-500">
                +{order.items.length - 4}
              </span>
            </div>
          )}
        </div>
      </div>

      {/* Tracking Info */}
      {order.tracking && (
        <div className="p-4 border-b border-gray-100 bg-blue-50">
          <div className="flex items-center gap-2 mb-2">
            <Truck className="w-4 h-4 text-blue-600" />
            <span className="text-sm font-medium text-blue-800">{t('Shipping details')}</span>
          </div>
          <p className="text-sm text-gray-600">
            {order.tracking.provider}: <span className="font-mono">{order.tracking.tracking_number}</span>
          </p>
          {order.tracking.tracking_link && (
            <motion.a
              href={order.tracking.tracking_link}
              target="_blank"
              rel="noopener noreferrer"
              onClick={onTrack}
              className="inline-flex items-center gap-1 text-sm text-blue-600 hover:text-blue-700 mt-2"
              whileHover={{ x: resolvedIsRtl ? -3 : 3 }}
            >
              <MapPin className="w-4 h-4" />
              {t('Track shipment')}
              <ExternalLink className="w-3 h-3" />
            </motion.a>
          )}
        </div>
      )}

      {/* Footer */}
      <div className="p-4 flex items-center justify-between">
        <div>
          <p className="text-sm text-gray-500">{t('Total')}</p>
          <p className="font-bold text-lg text-gray-800" dangerouslySetInnerHTML={{ __html: order.total }} />
        </div>
        <motion.a
          href={order.order_url}
          onClick={onViewOrder}
          className="flex items-center gap-2 px-4 py-2 bg-gray-100 text-gray-700 rounded-lg text-sm font-medium hover:bg-gray-200 transition-colors"
          whileHover={{ scale: 1.02 }}
          whileTap={{ scale: 0.98 }}
        >
          {t('View order')}
          <ExternalLink className="w-4 h-4" />
        </motion.a>
      </div>
    </motion.div>
  )
}

export default OrderStatusWidget

