import { useQuery } from '@tanstack/react-query';
import { Link } from '@tanstack/react-router';
import { fetchPinnedLiveBlogs } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Calendar, Eye, MessageSquare, Pin, ChevronDown, ChevronUp, Clock } from 'lucide-react';
import { useState } from 'react';

export function PinnedLiveBlogsSidebar() {
  const [showUpdates, setShowUpdates] = useState(true);

  const { data: liveBlogs, isLoading, error } = useQuery({
    queryKey: ['pinned-live-blogs'],
    queryFn: fetchPinnedLiveBlogs,
  });

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'live':
        return (
          <span className="px-2 py-0.5 bg-accent text-foreground text-xs font-body font-bold uppercase">
            LIVE
          </span>
        );
      case 'ended':
        return (
          <span className="px-2 py-0.5 border-2 border-foreground/40 text-foreground/40 text-xs font-body font-bold uppercase">
            ENDED
          </span>
        );
      case 'archived':
        return (
          <span className="px-2 py-0.5 border-2 border-foreground/30 text-foreground/30 text-xs font-body font-bold uppercase">
            ARCHIVED
          </span>
        );
      default:
        return (
          <span className="px-2 py-0.5 border-2 border-foreground text-foreground text-xs font-body font-bold uppercase">
            DRAFT
          </span>
        );
    }
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('mk-MK', {
      day: 'numeric',
      month: 'short',
    });
  };

  const formatRelativeTime = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    const diffDays = Math.floor(diffMs / 86400000);

    if (diffMins < 1) return 'сега';
    if (diffMins < 60) return `${diffMins}м`;
    if (diffHours < 24) return `${diffHours}ч`;
    return `${diffDays}д`;
  };

  // Collect last 5 updates from all pinned live blogs
  const getLastFiveUpdates = () => {
    if (!liveBlogs) return [];

    const allUpdates: Array<{
      id: string;
      content: string;
      createdAt: string;
      liveBlogTitle: string;
      liveBlogSlug: string;
    }> = [];

    liveBlogs.forEach((liveBlog) => {
      if (liveBlog.updates && liveBlog.updates.length > 0) {
        liveBlog.updates.forEach((update) => {
          allUpdates.push({
            ...update,
            liveBlogTitle: liveBlog.title,
            liveBlogSlug: liveBlog.slug,
          });
        });
      }
    });

    // Sort by date descending and take first 5
    return allUpdates
      .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
      .slice(0, 5);
  };

  const lastFiveUpdates = getLastFiveUpdates();

  if (isLoading) {
    return (
      <div className="border-brutal-sm bg-card p-6">
        <div className="flex items-center gap-2 mb-6">
          <Pin className="h-5 w-5" />
          <h3 className="text-xl font-display">Pinned Live</h3>
        </div>
        <div className="space-y-4">
          {[1, 2, 3].map((i) => (
            <div key={i} className="animate-pulse">
              <div className="h-4 bg-muted rounded w-3/4 mb-2"></div>
              <div className="h-3 bg-muted rounded w-1/2"></div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="border-brutal-sm bg-card p-6">
        <div className="flex items-center gap-2 mb-6">
          <Pin className="h-5 w-5" />
          <h3 className="text-xl font-display">Pinned Live</h3>
        </div>
        <div className="text-center py-4">
          <div className="text-destructive font-body text-sm mb-2">ERROR</div>
          <Button variant="brutal" size="sm" onClick={() => window.location.reload()}>
            Retry
          </Button>
        </div>
      </div>
    );
  }

  if (!liveBlogs || liveBlogs.length === 0) {
    return (
      <div className="border-brutal-sm bg-card p-6">
        <div className="flex items-center gap-2 mb-6">
          <Pin className="h-5 w-5" />
          <h3 className="text-xl font-display">Pinned Live</h3>
        </div>
        <div className="text-center py-6 border-2 border-dashed border-foreground/20 p-4">
          <div className="font-body text-muted-foreground mb-2">No pinned live blogs</div>
          <p className="font-body text-xs text-muted-foreground">
            Pin live blogs from the admin panel.
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="border-brutal-sm bg-card p-6">
      {/* Latest Updates Section - Collapsible */}
      {lastFiveUpdates.length > 0 && (
        <div className="mb-6 pb-6 border-b-2 border-foreground/10">
          <button
            onClick={() => setShowUpdates(!showUpdates)}
            className="w-full flex items-center justify-between mb-4 group"
          >
            <div className="flex items-center gap-2">
              <Clock className="h-5 w-5 text-accent" />
              <h3 className="text-xl font-display">Свежо набрано</h3>
            </div>
            <div className="flex items-center gap-2">
              <span className="px-2 py-1 border-2 border-foreground bg-foreground text-background text-xs font-body font-bold uppercase">
                {lastFiveUpdates.length}
              </span>
              {showUpdates ? (
                <ChevronUp className="h-4 w-4 transition-transform" />
              ) : (
                <ChevronDown className="h-4 w-4 transition-transform" />
              )}
            </div>
          </button>

          {showUpdates && (
            <div className="space-y-3 animate-scale-in">
              {lastFiveUpdates.map((update) => (
                <Link
                  key={update.id}
                  to="/live-blogs/$slug"
                  params={{ slug: update.liveBlogSlug }}
                  className="block group"
                >
                  <div className="p-3 border-2 border-foreground/10 hover:border-accent hover:bg-accent/5 transition-all duration-150">
                    <div className="flex items-start justify-between gap-2 mb-2">
                      <span className="text-xs font-body font-bold text-muted-foreground line-clamp-1">
                        {update.liveBlogTitle}
                      </span>
                      <span className="text-xs font-body text-muted-foreground whitespace-nowrap">
                        {formatRelativeTime(update.createdAt)}
                      </span>
                    </div>
                    <p className="text-sm font-body text-foreground line-clamp-2 group-hover:text-accent transition-colors">
                      {update.content.replace(/<[^>]*>/g, '').substring(0, 120)}
                      {update.content.length > 120 ? '...' : ''}
                    </p>
                  </div>
                </Link>
              ))}
            </div>
          )}
        </div>
      )}

      <div className="flex items-center justify-between mb-6 pb-4 border-b-2 border-foreground/10">
        <div className="flex items-center gap-2">
          <Pin className="h-5 w-5 text-accent" />
          <h3 className="text-xl font-display">Во Живо</h3>
        </div>
        <span className="px-2 py-1 border-2 border-foreground bg-foreground text-background text-xs font-body font-bold uppercase">
          {liveBlogs.length}
        </span>
      </div>

      <div className="space-y-4">
        {liveBlogs.map((liveBlog) => (
          <Link
            key={liveBlog.id}
            to="/live-blogs/$slug"
            params={{ slug: liveBlog.slug }}
            className="block group"
          >
            <div className="p-4 border-2 border-foreground/10 hover:border-foreground hover:shadow-brutal-sm transition-all duration-150 group-hover:-translate-y-1">
              <div className="flex items-start justify-between mb-2">
                <h4 className="font-body text-sm font-bold leading-tight line-clamp-2 group-hover:text-accent transition-colors">
                  {liveBlog.title}
                </h4>
                {getStatusBadge(liveBlog.status)}
              </div>

              {liveBlog.description && (
                <p className="text-xs font-body text-muted-foreground mb-3 line-clamp-2">
                  {liveBlog.description}
                </p>
              )}

              <div className="flex flex-wrap items-center gap-3 text-xs font-body text-muted-foreground">
                <div className="flex items-center gap-1">
                  <Calendar className="h-3 w-3" />
                  <span>{formatDate(liveBlog.createdAt)}</span>
                </div>

                <div className="flex items-center gap-1">
                  <Eye className="h-3 w-3" />
                  <span>{liveBlog.viewCount}</span>
                </div>

                {liveBlog.updates && liveBlog.updates.length > 0 && (
                  <div className="flex items-center gap-1">
                    <MessageSquare className="h-3 w-3" />
                    <span>{liveBlog.updates.length}</span>
                  </div>
                )}

                {liveBlog.author && (
                  <div className="text-xs text-muted-foreground">
                    {liveBlog.author.name}
                  </div>
                )}
              </div>

              {liveBlog.featuredImage && (
                <div className="mt-3">
                  <div className="relative h-20 border-2 border-foreground/10 overflow-hidden">
                    <img
                      src={liveBlog.featuredImage}
                      alt={liveBlog.title}
                      className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-110"
                    />
                  </div>
                </div>
              )}
            </div>
          </Link>
        ))}
      </div>

      <div className="mt-6 pt-4 border-t-2 border-foreground/10">
        <Link to="/live-blogs" className="block">
          <Button variant="brutal" className="w-full justify-center">
            ...
          </Button>
        </Link>
      </div>
    </div>
  );
}
