import { useQuery, useMutation } from "@tanstack/react-query";
import { Session, Event, Speaker, insertSessionSchema } from "@shared/schema";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
} from "@/components/ui/command";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useToast } from "@/hooks/use-toast";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { Loader2, Plus, Check, ChevronsUpDown, Edit, Trash2 } from "lucide-react";
import { useState } from "react";
import { Textarea } from "@/components/ui/textarea";
import { format } from "date-fns";
import { cn } from "@/lib/utils";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Badge } from "@/components/ui/badge";

export default function SessionsPage() {
  const { toast } = useToast();
  const [isAdding, setIsAdding] = useState(false);
  const [editingSession, setEditingSession] = useState<Session | null>(null);
  const [selectedSpeakers, setSelectedSpeakers] = useState<number[]>([]);
  const [sessionToDelete, setSessionToDelete] = useState<Session | null>(null);

  const { data: sessions, isLoading: loadingSessions } = useQuery<Session[]>({
    queryKey: ["/api/sessions"],
  });

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

  const { data: speakers } = useQuery<Speaker[]>({
    queryKey: ["/api/speakers"],
  });

  const form = useForm({
    resolver: zodResolver(insertSessionSchema),
    defaultValues: {
      eventId: 0,
      sessionTitle: "",
      sessionTitleAr: "",
      sessionDescription: "",
      sessionDescriptionAr: "",
      venue: "",
      venueAr: "",
      sessionDate: "",
      sessionTime: "",
      liveStreamUrl: "",
      speakerIds: [],
      sessionType: "main" as "main" | "breakout",
    },
  });

  // Reset form when switching between add/edit modes
  const resetForm = (session?: Session) => {
    if (session) {
      form.reset({
        eventId: session.eventId,
        sessionTitle: session.sessionTitle,
        sessionTitleAr: session.sessionTitleAr,
        sessionDescription: session.sessionDescription,
        sessionDescriptionAr: session.sessionDescriptionAr,
        venue: session.venue,
        venueAr: session.venueAr,
        sessionDate: session.sessionDate,
        sessionTime: session.sessionTime,
        liveStreamUrl: session.liveStreamUrl || "",
        sessionType: session.sessionType as "main" | "breakout",
      });
      setSelectedSpeakers(session.speakers?.map(s => s.id) || []);
    } else {
      form.reset();
      setSelectedSpeakers([]);
    }
  };

  const createSessionMutation = useMutation({
    mutationFn: async (data: any) => {
      const sessionData = {
        ...data,
        speakerIds: selectedSpeakers,
      };
      const res = await apiRequest("POST", "/api/sessions", sessionData);
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/sessions"] });
      toast({
        title: "Session created",
        description: "The session has been created successfully.",
      });
      setIsAdding(false);
      setSelectedSpeakers([]);
      form.reset();
    },
    onError: (error: Error) => {
      toast({
        title: "Error",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const updateSessionMutation = useMutation({
    mutationFn: async (data: any) => {
      const sessionData = {
        ...data,
        speakerIds: selectedSpeakers,
      };
      const res = await apiRequest("PATCH", `/api/sessions/${editingSession?.id}`, sessionData);
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/sessions"] });
      toast({
        title: "Session updated",
        description: "The session has been updated successfully.",
      });
      setEditingSession(null);
      setSelectedSpeakers([]);
      form.reset();
    },
    onError: (error: Error) => {
      toast({
        title: "Error",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const deleteSessionMutation = useMutation({
    mutationFn: async (sessionId: number) => {
      await apiRequest("DELETE", `/api/sessions/${sessionId}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/sessions"] });
      toast({
        title: "Session deleted",
        description: "The session has been deleted successfully.",
      });
      setSessionToDelete(null);
    },
    onError: (error: Error) => {
      toast({
        title: "Error",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  if (loadingSessions) {
    return (
      <div className="flex justify-center">
        <Loader2 className="h-8 w-8 animate-spin" />
      </div>
    );
  }

  return (
    <div className="space-y-8">
      <div className="flex justify-between items-center">
        <h1 className="text-3xl font-bold">Sessions Management</h1>
        <Button 
          onClick={() => {
            setIsAdding(true);
            setEditingSession(null);
            resetForm();
          }} 
          disabled={isAdding || editingSession !== null}
        >
          <Plus className="h-4 w-4 mr-2" />
          Add Session
        </Button>
      </div>

      {(isAdding || editingSession) && (
        <Card>
          <CardHeader>
            <CardTitle>{editingSession ? "Edit Session" : "Add New Session"}</CardTitle>
          </CardHeader>
          <CardContent>
            <Form {...form}>
              <form
                onSubmit={form.handleSubmit((data) =>
                  editingSession 
                    ? updateSessionMutation.mutate(data)
                    : createSessionMutation.mutate(data)
                )}
                className="space-y-4"
              >
                <div className="grid md:grid-cols-2 gap-4">
                  <FormField
                    control={form.control}
                    name="eventId"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Event</FormLabel>
                        <Select
                          onValueChange={(value) => field.onChange(Number(value))}
                          defaultValue={field.value.toString()}
                        >
                          <FormControl>
                            <SelectTrigger>
                              <SelectValue placeholder="Select an event" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            {events?.map((event) => (
                              <SelectItem
                                key={event.id}
                                value={event.id.toString()}
                              >
                                {event.eventName}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  {/* Session Type Selection */}
                  <FormField
                    control={form.control}
                    name="sessionType"
                    render={({ field }) => (
                      <FormItem className="space-y-3">
                        <FormLabel>Session Type</FormLabel>
                        <FormControl>
                          <RadioGroup
                            onValueChange={field.onChange}
                            defaultValue={field.value}
                            className="flex space-x-4"
                          >
                            <FormItem className="flex items-center space-x-3 space-y-0">
                              <FormControl>
                                <RadioGroupItem value="main" />
                              </FormControl>
                              <FormLabel className="font-normal">
                                Main Session
                              </FormLabel>
                            </FormItem>
                            <FormItem className="flex items-center space-x-3 space-y-0">
                              <FormControl>
                                <RadioGroupItem value="breakout" />
                              </FormControl>
                              <FormLabel className="font-normal">
                                Breakout Session
                              </FormLabel>
                            </FormItem>
                          </RadioGroup>
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  {/* Rest of the form fields remain unchanged */}
                  <FormField
                    control={form.control}
                    name="sessionTitle"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Session Title (English)</FormLabel>
                        <FormControl>
                          <Input {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="sessionTitleAr"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Session Title (Arabic)</FormLabel>
                        <FormControl>
                          <Input {...field} dir="rtl" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="sessionDescription"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Description (English)</FormLabel>
                        <FormControl>
                          <Textarea {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="sessionDescriptionAr"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Description (Arabic)</FormLabel>
                        <FormControl>
                          <Textarea {...field} dir="rtl" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="venue"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Venue (English)</FormLabel>
                        <FormControl>
                          <Input {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="venueAr"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Venue (Arabic)</FormLabel>
                        <FormControl>
                          <Input {...field} dir="rtl" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="sessionDate"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Date</FormLabel>
                        <FormControl>
                          <Input type="date" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="sessionTime"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Time</FormLabel>
                        <FormControl>
                          <Input type="time" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="liveStreamUrl"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Live Stream URL (Optional)</FormLabel>
                        <FormControl>
                          <Input type="url" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                {/* Speakers Multi-select */}
                <FormItem>
                  <FormLabel>Speakers</FormLabel>
                  <Popover>
                    <PopoverTrigger asChild>
                      <FormControl>
                        <Button
                          variant="outline"
                          role="combobox"
                          className={cn(
                            "w-full justify-between",
                            !selectedSpeakers.length && "text-muted-foreground"
                          )}
                        >
                          {selectedSpeakers.length > 0
                            ? `${selectedSpeakers.length} speaker(s) selected`
                            : "Select speakers"}
                          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                        </Button>
                      </FormControl>
                    </PopoverTrigger>
                    <PopoverContent className="w-full p-0">
                      <Command>
                        <CommandInput placeholder="Search speakers..." />
                        <CommandEmpty>No speakers found.</CommandEmpty>
                        <CommandGroup>
                          {speakers?.map((speaker) => (
                            <CommandItem
                              key={speaker.id}
                              value={speaker.name}
                              onSelect={() => {
                                if (selectedSpeakers.includes(speaker.id)) {
                                  setSelectedSpeakers(selectedSpeakers.filter(id => id !== speaker.id));
                                } else {
                                  setSelectedSpeakers([...selectedSpeakers, speaker.id]);
                                }
                              }}
                            >
                              <Check
                                className={cn(
                                  "mr-2 h-4 w-4",
                                  selectedSpeakers.includes(speaker.id)
                                    ? "opacity-100"
                                    : "opacity-0"
                                )}
                              />
                              {speaker.name}
                            </CommandItem>
                          ))}
                        </CommandGroup>
                      </Command>
                    </PopoverContent>
                  </Popover>
                </FormItem>

                <div className="flex justify-end gap-4">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => {
                      setIsAdding(false);
                      setEditingSession(null);
                      setSelectedSpeakers([]);
                      form.reset();
                    }}
                  >
                    Cancel
                  </Button>
                  <Button
                    type="submit"
                    disabled={createSessionMutation.isPending || updateSessionMutation.isPending}
                  >
                    {(createSessionMutation.isPending || updateSessionMutation.isPending) && (
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    )}
                    {editingSession ? "Update Session" : "Create Session"}
                  </Button>
                </div>
              </form>
            </Form>
          </CardContent>
        </Card>
      )}

      <div className="grid md:grid-cols-2 gap-4">
        {sessions?.map((session) => (
          <Card key={session.id}>
            <CardContent className="pt-6">
              <div className="flex justify-between items-start mb-4">
                <div>
                  <div className="flex items-center gap-2 mb-1">
                    <h3 className="font-semibold">{session.sessionTitle}</h3>
                    <Badge variant={session.sessionType === "main" ? "default" : "secondary"}>
                      {session.sessionType === "main" ? "Main Session" : "Breakout Session"}
                    </Badge>
                  </div>
                  <p className="text-sm text-muted-foreground mb-2" dir="rtl">
                    {session.sessionTitleAr}
                  </p>
                  <p className="text-sm mb-2">{session.venue}</p>
                  <p className="text-sm text-muted-foreground" dir="rtl">
                    {session.venueAr}
                  </p>
                </div>
                <div className="flex gap-2">
                  <Button
                    variant="ghost"
                    size="icon"
                    onClick={() => {
                      setEditingSession(session);
                      setIsAdding(false);
                      resetForm(session);
                    }}
                  >
                    <Edit className="h-4 w-4" />
                  </Button>
                  <AlertDialog>
                    <AlertDialogTrigger asChild>
                      <Button
                        variant="ghost"
                        size="icon"
                        className="text-destructive"
                        onClick={() => setSessionToDelete(session)}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </AlertDialogTrigger>
                    <AlertDialogContent>
                      <AlertDialogHeader>
                        <AlertDialogTitle>Delete Session</AlertDialogTitle>
                        <AlertDialogDescription>
                          Are you sure you want to delete this session? This action cannot be undone.
                        </AlertDialogDescription>
                      </AlertDialogHeader>
                      <AlertDialogFooter>
                        <AlertDialogCancel onClick={() => setSessionToDelete(null)}>
                          Cancel
                        </AlertDialogCancel>
                        <AlertDialogAction
                          onClick={() => session.id && deleteSessionMutation.mutate(session.id)}
                          className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                        >
                          {deleteSessionMutation.isPending ? (
                            <Loader2 className="h-4 w-4 animate-spin" />
                          ) : (
                            "Delete"
                          )}
                        </AlertDialogAction>
                      </AlertDialogFooter>
                    </AlertDialogContent>
                  </AlertDialog>
                </div>
              </div>
              <div className="mt-4">
                <p className="text-sm">
                  {format(new Date(session.sessionDate), "PPP")} at{" "}
                  {session.sessionTime}
                </p>
                {session.speakers && session.speakers.length > 0 && (
                  <div className="mt-4 border-t pt-4">
                    <p className="text-sm font-medium mb-2">Speakers:</p>
                    <div className="flex flex-wrap gap-2">
                      {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={speaker.name}
                              className="w-full h-full object-cover"
                            />
                          </div>
                          <span className="text-sm">{speaker.name}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
                {session.liveStreamUrl && (
                  <a
                    href={session.liveStreamUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-sm text-primary hover:underline block mt-2"
                  >
                    Join Live Stream
                  </a>
                )}
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
}