'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 { MessageSquare, Hash, Users, Circle } 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 { ScrollArea } from '@/components/ui/scroll-area';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { useMessages, useStreams, useUnreadCounts } from '@/hooks/integrations';

interface ZulipContentProps {
  locale: string;
}

/**
 * ZULIP integration content - displays messages and streams
 */
export function ZulipContent({ locale }: ZulipContentProps) {
  const t = useTranslations('widgets.chat');
  const tInt = useTranslations('integrations');
  const { data: messages, isLoading: messagesLoading } = useMessages();
  const { data: streams, isLoading: streamsLoading } = useStreams();
  const { data: unreadCounts } = useUnreadCounts();
  const dateLocale = locale === 'de' ? de : enUS;

  const totalUnread = unreadCounts?.reduce((sum, c) => sum + c.count, 0) ?? 0;

  return (
    <div className="space-y-6">
      {/* Stats Cards */}
      <div className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Streams</CardTitle>
            <Hash className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {streamsLoading ? <Skeleton className="h-8 w-12" /> : streams?.length ?? 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">Ungelesene</CardTitle>
            <Circle className="h-4 w-4 fill-primary text-primary" />
          </CardHeader>
          <CardContent>
            <div className={cn('text-2xl font-bold', totalUnread > 0 && 'text-primary')}>
              {totalUnread}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Nachrichten heute</CardTitle>
            <MessageSquare className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {messagesLoading ? <Skeleton className="h-8 w-12" /> : messages?.length ?? 0}
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        {/* Streams */}
        <Card>
          <CardHeader>
            <CardTitle>Streams</CardTitle>
            <CardDescription>Ihre abonnierten ZULIP Streams</CardDescription>
          </CardHeader>
          <CardContent>
            {streamsLoading ? (
              <div className="space-y-2">
                {Array.from({ length: 4 }).map((_, i) => (
                  <Skeleton key={i} className="h-12 w-full" />
                ))}
              </div>
            ) : streams && streams.length > 0 ? (
              <div className="space-y-2">
                {streams.map((stream) => {
                  const unread = unreadCounts?.find((c) => c.streamId === stream.id);
                  return (
                    <div
                      key={stream.id}
                      className="flex items-center justify-between rounded-lg border p-3 transition-colors hover:bg-muted/50"
                    >
                      <div className="flex items-center gap-3">
                        <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary/10">
                          <Hash className="h-4 w-4 text-primary" />
                        </div>
                        <div>
                          <p className="font-medium">{stream.name}</p>
                          {stream.description && (
                            <p className="text-xs text-muted-foreground">{stream.description}</p>
                          )}
                        </div>
                      </div>
                      {unread && unread.count > 0 && (
                        <Badge variant="default">{unread.count}</Badge>
                      )}
                    </div>
                  );
                })}
              </div>
            ) : (
              <p className="text-center text-muted-foreground">{tInt('noStreamsFound')}</p>
            )}
          </CardContent>
        </Card>

        {/* Recent Messages */}
        <Card>
          <CardHeader>
            <CardTitle>Letzte Nachrichten</CardTitle>
            <CardDescription>Aktuelle Nachrichten aus Ihren Streams</CardDescription>
          </CardHeader>
          <CardContent>
            <ScrollArea className="h-[300px]">
              {messagesLoading ? (
                <div className="space-y-3">
                  {Array.from({ length: 5 }).map((_, i) => (
                    <div key={i} className="flex gap-3">
                      <Skeleton className="h-10 w-10 rounded-full" />
                      <div className="flex-1 space-y-2">
                        <Skeleton className="h-4 w-3/4" />
                        <Skeleton className="h-3 w-1/2" />
                      </div>
                    </div>
                  ))}
                </div>
              ) : messages && messages.length > 0 ? (
                <div className="space-y-4">
                  {messages.map((message, index) => (
                    <motion.div
                      key={message.id}
                      initial={{ opacity: 0, x: -10 }}
                      animate={{ opacity: 1, x: 0 }}
                      transition={{ duration: 0.2, delay: index * 0.03 }}
                      className={cn(
                        'rounded-lg border p-3',
                        !message.isRead && 'border-primary/50 bg-primary/5'
                      )}
                    >
                      <div className="flex items-start gap-3">
                        <Avatar className="h-10 w-10">
                          <AvatarFallback>
                            {message.senderName
                              .split(' ')
                              .map((n) => n[0])
                              .join('')
                              .toUpperCase()}
                          </AvatarFallback>
                        </Avatar>
                        <div className="min-w-0 flex-1">
                          <div className="flex items-center gap-2">
                            <span className="font-medium">{message.senderName}</span>
                            {!message.isRead && (
                              <Circle className="h-2 w-2 fill-primary text-primary" />
                            )}
                          </div>
                          <div className="flex items-center gap-1 text-xs text-muted-foreground">
                            <Hash className="h-3 w-3" />
                            {message.streamName} - {message.topic}
                          </div>
                          <p className="mt-1 text-sm">{message.content}</p>
                          <p className="mt-1 text-xs text-muted-foreground">
                            {formatDistanceToNow(message.timestamp, {
                              addSuffix: true,
                              locale: dateLocale,
                            })}
                          </p>
                        </div>
                      </div>
                    </motion.div>
                  ))}
                </div>
              ) : (
                <p className="text-center text-muted-foreground">{t('noMessages')}</p>
              )}
            </ScrollArea>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
