import { useState } from "react";
import { useLanguage } from "@/hooks/use-language";
import { useToast } from "@/hooks/use-toast";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Loader2, WifiOff } from "lucide-react";
import { useNotifications } from "@/components/notification/notification-provider";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useQuery } from "@tanstack/react-query";
import { apiRequest } from "@/lib/queryClient";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

// Define system pages structure
const systemPages = [
  {
    label: "Program",
    value: "/sessions",
    subPages: [
      { label: "Session Details", value: "/sessions/:id" },
      { label: "Live Stream", value: "/sessions/:id/live" },
    ],
  },
  {
    label: "Live Streams",
    value: "/live-streams",
    subPages: [
      { label: "Stream View", value: "/live-streams/:id" },
    ],
  },
  {
    label: "Speakers",
    value: "/speakers",
    subPages: [
      { label: "Speaker Profile", value: "/speakers/:id" },
    ],
  },
  {
    label: "News",
    value: "/news",
    subPages: [
      { label: "News Article", value: "/news/:id" },
    ],
  },
  {
    label: "Gallery",
    value: "/gallery",
    subPages: [
      { label: "Image Gallery", value: "/gallery/images" },
      { label: "Video Gallery", value: "/gallery/videos" },
    ],
  },
  {
    label: "Polls",
    value: "/polls",
    subPages: [
      { label: "Poll Submission", value: "/polls/:id/submit" },
      { label: "Poll Results", value: "/polls/:id/results" },
    ],
  },
];

export default function NotificationsPage() {
  const { t } = useLanguage();
  const { isConnected, sendNotification } = useNotifications();
  const [isLoading, setIsLoading] = useState(false);
  const [urlType, setUrlType] = useState<"custom" | "system">("custom");
  const [selectedMainPage, setSelectedMainPage] = useState<string>("");
  const [selectedSubPage, setSelectedSubPage] = useState<string>("main_page_only");
  const [selectedItemId, setSelectedItemId] = useState<string | null>(null);
  const { toast } = useToast();

  // Fetch data based on selected main page
  const { data: newsArticles } = useQuery({
    queryKey: ["/api/news"],
    enabled: selectedMainPage === "/news" && selectedSubPage !== "main_page_only",
  });

  const { data: speakers } = useQuery({
    queryKey: ["/api/speakers"],
    enabled: selectedMainPage === "/speakers" && selectedSubPage !== "main_page_only",
  });

  const { data: sessions } = useQuery({
    queryKey: ["/api/sessions"],
    enabled: selectedMainPage === "/sessions" && selectedSubPage !== "main_page_only",
  });

  const { data: polls } = useQuery({
    queryKey: ["/api/polls"],
    enabled: selectedMainPage === "/polls" && selectedSubPage !== "main_page_only",
  });

  const { data: streams } = useQuery({
    queryKey: ["/api/sessions/live-streams"],
    enabled: selectedMainPage === "/live-streams" && selectedSubPage !== "main_page_only",
  });

  const getSelectedPage = () => {
    if (urlType === "custom") {
      return null;
    }

    const mainPage = systemPages.find(page => page.value === selectedMainPage);
    if (!mainPage) return null;

    if (selectedSubPage === "main_page_only") {
      return mainPage.value;
    }

    // Handle specific item selection
    if (selectedItemId) {
      const subPage = mainPage.subPages.find(sub => sub.value === selectedSubPage);
      if (!subPage) return mainPage.value;

      // Handle live streams differently
      if (mainPage.value === "/live-streams") {
        return `/live-streams/${selectedItemId}`;
      }

      // Replace :id with the actual selected item ID
      return subPage.value.replace(":id", selectedItemId);
    }

    return mainPage.value;
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setIsLoading(true);

    const form = e.target as HTMLFormElement;
    const title = (form.elements.namedItem('title') as HTMLInputElement).value;
    const body = (form.elements.namedItem('body') as HTMLInputElement).value;
    let url = urlType === "custom" 
      ? (form.elements.namedItem('url') as HTMLInputElement).value
      : getSelectedPage();

    // Add isLiveStream flag for live stream notifications
    const isLiveStream = selectedMainPage === "/live-streams" && selectedItemId !== null;
    const sessionId = isLiveStream ? parseInt(selectedItemId!) : undefined;

    try {
      await sendNotification({
        title,
        body,
        url: url || undefined,
        sessionId,
        isLiveStream
      });

      toast({
        title: t("Success", "نجاح"),
        description: t("Notification sent successfully", "تم إرسال الإشعار بنجاح"),
      });

      form.reset();
      setSelectedMainPage("");
      setSelectedSubPage("main_page_only");
      setSelectedItemId(null);
    } catch (error) {
      console.error('Error in form submission:', error);
      toast({
        title: t("Error", "خطأ"),
        description: error instanceof Error ? error.message : t("Failed to send notification", "فشل في إرسال الإشعار"),
        variant: "destructive",
      });
    } finally {
      setIsLoading(false);
    }
  };

  // Render specific items based on selected page type
  const renderSpecificItems = () => {
    if (selectedSubPage === "main_page_only") return null;

    switch (selectedMainPage) {
      case "/news":
        return newsArticles?.map(article => (
          <SelectItem key={article.id} value={article.id.toString()}>
            {article.title}
          </SelectItem>
        ));
      case "/speakers":
        return speakers?.map(speaker => (
          <SelectItem key={speaker.id} value={speaker.id.toString()}>
            {speaker.name}
          </SelectItem>
        ));
      case "/sessions":
        return sessions?.map(session => (
          <SelectItem key={session.id} value={session.id.toString()}>
            {session.sessionTitle}
          </SelectItem>
        ));
      case "/polls":
        return polls?.map(poll => (
          <SelectItem key={poll.id} value={poll.id.toString()}>
            {poll.title}
          </SelectItem>
        ));
      case "/live-streams":
        return streams?.sessions?.map((stream: any) => ( //Type assertion added here
          <SelectItem key={stream.id} value={stream.id.toString()}>
            {stream.sessionTitle}
          </SelectItem>
        ));
      default:
        return null;
    }
  };

  const shouldShowSpecificItems = () => {
    return selectedMainPage && selectedSubPage !== "main_page_only" && ["/news", "/speakers", "/sessions", "/polls", "/live-streams"].includes(selectedMainPage);
  };

  return (
    <div className="container mx-auto py-8">
      <div className="flex justify-between items-center mb-8">
        <h1 className="text-3xl font-bold">
          {t("Notification Management", "إدارة الإشعارات")}
        </h1>

        {!isConnected && (
          <div className="flex items-center gap-2 text-destructive">
            <WifiOff className="h-4 w-4" />
            <span className="text-sm">
              {t("Disconnected from notification service", "غير متصل بخدمة الإشعارات")}
            </span>
          </div>
        )}
      </div>

      <Card>
        <CardHeader>
          <CardTitle>{t("Send Push Notification", "إرسال إشعار")}</CardTitle>
          <CardDescription>
            {t(
              "Send a push notification to all registered users",
              "إرسال إشعار لجميع المستخدمين المسجلين"
            )}
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="space-y-2">
              <label className="text-sm font-medium">
                {t("Title", "العنوان")}
              </label>
              <input
                type="text"
                name="title"
                className="w-full px-3 py-2 border rounded-md"
                placeholder={t("Enter notification title", "أدخل عنوان الإشعار")}
                required
              />
            </div>
            <div className="space-y-2">
              <label className="text-sm font-medium">
                {t("Message", "الرسالة")}
              </label>
              <textarea
                name="body"
                className="w-full px-3 py-2 border rounded-md"
                rows={4}
                placeholder={t("Enter notification message", "أدخل رسالة الإشعار")}
                required
              />
            </div>

            <Tabs value={urlType} onValueChange={(value) => setUrlType(value as "custom" | "system")}>
              <TabsList className="grid w-full grid-cols-2">
                <TabsTrigger value="custom">
                  {t("Custom URL", "رابط مخصص")}
                </TabsTrigger>
                <TabsTrigger value="system">
                  {t("System Pages", "صفحات النظام")}
                </TabsTrigger>
              </TabsList>

              <TabsContent value="custom">
                <div className="space-y-2">
                  <label className="text-sm font-medium">
                    {t("URL", "الرابط")}
                  </label>
                  <input
                    type="url"
                    name="url"
                    className="w-full px-3 py-2 border rounded-md"
                    placeholder={t("Enter URL for notification click", "أدخل الرابط عند النقر على الإشعار")}
                  />
                </div>
              </TabsContent>

              <TabsContent value="system" className="space-y-4">
                <Select
                  value={selectedMainPage}
                  onValueChange={(value) => {
                    setSelectedMainPage(value);
                    setSelectedSubPage("main_page_only");
                    setSelectedItemId(null);
                  }}
                >
                  <SelectTrigger>
                    <SelectValue placeholder={t("Select main page", "اختر الصفحة الرئيسية")} />
                  </SelectTrigger>
                  <SelectContent>
                    {systemPages.map((page) => (
                      <SelectItem key={page.value} value={page.value}>
                        {t(page.label, page.label)}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>

                {selectedMainPage && (
                  <Select
                    value={selectedSubPage}
                    onValueChange={(value) => {
                      setSelectedSubPage(value);
                      setSelectedItemId(null);
                    }}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder={t("Select sub-page (optional)", "اختر الصفحة الفرعية (اختياري)")} />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="main_page_only">
                        {t("Main page only", "الصفحة الرئيسية فقط")}
                      </SelectItem>
                      {systemPages
                        .find(page => page.value === selectedMainPage)
                        ?.subPages.map((subPage) => (
                          <SelectItem key={subPage.value} value={subPage.value}>
                            {t(subPage.label, subPage.label)}
                          </SelectItem>
                        ))}
                    </SelectContent>
                  </Select>
                )}

                {shouldShowSpecificItems() && (
                  <Select
                    value={selectedItemId || ""}
                    onValueChange={setSelectedItemId}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder={t("Select specific item", "اختر عنصراً محدداً")} />
                    </SelectTrigger>
                    <SelectContent>
                      {renderSpecificItems()}
                    </SelectContent>
                  </Select>
                )}
              </TabsContent>
            </Tabs>

            <Button 
              type="submit" 
              disabled={isLoading || !isConnected || (urlType === "system" && !selectedMainPage)} 
              className="w-full"
            >
              {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              {t("Send Notification", "إرسال الإشعار")}
            </Button>

            {!isConnected && (
              <p className="text-sm text-destructive text-center">
                {t(
                  "Cannot send notifications while disconnected from service",
                  "لا يمكن إرسال الإشعارات أثناء عدم الاتصال بالخدمة"
                )}
              </p>
            )}
          </form>
        </CardContent>
      </Card>
    </div>
  );
}