'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 { Package, ShoppingCart, TrendingUp, TrendingDown, Truck, AlertCircle } from 'lucide-react';

import { cn } from '@/lib/utils';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { useOrders, useOrderCounts } from '@/hooks/integrations';
import type { OrderStatus } from '@/types/integrations';

interface PlentyOneContentProps {
  locale: string;
}

/** Order status badge variants */
const statusVariants: Record<OrderStatus, 'default' | 'secondary' | 'success' | 'warning' | 'destructive'> = {
  new: 'default',
  processing: 'warning',
  shipped: 'success',
  delivered: 'secondary',
  cancelled: 'destructive',
  returned: 'destructive',
};

/**
 * PlentyONE integration content - displays orders and statistics
 */
export function PlentyOneContent({ locale }: PlentyOneContentProps) {
  const t = useTranslations('widgets.orders');
  const { data: orders, isLoading: ordersLoading } = useOrders({ limit: 10 });
  const { data: counts, isLoading: countsLoading } = useOrderCounts();
  const dateLocale = locale === 'de' ? de : enUS;

  return (
    <div className="space-y-6">
      {/* Stats Cards */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">{t('status.new')}</CardTitle>
            <ShoppingCart className="h-4 w-4 text-primary" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {countsLoading ? <Skeleton className="h-8 w-12" /> : counts?.new ?? 0}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">{t('status.processing')}</CardTitle>
            <Package className="h-4 w-4 text-yellow-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {countsLoading ? <Skeleton className="h-8 w-12" /> : counts?.processing ?? 0}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">{t('status.shipped')}</CardTitle>
            <Truck className="h-4 w-4 text-green-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {countsLoading ? <Skeleton className="h-8 w-12" /> : counts?.shipped ?? 0}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Gesamt</CardTitle>
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {countsLoading ? <Skeleton className="h-8 w-12" /> : counts?.total ?? 0}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Orders Table */}
      <Card>
        <CardHeader>
          <CardTitle>Letzte Bestellungen</CardTitle>
          <CardDescription>Die 10 neuesten Bestellungen aus PlentyONE</CardDescription>
        </CardHeader>
        <CardContent>
          {ordersLoading ? (
            <div className="space-y-2">
              {Array.from({ length: 5 }).map((_, i) => (
                <Skeleton key={i} className="h-12 w-full" />
              ))}
            </div>
          ) : orders && orders.length > 0 ? (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Bestellnummer</TableHead>
                  <TableHead>Kunde</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead className="text-right">Betrag</TableHead>
                  <TableHead>Datum</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {orders.map((order, index) => (
                  <motion.tr
                    key={order.id}
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.2, delay: index * 0.03 }}
                    className="border-b transition-colors hover:bg-muted/50"
                  >
                    <TableCell className="font-medium">{order.orderNumber}</TableCell>
                    <TableCell>
                      <div>
                        <p>{order.customerName}</p>
                        <p className="text-xs text-muted-foreground">{order.customerEmail}</p>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant={statusVariants[order.status]}>
                        {t(`status.${order.status}`)}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-right font-medium">
                      {order.totalAmount.toLocaleString(locale, {
                        style: 'currency',
                        currency: order.currency,
                      })}
                    </TableCell>
                    <TableCell className="text-muted-foreground">
                      {formatDistanceToNow(order.createdAt, {
                        addSuffix: true,
                        locale: dateLocale,
                      })}
                    </TableCell>
                  </motion.tr>
                ))}
              </TableBody>
            </Table>
          ) : (
            <div className="flex items-center justify-center py-8 text-muted-foreground">
              <Package className="mr-2 h-5 w-5" />
              {t('noOrders')}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
