import { Suspense } from "react";
import Agenda from "@/components/event/agenda";
import Countdown from "@/components/event/countdown";
import { QuestionForm } from "@/components/question/question-form";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useAuth } from "@/hooks/use-auth";
import { useLanguage } from "@/hooks/use-language";
import { useQuery } from "@tanstack/react-query";
import { Session, Speaker } from "@shared/schema";
import { format } from "date-fns";
import { Calendar, MapPin, Clock, ArrowRight, Loader2 } from "lucide-react";
import { Link } from "wouter";
import { Button } from "@/components/ui/button";

type SessionWithSpeakers = Session & {
  speakers: Speaker[];
};

// Separate component for sessions list to enable suspense boundary
function UpcomingSessions() {
  const { language, t } = useLanguage();
  const isArabic = language === 'ar';

  const { data: sessions, isLoading } = useQuery<SessionWithSpeakers[]>({
    queryKey: ["/api/sessions"],
    staleTime: 5 * 60 * 1000, // Keep fresh for 5 minutes
    gcTime: 10 * 60 * 1000, // Cache for 10 minutes
    suspense: true,
  });

  if (isLoading) {
    return <Loader2 className="h-8 w-8 animate-spin mx-auto" />;
  }

  // Sort sessions by date and time, and take first 5
  const upcomingSessions = sessions
    ?.sort((a, b) => {
      const dateA = new Date(`${a.sessionDate}T${a.sessionTime}`);
      const dateB = new Date(`${b.sessionDate}T${b.sessionTime}`);
      return dateA.getTime() - dateB.getTime();
    })
    .slice(0, 5);

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between pb-2">
        <CardTitle>{t("Upcoming Sessions", "الجلسات القادمة")}</CardTitle>
        <Link href="/sessions">
          <Button variant="ghost" className="flex items-center gap-2">
            {t("View All Sessions", "عرض كل الجلسات")}
            <ArrowRight className="h-4 w-4" />
          </Button>
        </Link>
      </CardHeader>
      <CardContent className="space-y-6">
        {upcomingSessions?.map((session) => (
          <Link key={session.id} href={`/sessions/${session.id}`}>
            <div className="p-6 rounded-lg border hover:bg-accent cursor-pointer transition-colors">
              <h3 className="text-lg font-semibold mb-4">
                {isArabic ? session.sessionTitleAr : session.sessionTitle}
              </h3>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-4">
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <Calendar className="h-4 w-4 flex-shrink-0" />
                  <span>{format(new Date(session.sessionDate), "PPP")}</span>
                </div>
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <Clock className="h-4 w-4 flex-shrink-0" />
                  <span>
                    {format(new Date(`2000-01-01T${session.sessionTime}`), "p")}
                  </span>
                </div>
                <div className="flex items-center gap-2 text-sm text-muted-foreground sm:col-span-2">
                  <MapPin className="h-4 w-4 flex-shrink-0" />
                  <span>{isArabic ? session.venueAr : session.venue}</span>
                </div>
              </div>
              {session.speakers?.length > 0 && (
                <div className="border-t pt-4">
                  <p className="text-sm font-medium mb-2">
                    {t("Speakers", "المتحدثون")}:
                  </p>
                  <div className="flex flex-wrap gap-3">
                    {session.speakers.map((speaker) => (
                      <div
                        key={speaker.id}
                        className="flex items-center gap-2 bg-muted/50 rounded-full px-3 py-1"
                      >
                        <div className="w-6 h-6 rounded-full overflow-hidden border">
                          <img
                            src={speaker.imageUrl}
                            alt={isArabic ? speaker.nameAr : speaker.name}
                            className="w-full h-full object-cover"
                          />
                        </div>
                        <span className="text-sm">
                          {isArabic ? speaker.nameAr : speaker.name}
                        </span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </Link>
        ))}
      </CardContent>
    </Card>
  );
}

// Separate questions component with its own suspense boundary
function Questions() {
  const { language, t } = useLanguage();

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t("Ask a Question", "اطرح سؤالاً")}</CardTitle>
      </CardHeader>
      <CardContent>
        <QuestionForm />
      </CardContent>
    </Card>
  );
}

export default function HomePage() {
  const { user } = useAuth();
  const { language, t } = useLanguage();
  const isArabic = language === 'ar';

  return (
    <div className="space-y-8">
      <section className="text-center py-12">
        <h1 className="text-4xl font-bold mb-4">
          {t(
            "Welcome to National Development Summit 2025",
            "مرحباً بكم في قمة التنمية الوطنية 2025"
          )}
        </h1>
        <p className="text-xl text-muted-foreground mb-8">
          {t(
            "Shaping the Future of National Development",
            "تشكيل مستقبل التنمية الوطنية"
          )}
        </p>
        <Countdown />
      </section>

      <div className="grid md:grid-cols-2 gap-8">
        <Suspense fallback={<Loader2 className="h-8 w-8 animate-spin mx-auto" />}>
          <UpcomingSessions />
        </Suspense>
        <Suspense fallback={<Loader2 className="h-8 w-8 animate-spin mx-auto" />}>
          <Questions />
        </Suspense>
      </div>
    </div>
  );
}