'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 { Headphones, MessageCircle, AlertTriangle, Clock, User, CheckCircle } 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 { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { useTickets, useTicketCounts } from '@/hooks/integrations';
import type { TicketPriority, TicketStatus } from '@/types/integrations';

interface FreeScoutContentProps {
  locale: string;
}

/** Priority badge variants */
const priorityVariants: Record<TicketPriority, 'default' | 'secondary' | 'destructive' | 'warning'> = {
  urgent: 'destructive',
  high: 'warning',
  medium: 'secondary',
  low: 'default',
};

/** Status badge variants */
const statusVariants: Record<TicketStatus, 'default' | 'secondary' | 'success' | 'outline'> = {
  open: 'default',
  pending: 'secondary',
  resolved: 'success',
  closed: 'outline',
};

/**
 * FreeScout integration content - displays tickets
 */
export function FreeScoutContent({ locale }: FreeScoutContentProps) {
  const t = useTranslations('widgets.tickets');
  const { data: tickets, isLoading: ticketsLoading } = useTickets({ limit: 15 });
  const { data: counts, isLoading: countsLoading } = useTicketCounts();
  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.open')}</CardTitle>
            <Headphones className="h-4 w-4 text-primary" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {countsLoading ? <Skeleton className="h-8 w-12" /> : counts?.open ?? 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.pending')}</CardTitle>
            <Clock className="h-4 w-4 text-yellow-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {countsLoading ? <Skeleton className="h-8 w-12" /> : counts?.pending ?? 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('priority.urgent')}</CardTitle>
            <AlertTriangle className="h-4 w-4 text-destructive" />
          </CardHeader>
          <CardContent>
            <div className={cn('text-2xl font-bold', (counts?.byPriority?.urgent ?? 0) > 0 && 'text-destructive')}>
              {countsLoading ? <Skeleton className="h-8 w-12" /> : counts?.byPriority?.urgent ?? 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.resolved')}</CardTitle>
            <CheckCircle className="h-4 w-4 text-green-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-500">
              {countsLoading ? <Skeleton className="h-8 w-12" /> : counts?.resolved ?? 0}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Tickets Table */}
      <Card>
        <CardHeader>
          <CardTitle>Support-Tickets</CardTitle>
          <CardDescription>Aktuelle Tickets aus FreeScout</CardDescription>
        </CardHeader>
        <CardContent>
          {ticketsLoading ? (
            <div className="space-y-2">
              {Array.from({ length: 5 }).map((_, i) => (
                <Skeleton key={i} className="h-16 w-full" />
              ))}
            </div>
          ) : tickets && tickets.length > 0 ? (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-20">#</TableHead>
                  <TableHead>Betreff</TableHead>
                  <TableHead>Kunde</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Prioritaet</TableHead>
                  <TableHead>Zugewiesen</TableHead>
                  <TableHead className="text-right">Antworten</TableHead>
                  <TableHead>Aktualisiert</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {tickets.map((ticket, index) => (
                  <motion.tr
                    key={ticket.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-mono text-sm">{ticket.number}</TableCell>
                    <TableCell>
                      <p className="max-w-[200px] truncate font-medium">{ticket.subject}</p>
                    </TableCell>
                    <TableCell>
                      <div>
                        <p className="truncate">{ticket.customerName}</p>
                        <p className="truncate text-xs text-muted-foreground">{ticket.customerEmail}</p>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant={statusVariants[ticket.status]}>
                        {t(`status.${ticket.status}`)}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Badge variant={priorityVariants[ticket.priority]}>
                        {t(`priority.${ticket.priority}`)}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      {ticket.assigneeName ? (
                        <div className="flex items-center gap-2">
                          <Avatar className="h-6 w-6">
                            <AvatarFallback className="text-xs">
                              {ticket.assigneeName
                                .split(' ')
                                .map((n) => n[0])
                                .join('')}
                            </AvatarFallback>
                          </Avatar>
                          <span className="text-sm">{ticket.assigneeName}</span>
                        </div>
                      ) : (
                        <span className="text-muted-foreground">-</span>
                      )}
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex items-center justify-end gap-1">
                        <MessageCircle className="h-4 w-4 text-muted-foreground" />
                        {ticket.replyCount}
                      </div>
                    </TableCell>
                    <TableCell className="text-muted-foreground">
                      {ticket.lastReplyAt
                        ? formatDistanceToNow(ticket.lastReplyAt, {
                            addSuffix: true,
                            locale: dateLocale,
                          })
                        : '-'}
                    </TableCell>
                  </motion.tr>
                ))}
              </TableBody>
            </Table>
          ) : (
            <div className="flex items-center justify-center py-8 text-muted-foreground">
              <Headphones className="mr-2 h-5 w-5" />
              {t('noTickets')}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
