'use client';

import { useTranslations } from 'next-intl';
import { formatDistanceToNow } from 'date-fns';
import { de, enUS } from 'date-fns/locale';
import { motion } from 'framer-motion';
import Link from 'next/link';
import { ShoppingCart, Package, Truck, Eye, MoreHorizontal } from 'lucide-react';

import { cn } from '@/lib/utils';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { WidgetContainer } from '../../widget-container';
import { useOrders } from '@/hooks/integrations';
import type { OrderStatus } from '@/types/integrations';

interface OrdersWidgetProps {
  id: string;
  isEditing?: boolean;
  onRemove?: () => void;
  locale?: string;
  maxItems?: number;
  className?: string;
}

/** Status badge configuration */
const statusConfig: Record<
  OrderStatus,
  { variant: 'default' | 'secondary' | 'success' | 'warning' | 'destructive'; labelKey: string }
> = {
  new: { variant: 'default', labelKey: 'new' },
  processing: { variant: 'warning', labelKey: 'processing' },
  shipped: { variant: 'success', labelKey: 'shipped' },
  delivered: { variant: 'secondary', labelKey: 'delivered' },
  cancelled: { variant: 'destructive', labelKey: 'cancelled' },
  returned: { variant: 'destructive', labelKey: 'returned' },
};

/**
 * Orders Widget - Displays recent PlentyONE orders with status
 */
export function OrdersWidget({
  id,
  isEditing = false,
  onRemove,
  locale = 'de',
  maxItems = 5,
  className,
}: OrdersWidgetProps) {
  const t = useTranslations('widgets.orders');
  const { data: orders, isLoading, error } = useOrders({ limit: maxItems });
  const dateLocale = locale === 'de' ? de : enUS;

  return (
    <WidgetContainer
      id={id}
      title={t('name')}
      icon={<ShoppingCart className="h-4 w-4 text-primary" />}
      isEditing={isEditing}
      onRemove={onRemove}
      className={className}
    >
      <ScrollArea className="h-[220px] pr-2">
        {isLoading ? (
          <div className="space-y-3">
            {Array.from({ length: 4 }).map((_, i) => (
              <div key={i} className="flex items-center justify-between">
                <div className="space-y-2">
                  <Skeleton className="h-4 w-32" />
                  <Skeleton className="h-3 w-24" />
                </div>
                <Skeleton className="h-6 w-20" />
              </div>
            ))}
          </div>
        ) : error ? (
          <div className="flex h-full items-center justify-center text-sm text-muted-foreground">
            {t('error')}
          </div>
        ) : orders && orders.length > 0 ? (
          <div className="space-y-3">
            {orders.map((order, index) => {
              const status = statusConfig[order.status];
              return (
                <motion.div
                  key={order.id}
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.2, delay: index * 0.05 }}
                  className="flex items-center justify-between rounded-lg border p-3 transition-colors hover:bg-muted/50"
                >
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-2">
                      <span className="truncate font-medium">{order.orderNumber}</span>
                      <Badge variant={status.variant} className="shrink-0">
                        {t(`status.${order.status}`)}
                      </Badge>
                    </div>
                    <div className="mt-1 flex items-center gap-2 text-sm text-muted-foreground">
                      <span className="truncate">{order.customerName}</span>
                      <span>-</span>
                      <span className="font-medium">
                        {order.totalAmount.toLocaleString(locale, {
                          style: 'currency',
                          currency: order.currency,
                        })}
                      </span>
                    </div>
                    <p className="mt-1 text-xs text-muted-foreground">
                      {formatDistanceToNow(order.createdAt, {
                        addSuffix: true,
                        locale: dateLocale,
                      })}
                    </p>
                  </div>

                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button variant="ghost" size="icon" className="h-8 w-8 shrink-0">
                        <MoreHorizontal className="h-4 w-4" />
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                      <DropdownMenuItem>
                        <Eye className="mr-2 h-4 w-4" />
                        {t('viewDetails')}
                      </DropdownMenuItem>
                      {order.status === 'processing' && (
                        <DropdownMenuItem>
                          <Truck className="mr-2 h-4 w-4" />
                          {t('markShipped')}
                        </DropdownMenuItem>
                      )}
                    </DropdownMenuContent>
                  </DropdownMenu>
                </motion.div>
              );
            })}
          </div>
        ) : (
          <div className="flex h-full items-center justify-center text-sm text-muted-foreground">
            {t('noOrders')}
          </div>
        )}
      </ScrollArea>

      {/* Footer link */}
      <div className="mt-3 border-t pt-3">
        <Button variant="ghost" size="sm" className="w-full" asChild>
          <Link href={`/${locale}/integrations/plentyone`}>
            <Package className="mr-2 h-4 w-4" />
            {t('viewAll')}
          </Link>
        </Button>
      </div>
    </WidgetContainer>
  );
}
