'use client';

import { useState } from 'react';
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 { MessageSquare, Send, Hash, Circle } from 'lucide-react';

import { cn } from '@/lib/utils';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { WidgetContainer } from '../../widget-container';
import { useMessages, useUnreadCounts, useSendMessage } from '@/hooks/integrations';

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

/**
 * Chat Widget - Displays recent ZULIP messages with quick reply
 */
export function ChatWidget({
  id,
  isEditing = false,
  onRemove,
  locale = 'de',
  maxItems = 5,
  className,
}: ChatWidgetProps) {
  const t = useTranslations('widgets.chat');
  const { data: messages, isLoading: messagesLoading } = useMessages();
  const { data: unreadCounts } = useUnreadCounts();
  const sendMessage = useSendMessage();
  const [replyTo, setReplyTo] = useState<number | null>(null);
  const [replyText, setReplyText] = useState('');
  const dateLocale = locale === 'de' ? de : enUS;

  const displayedMessages = messages?.slice(0, maxItems) ?? [];
  const totalUnread = unreadCounts?.reduce((sum, c) => sum + c.count, 0) ?? 0;

  const handleReply = async () => {
    if (!replyText.trim() || !replyTo) return;

    const message = messages?.find((m) => m.id === replyTo);
    if (!message) return;

    await sendMessage.mutateAsync({
      streamId: message.streamId,
      topic: message.topic,
      content: replyText,
    });

    setReplyText('');
    setReplyTo(null);
  };

  return (
    <WidgetContainer
      id={id}
      title={t('name')}
      icon={
        <div className="relative">
          <MessageSquare className="h-4 w-4 text-primary" />
          {totalUnread > 0 && (
            <span className="absolute -right-1 -top-1 flex h-3 w-3 items-center justify-center rounded-full bg-destructive text-[8px] text-white">
              {totalUnread > 9 ? '9+' : totalUnread}
            </span>
          )}
        </div>
      }
      isEditing={isEditing}
      onRemove={onRemove}
      className={className}
    >
      <ScrollArea className="h-[200px] pr-2">
        {messagesLoading ? (
          <div className="space-y-3">
            {Array.from({ length: 4 }).map((_, i) => (
              <div key={i} className="flex gap-3">
                <Skeleton className="h-8 w-8 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>
        ) : displayedMessages.length > 0 ? (
          <div className="space-y-3">
            {displayedMessages.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.05 }}
                className={cn(
                  'rounded-lg border p-2 transition-colors',
                  !message.isRead && 'border-primary/50 bg-primary/5',
                  replyTo === message.id && 'ring-2 ring-primary'
                )}
              >
                <div className="flex items-start gap-2">
                  <Avatar className="h-8 w-8">
                    <AvatarFallback className="text-xs">
                      {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="truncate text-sm 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" />
                      <span>{message.streamName}</span>
                      <span>-</span>
                      <span className="truncate">{message.topic}</span>
                    </div>
                    <p className="mt-1 line-clamp-2 text-sm">{message.content}</p>
                    <div className="mt-1 flex items-center justify-between">
                      <span className="text-xs text-muted-foreground">
                        {formatDistanceToNow(message.timestamp, {
                          addSuffix: true,
                          locale: dateLocale,
                        })}
                      </span>
                      <Button
                        variant="ghost"
                        size="sm"
                        className="h-6 text-xs"
                        onClick={() =>
                          setReplyTo(replyTo === message.id ? null : message.id)
                        }
                      >
                        {t('reply')}
                      </Button>
                    </div>
                  </div>
                </div>
              </motion.div>
            ))}
          </div>
        ) : (
          <div className="flex h-full items-center justify-center text-sm text-muted-foreground">
            {t('noMessages')}
          </div>
        )}
      </ScrollArea>

      {/* Quick Reply */}
      {replyTo && (
        <motion.div
          initial={{ opacity: 0, height: 0 }}
          animate={{ opacity: 1, height: 'auto' }}
          exit={{ opacity: 0, height: 0 }}
          className="mt-2 flex gap-2"
        >
          <Input
            value={replyText}
            onChange={(e) => setReplyText(e.target.value)}
            placeholder={t('replyPlaceholder')}
            className="h-8 text-sm"
            onKeyDown={(e) => {
              if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                handleReply();
              }
            }}
          />
          <Button
            size="icon"
            className="h-8 w-8 shrink-0"
            onClick={handleReply}
            disabled={!replyText.trim() || sendMessage.isPending}
          >
            <Send className="h-4 w-4" />
          </Button>
        </motion.div>
      )}

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