import { useState } from "react";
import { useLanguage } from "@/hooks/use-language";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { useQuery, useMutation } from "@tanstack/react-query";
import { useAuth } from "@/hooks/use-auth";
import { Plus, ChartBar, Edit, Trash, Send, Bell, Radio } from "lucide-react";
import type {
  Poll,
  Event,
  Session,
  PollType,
  PollQuestion,
} from "@shared/schema";
import {
  Form,
  FormField,
  FormItem,
  FormLabel,
  FormControl,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { useForm } from "react-hook-form";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { format } from "date-fns";
import { useLocation } from "wouter";

export default function PollsPage() {
  const { t } = useLanguage();
  const { user } = useAuth();
  const { toast } = useToast();
  const [, setLocation] = useLocation();
  const [filterEventId, setFilterEventId] = useState<number | null>(null);
  const [filterSessionId, setFilterSessionId] = useState<number | null>(null);
  const [selectedEventId, setSelectedEventId] = useState<number | null>(null);
  const [selectedSessionId, setSelectedSessionId] = useState<number | null>(
    null,
  );
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingPoll, setEditingPoll] = useState<Poll | null>(null);
  const [questions, setQuestions] = useState<PollQuestion[]>([]);

  const form = useForm({
    defaultValues: {
      title: "",
      titleAr: "",
      description: "",
      descriptionAr: "",
      startDate: "",
      startTime: "",
      endDate: "",
      endTime: "",
    },
  });

  const { data: events } = useQuery<Event[]>({
    queryKey: ["/api/events"],
    enabled: true,
  });

  const { data: sessions } = useQuery<Session[]>({
    queryKey: ["/api/sessions", filterEventId || selectedEventId],
    enabled: !!(filterEventId || selectedEventId),
  });

  const { data: polls } = useQuery<Poll[]>({
    queryKey: ["/api/polls", filterEventId, filterSessionId],
    queryFn: async () => {
      const url = new URL("/api/polls", window.location.origin);
      if (filterEventId)
        url.searchParams.append("eventId", filterEventId.toString());
      if (filterSessionId)
        url.searchParams.append("sessionId", filterSessionId.toString());
      const response = await fetch(url);
      if (!response.ok) throw new Error("Failed to fetch polls");
      return response.json();
    },
  });

  const { data: pollTypes } = useQuery<PollType[]>({
    queryKey: ["/api/poll-types"],
  });

  const updatePollMutation = useMutation({
    mutationFn: async (data: any) => {
      if (!editingPoll) throw new Error("No poll selected for editing");

      const startDateTime = new Date(
        `${data.startDate}T${data.startTime || "00:00"}`,
      );
      const endDateTime = new Date(
        `${data.endDate}T${data.endTime || "00:00"}`,
      );

      if (isNaN(startDateTime.getTime()) || isNaN(endDateTime.getTime())) {
        throw new Error("Invalid dates provided");
      }

      const pollData = {
        title: data.title,
        titleAr: data.titleAr,
        description: data.description,
        descriptionAr: data.descriptionAr,
        eventId: selectedEventId,
        sessionId: selectedSessionId,
        startDate: startDateTime,
        endDate: endDateTime,
        questions: questions,
      };

      const response = await apiRequest(
        "PATCH",
        `/api/polls/${editingPoll.id}`,
        pollData,
      );
      if (!response.ok) {
        throw new Error("Failed to update poll");
      }
      return response.json();
    },
    onSuccess: () => {
      setIsDialogOpen(false);
      setEditingPoll(null);
      form.reset();
      setQuestions([]);
      queryClient.invalidateQueries({ queryKey: ["/api/polls"] });
      toast({
        title: t("Success", "نجاح"),
        description: t("Poll updated successfully", "تم تحديث الاستطلاع بنجاح"),
      });
    },
    onError: (error: Error) => {
      toast({
        title: t("Error", "خطأ"),
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const createPollMutation = useMutation({
    mutationFn: async (formData: any) => {
      if (!selectedEventId) {
        throw new Error("Please select an event");
      }

      const startDateTime = new Date(
        `${formData.startDate}T${formData.startTime || "00:00"}`,
      );
      const endDateTime = new Date(
        `${formData.endDate}T${formData.endTime || "00:00"}`,
      );

      if (isNaN(startDateTime.getTime()) || isNaN(endDateTime.getTime())) {
        throw new Error("Invalid date/time format");
      }

      const pollData = {
        title: formData.title,
        titleAr: formData.titleAr,
        description: formData.description,
        descriptionAr: formData.descriptionAr,
        eventId: selectedEventId,
        sessionId: selectedSessionId,
        creatorId: user?.id,
        startDate: startDateTime.toISOString(),
        endDate: endDateTime.toISOString(),
        isActive: true,
        resultsPublished: false,
        questions: questions,
      };

      const response = await apiRequest("POST", "/api/polls", pollData);
      if (!response.ok) {
        throw new Error("Failed to create poll");
      }
      return response.json();
    },
    onSuccess: () => {
      setIsDialogOpen(false);
      form.reset();
      setQuestions([]);
      queryClient.invalidateQueries({ queryKey: ["/api/polls"] });
      toast({
        title: t("Success", "نجاح"),
        description: t("Poll created successfully", "تم إنشاء الاستطلاع بنجاح"),
      });
    },
    onError: (error: Error) => {
      toast({
        title: t("Error", "خطأ"),
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const sendNotificationMutation = useMutation({
    mutationFn: async (poll: Poll) => {
      const response = await apiRequest("POST", `/api/notifications/send`, {
        type: "poll",
        pollId: poll.id,
        title: poll.title,
        body: "You can submit your poll now.",
        message: "You can submit your Poll.",
        url: `/polls/${poll.id}/submit`
      });
      if (!response.ok) {
        throw new Error("Failed to send notification");
      }
      return response.json();
    },
    onSuccess: () => {
      toast({
        title: t("Success", "نجاح"),
        description: t(
          "Notification sent successfully",
          "تم إرسال الإشعار بنجاح"
        ),
      });
    },
    onError: (error: Error) => {
      toast({
        title: t("Error", "خطأ"),
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const announceResultsMutation = useMutation({
    mutationFn: async (poll: Poll) => {
      // First update poll to mark results as published
      const updateResponse = await apiRequest("PATCH", `/api/polls/${poll.id}`, {
        resultsPublished: true
      });

      if (!updateResponse.ok) {
        throw new Error("Failed to publish results");
      }

      // Then send notification about results
      const notifyResponse = await apiRequest("POST", `/api/notifications/send`, {
        type: "poll-results",
        pollId: poll.id,
        title: poll.title,
        body: "Poll results are now available!",
        message: "Poll results are now available.",
        url: `/polls/${poll.id}/results`  // Explicitly set to results page URL
      });

      if (!notifyResponse.ok) {
        throw new Error("Failed to send notification");
      }

      return notifyResponse.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/polls"] });
      toast({
        title: t("Success", "نجاح"),
        description: t(
          "Results published and notification sent",
          "تم نشر النتائج وإرسال الإشعار"
        ),
      });
    },
    onError: (error: Error) => {
      toast({
        title: t("Error", "خطأ"),
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const deletePollMutation = useMutation({
    mutationFn: async (pollId: number) => {
      const response = await apiRequest("DELETE", `/api/polls/${pollId}`);
      if (!response.ok) {
        throw new Error("Failed to delete poll");
      }
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/polls"] });
      toast({
        title: t("Success", "نجاح"),
        description: t(
          "Poll deleted successfully",
          "تم حذف الاستطلاع بنجاح"
        ),
      });
    },
    onError: (error: Error) => {
      toast({
        title: t("Error", "خطأ"),
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const onSubmit = (data: any) => {
    if (editingPoll) {
      updatePollMutation.mutate(data);
    } else {
      createPollMutation.mutate(data);
    }
  };

  const handleEdit = async (poll: Poll) => {
    setEditingPoll(poll);
    setSelectedEventId(poll.eventId);
    setSelectedSessionId(poll.sessionId);

    try {
      const response = await fetch(`/api/polls/${poll.id}/questions`);
      if (response.ok) {
        const pollQuestions = await response.json();
        setQuestions(pollQuestions);
      } else {
        console.error(`Failed to fetch poll questions: ${response.status}`);
      }
    } catch (error) {
      console.error("Error fetching poll questions:", error);
    }

    const startDate = new Date(poll.startDate);
    const endDate = new Date(poll.endDate);

    form.reset({
      title: poll.title,
      titleAr: poll.titleAr,
      description: poll.description,
      descriptionAr: poll.descriptionAr,
      startDate: format(startDate, "yyyy-MM-dd"),
      startTime: format(startDate, "HH:mm"),
      endDate: format(endDate, "yyyy-MM-dd"),
      endTime: format(endDate, "HH:mm"),
    });

    setIsDialogOpen(true);
  };

  const addQuestion = () => {
    setQuestions([
      ...questions,
      {
        id: questions.length + 1,
        pollId: 0,
        pollTypeId: 1,
        question: "",
        questionAr: "",
        options: [],
        optionsAr: [],
        required: true,
        order: questions.length + 1,
      },
    ]);
  };

  const updateQuestion = (index: number, updates: Partial<PollQuestion>) => {
    const newQuestions = [...questions];
    newQuestions[index] = { ...newQuestions[index], ...updates };
    setQuestions(newQuestions);
  };

  const removeQuestion = (index: number) => {
    setQuestions(questions.filter((_, i) => i !== index));
  };

  const renderQuestionInput = (index: number, currentQuestion:PollQuestion) => {
    if (!currentQuestion) return null;

    const shouldShowOptions = currentQuestion.pollTypeId === 3 || currentQuestion.pollTypeId === 7;

    const addOption = () => {
      const options = [...(currentQuestion.options || [])];
      const optionsAr = [...(currentQuestion.optionsAr || [])];

      if (currentQuestion.pollTypeId === 7) {
        const filteredOptions = options.filter(opt => opt !== "Other");
        const filteredOptionsAr = optionsAr.filter(opt => opt !== "أخرى");

        filteredOptions.push("");
        filteredOptionsAr.push("");

        filteredOptions.push("Other");
        filteredOptionsAr.push("أخرى");

        updateQuestion(index, {
          options: filteredOptions,
          optionsAr: filteredOptionsAr,
        });
      } else {
        updateQuestion(index, {
          options: [...options, ""],
          optionsAr: [...optionsAr, ""],
        });
      }
    };

    const removeOption = (optionIndex: number) => {
      const options = [...(currentQuestion.options || [])];
      const optionsAr = [...(currentQuestion.optionsAr || [])];
      options.splice(optionIndex, 1);
      optionsAr.splice(optionIndex, 1);
      updateQuestion(index, { options, optionsAr });
    };

    const updateOption = (optionIndex: number, value: string, isArabic: boolean) => {
      const options = [...(currentQuestion.options || [])];
      const optionsAr = [...(currentQuestion.optionsAr || [])];

      if (isArabic) {
        optionsAr[optionIndex] = value;
      } else {
        options[optionIndex] = value;
      }

      if (currentQuestion.pollTypeId === 7) {
        const filteredOptions = options.filter(opt => opt !== "Other");
        const filteredOptionsAr = optionsAr.filter(opt => opt !== "أخرى");

        filteredOptions.push("Other");
        filteredOptionsAr.push("أخرى");

        updateQuestion(index, { 
          options: filteredOptions,
          optionsAr: filteredOptionsAr
        });
      } else {
        updateQuestion(index, { options, optionsAr });
      }
    };

    return (
      <div className="space-y-4">
        <div>
          <label className="text-sm font-medium mb-2 block">
            {t("Question Type", "نوع السؤال")}
          </label>
          <select
            className="w-full border rounded p-2"
            value={currentQuestion.pollTypeId}
            onChange={(e) =>
              updateQuestion(index, {
                pollTypeId: Number(e.target.value),
                options: [],
                optionsAr: [],
              })
            }
          >
            {pollTypes?.map((type) => (
              <option key={type.id} value={type.id}>
                {type.name}
              </option>
            ))}
          </select>
        </div>

        <Input
          placeholder={t("Question", "السؤال")}
          value={currentQuestion.question}
          onChange={(e) =>
            updateQuestion(index, { question: e.target.value })
          }
        />

        <Input
          placeholder={t("Question (Arabic)", "السؤال (عربي)")}
          value={currentQuestion.questionAr}
          onChange={(e) =>
            updateQuestion(index, {
              questionAr: e.target.value,
            })
          }
        />

        {shouldShowOptions && (
          <div className="space-y-4">
            <div className="flex justify-between items-center">
              <h4 className="text-sm font-medium">
                {t("Options", "الخيارات")}
              </h4>
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={addOption}
              >
                <Plus className="w-4 h-4 mr-2" />
                {t("Add Option", "إضافة خيار")}
              </Button>
            </div>

            {(currentQuestion.options || []).map((option, optionIndex) => {
              if (currentQuestion.pollTypeId === 7 && optionIndex === currentQuestion.options.length - 1) {
                return null;
              }

              return (
                <div key={optionIndex} className="grid grid-cols-[1fr,1fr,auto] gap-2 items-start">
                  <Input
                    placeholder={t("Option in English", "الخيار بالإنجليزية")}
                    value={option}
                    onChange={(e) => updateOption(optionIndex, e.target.value, false)}
                  />
                  <Input
                    placeholder={t("Option in Arabic", "الخيار بالعربية")}
                    value={currentQuestion.optionsAr?.[optionIndex] || ""}
                    onChange={(e) => updateOption(optionIndex, e.target.value, true)}
                  />
                  <Button
                    type="button"
                    variant="destructive"
                    size="icon"
                    onClick={() => removeOption(optionIndex)}
                  >
                    <Trash className="w-4 h-4" />
                  </Button>
                </div>
              );
            })}

            {currentQuestion.pollTypeId === 7 && (
              <div className="mt-2 p-2 bg-muted rounded-lg">
                <p className="text-sm text-muted-foreground">
                  {t(
                    '"Other" option will be automatically added as the last option',
                    'سيتم إضافة خيار "أخرى" تلقائياً كآخر خيار'
                  )}
                </p>
              </div>
            )}
          </div>
        )}
      </div>
    );
  };

  return (
    <div className="space-y-8">
      <div className="flex justify-between items-center">
        <h1 className="text-3xl font-bold">
          {t("Polls Management", "إدارة الاستطلاعات")}
        </h1>
        <Button
          onClick={() => {
            setEditingPoll(null);
            form.reset();
            setQuestions([]);
            setIsDialogOpen(true);
          }}
        >
          <Plus className="w-4 h-4 mr-2" />
          {t("Create Poll", "إنشاء استطلاع")}
        </Button>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="text-sm font-medium mb-2 block">
            {t("Filter by Event", "تصفية حسب الفعالية")}
          </label>
          <select
            className="w-full border rounded p-2"
            value={filterEventId || ""}
            onChange={(e) => {
              const value = e.target.value;
              setFilterEventId(value ? Number(value) : null);
              setFilterSessionId(null);
            }}
          >
            <option value="">{t("All Events", "جميع الفعاليات")}</option>
            {events?.map((event) => (
              <option key={event.id} value={event.id}>
                {event.eventName}
              </option>
            ))}
          </select>
        </div>
        <div>
          <label className="text-sm font-medium mb-2 block">
            {t("Filter by Session", "تصفية حسب الجلسة")}
          </label>
          <select
            className="w-full border rounded p-2"
            value={filterSessionId || ""}
            onChange={(e) => {
              const value = e.target.value;
              setFilterSessionId(value ? Number(value) : null);
            }}
            disabled={!filterEventId}
          >
            <option value="">{t("All Sessions", "جميع الجلسات")}</option>
            {sessions?.map((session) => (
              <option key={session.id} value={session.id}>
                {session.sessionTitle}
              </option>
            ))}
          </select>
        </div>
      </div>

      <div className="grid gap-4">
        {polls
          ?.sort(
            (a, b) =>
              new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
          )
          .map((poll) => (
            <Card key={poll.id}>
              <CardHeader>
                <div className="flex justify-between items-center">
                  <CardTitle>{poll.title}</CardTitle>
                  <div className="flex gap-2">
                    {!poll.resultsPublished && (
                      <>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setLocation(`/polls/${poll.id}/submit`)}
                        >
                          <Send className="w-4 h-4 mr-2" />
                          {t("Open Poll", "فتح الاستطلاع")}
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => sendNotificationMutation.mutate(poll)}
                        >
                          <Bell className="w-4 h-4 mr-2" />
                          {t("Send Notification", "إرسال إشعار")}
                        </Button>
                      </>
                    )}
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => {
                        setLocation(`/polls/${poll.id}/results`);
                      }}
                    >
                      <ChartBar className="w-4 h-4 mr-2" />
                      {t("View Results", "عرض النتائج")}
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleEdit(poll)}
                    >
                      <Edit className="w-4 h-4 mr-2" />
                      {t("Edit", "تعديل")}
                    </Button>
                    {!poll.resultsPublished && (
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => announceResultsMutation.mutate(poll)}
                      >
                        <Radio className="w-4 h-4 mr-2" />
                        {t("Announce Results", "إعلان النتائج")}
                      </Button>
                    )}
                    <Button
                      variant="destructive"
                      size="sm"
                      onClick={() => {
                        if (confirm(t("Are you sure you want to delete this poll?", "هل أنت متأكد من حذف هذا الاستطلاع؟"))) {
                          deletePollMutation.mutate(poll.id);
                        }
                      }}
                      disabled={deletePollMutation.isPending}
                    >
                      <Trash className="w-4 h-4 mr-2" />
                      {t("Delete", "حذف")}
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <p className="text-muted-foreground">{poll.description}</p>
                <div className="mt-4 text-sm text-muted-foreground">
                  <p>
                    {t("Start Date", "تاريخ البدء")}:{" "}
                    {format(new Date(poll.startDate), "PPp")}
                  </p>
                  <p>
                    {t("End Date", "تاريخ الانتهاء")}:{" "}
                    {format(new Date(poll.endDate), "PPp")}
                  </p>
                  {poll.sessionId &&
                    sessions?.find((s) => s.id === poll.sessionId) && (
                      <p className="mt-2">
                        {t("Session", "الجلسة")}:{" "}
                        {
                          sessions.find((s) => s.id === poll.sessionId)
                            ?.sessionTitle
                        }
                      </p>
                    )}
                </div>
              </CardContent>
            </Card>
          ))}
      </div>

      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="sm:max-w-[600px] max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {editingPoll
                ? t("Edit Poll", "تعديل الاستطلاع")
                : t("Create New Poll", "إنشاء استطلاع جديد")}
            </DialogTitle>
          </DialogHeader>
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-sm font-medium mb-2 block">
                    {t("Select Event", "اختر الفعالية")}
                  </label>
                  <select
                    className="w-full border rounded p-2"
                    value={selectedEventId || ""}
                    onChange={(e) => {
                      const value = e.target.value;
                      setSelectedEventId(value ? Number(value) : null);
                      setSelectedSessionId(null);
                    }}
                  >
                    <option value="">{t("Select...", "اختر...")}</option>
                    {events?.map((event) => (
                      <option key={event.id} value={event.id}>
                        {event.eventName}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="text-sm font-medium mb-2 block">
                    {t("Select Session", "اختر الجلسة")}
                  </label>
                  <select
                    className="w-full border rounded p-2"
                    value={selectedSessionId || ""}
                    onChange={(e) => {
                      const value = e.target.value;
                      setSelectedSessionId(value ? Number(value) : null);
                    }}
                    disabled={!selectedEventId}
                  >
                    <option value="">{t("Select...", "اختر...")}</option>
                    {sessions?.map((session) => (
                      <option key={session.id} value={session.id}>
                        {session.sessionTitle}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              <FormField
                control={form.control}
                name="title"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("Title", "العنوان")}</FormLabel>
                    <FormControl>
                      <Input {...field} />
                    </FormControl>
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="titleAr"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      {t("Title (Arabic)", "العنوان (عربي)")}
                    </FormLabel>
                    <FormControl>
                      <Input {...field} />
                    </FormControl>
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="description"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("Description", "الوصف")}</FormLabel>
                    <FormControl>
                      <Textarea {...field} />
                    </FormControl>
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="descriptionAr"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      {t("Description (Arabic)", "الوصف (عربي)")}
                    </FormLabel>
                    <FormControl>
                      <Textarea {...field} />
                    </FormControl>
                  </FormItem>
                )}
              />

              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="startDate"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t("Start Date", "تاريخ البدء")}</FormLabel>
                      <FormControl>
                        <Input type="date" {...field} />
                      </FormControl>
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="startTime"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t("Start Time", "وقت البدء")}</FormLabel>
                      <FormControl>
                        <Input type="time" {...field} />
                      </FormControl>
                    </FormItem>
                  )}
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="endDate"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t("End Date", "تاريخ الانتهاء")}</FormLabel>
                      <FormControl>
                        <Input type="date" {...field} />
                      </FormControl>
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="endTime"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t("End Time", "وقت الانتهاء")}</FormLabel>
                      <FormControl>
                        <Input type="time" {...field} />
                      </FormControl>
                    </FormItem>
                  )}
                />
              </div>

              <div className="space-y-4">
                <div className="flex justify-between items-center">
                  <h3 className="text-lg font-medium">
                    {t("Questions", "الأسئلة")}
                  </h3>
                  <Button type="button" onClick={addQuestion}>
                    <Plus className="w-4 h-4 mr-2" />
                    {t("Add Question", "إضافة سؤال")}
                  </Button>
                </div>

                {questions.map((question, index) => (
                  <Card key={index} className="p-4">
                    <div className="space-y-4">
                      <div className="flex justify-between">
                        <h4 className="font-medium">
                          {t("Question", "سؤال")} {index + 1}
                        </h4>
                        <Button
                          variant="destructive"
                          size="sm"
                          onClick={() => removeQuestion(index)}
                        >
                          <Trash className="w-4 h-4" />
                        </Button>
                      </div>
                      {renderQuestionInput(index, question)}
                    </div>
                  </Card>
                ))}
              </div>

              <Button type="submit" className="w-full">
                {editingPoll
                  ? t("Update Poll", "تحديث الاستطلاع")
                  : t("Create Poll", "إنشاء استطلاع")}
              </Button>
            </form>
          </Form>
        </DialogContent>
      </Dialog>
    </div>
  );
}