import { useQuery, useMutation } from "@tanstack/react-query";
import { Speaker, insertSpeakerSchema } 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 { 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, Edit, Trash2 } from "lucide-react";
import { useState } from "react";
import { Textarea } from "@/components/ui/textarea";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";

export default function SpeakersPage() {
  const { toast } = useToast();
  const [isAdding, setIsAdding] = useState(false);
  const [editingSpeaker, setEditingSpeaker] = useState<Speaker | null>(null);
  const [speakerToDelete, setSpeakerToDelete] = useState<Speaker | null>(null);

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

  const form = useForm({
    resolver: zodResolver(insertSpeakerSchema),
    defaultValues: {
      name: "",
      nameAr: "",
      title: "",
      titleAr: "",
      bio: "",
      bioAr: "",
      imageUrl: "",
      organization: "",
      organizationAr: "",
      position: "",
      positionAr: "",
    },
  });

  // Reset form when switching between add/edit modes
  const resetForm = (speaker?: Speaker) => {
    if (speaker) {
      form.reset({
        name: speaker.name,
        nameAr: speaker.nameAr,
        title: speaker.title,
        titleAr: speaker.titleAr,
        bio: speaker.bio,
        bioAr: speaker.bioAr,
        imageUrl: speaker.imageUrl,
        organization: speaker.organization || "",
        organizationAr: speaker.organizationAr || "",
        position: speaker.position || "",
        positionAr: speaker.positionAr || "",
      });
    } else {
      form.reset({
        name: "",
        nameAr: "",
        title: "",
        titleAr: "",
        bio: "",
        bioAr: "",
        imageUrl: "",
        organization: "",
        organizationAr: "",
        position: "",
        positionAr: "",
      });
    }
  };

  const createSpeakerMutation = useMutation({
    mutationFn: async (data: any) => {
      const res = await apiRequest("POST", "/api/speakers", data);
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/speakers"] });
      toast({
        title: "Speaker added",
        description: "The speaker has been added successfully.",
      });
      setIsAdding(false);
      form.reset();
    },
    onError: (error: Error) => {
      toast({
        title: "Error",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const updateSpeakerMutation = useMutation({
    mutationFn: async (data: any) => {
      if (!editingSpeaker?.id) throw new Error("No speaker ID provided");
      const res = await apiRequest("PATCH", `/api/speakers/${editingSpeaker.id}`, data);
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/speakers"] });
      toast({
        title: "Speaker updated",
        description: "The speaker has been updated successfully.",
      });
      setEditingSpeaker(null);
      form.reset();
    },
    onError: (error: Error) => {
      toast({
        title: "Error",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const deleteSpeakerMutation = useMutation({
    mutationFn: async (speakerId: number) => {
      await apiRequest("DELETE", `/api/speakers/${speakerId}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/speakers"] });
      toast({
        title: "Speaker deleted",
        description: "The speaker has been deleted successfully.",
      });
      setSpeakerToDelete(null);
    },
    onError: (error: Error) => {
      toast({
        title: "Error",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  if (isLoading) {
    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">Speakers Management</h1>
        <Button onClick={() => {
          setIsAdding(true);
          setEditingSpeaker(null);
          resetForm();
        }} disabled={isAdding || editingSpeaker !== null}>
          <Plus className="h-4 w-4 mr-2" />
          Add Speaker
        </Button>
      </div>

      {(isAdding || editingSpeaker) && (
        <Card>
          <CardHeader>
            <CardTitle>{editingSpeaker ? "Edit Speaker" : "Add New Speaker"}</CardTitle>
          </CardHeader>
          <CardContent>
            <Form {...form}>
              <form
                onSubmit={form.handleSubmit((data) =>
                  editingSpeaker
                    ? updateSpeakerMutation.mutate(data)
                    : createSpeakerMutation.mutate(data)
                )}
                className="space-y-4"
              >
                <div className="grid md:grid-cols-2 gap-4">
                  <FormField
                    control={form.control}
                    name="name"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Name (English)</FormLabel>
                        <FormControl>
                          <Input {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="nameAr"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Name (Arabic)</FormLabel>
                        <FormControl>
                          <Input {...field} dir="rtl" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="title"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Title (English)</FormLabel>
                        <FormControl>
                          <Input {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="titleAr"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Title (Arabic)</FormLabel>
                        <FormControl>
                          <Input {...field} dir="rtl" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="organization"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Organization (English)</FormLabel>
                        <FormControl>
                          <Input {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="organizationAr"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Organization (Arabic)</FormLabel>
                        <FormControl>
                          <Input {...field} dir="rtl" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="position"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Position (English)</FormLabel>
                        <FormControl>
                          <Input {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="positionAr"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Position (Arabic)</FormLabel>
                        <FormControl>
                          <Input {...field} dir="rtl" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="bio"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Bio (English)</FormLabel>
                        <FormControl>
                          <Textarea {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="bioAr"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Bio (Arabic)</FormLabel>
                        <FormControl>
                          <Textarea {...field} dir="rtl" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="imageUrl"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Profile Image</FormLabel>
                        <FormControl>
                          <div className="flex items-center space-x-2">
                            <Input
                              type="file"
                              accept="image/*"
                              onChange={async (e) => {
                                try {
                                  const file = e.target.files?.[0];
                                  if (file) {
                                    const formData = new FormData();
                                    formData.append("file", file);

                                    const res = await fetch("/api/upload", {
                                      method: "POST",
                                      body: formData,
                                    });

                                    if (!res.ok) {
                                      throw new Error(`Upload failed: ${res.status}`);
                                    }

                                    const { url } = await res.json();
                                    field.onChange(url);
                                    form.setValue("imageUrl", url, {
                                      shouldDirty: true,
                                      shouldValidate: true,
                                      shouldTouch: true
                                    });

                                    toast({
                                      title: "Upload successful",
                                      description: "Speaker profile image has been uploaded. Click Update Speaker to save changes.",
                                    });
                                  }
                                } catch (error) {
                                  console.error("Upload error:", error);
                                  toast({
                                    title: "Upload failed",
                                    description: error instanceof Error ? error.message : "Failed to upload image",
                                    variant: "destructive",
                                  });
                                }
                              }}
                            />
                            {field.value && (
                              <img
                                src={field.value}
                                alt="Profile preview"
                                className="w-10 h-10 rounded-full object-cover"
                              />
                            )}
                          </div>
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <div className="flex justify-end gap-4">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => {
                      setIsAdding(false);
                      setEditingSpeaker(null);
                      form.reset();
                    }}
                  >
                    Cancel
                  </Button>
                  <Button
                    type="submit"
                    disabled={createSpeakerMutation.isPending || updateSpeakerMutation.isPending}
                  >
                    {(createSpeakerMutation.isPending || updateSpeakerMutation.isPending) && (
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    )}
                    {editingSpeaker ? "Update Speaker" : "Add Speaker"}
                  </Button>
                </div>
              </form>
            </Form>
          </CardContent>
        </Card>
      )}

      <div className="grid md:grid-cols-3 gap-4">
        {speakers?.map((speaker) => (
          <Card key={speaker.id}>
            <CardContent className="pt-6">
              <div className="flex flex-col items-center text-center">
                <Avatar className="h-24 w-24 mb-4">
                  <AvatarImage src={speaker.imageUrl} alt={speaker.name} />
                  <AvatarFallback>{speaker.name[0]}</AvatarFallback>
                </Avatar>
                <h3 className="font-semibold mb-1">{speaker.name}</h3>
                <p className="text-sm mb-2" dir="rtl">
                  {speaker.nameAr}
                </p>
                <p className="text-sm text-muted-foreground">{speaker.title}</p>
                <p className="text-sm text-muted-foreground mb-2" dir="rtl">
                  {speaker.titleAr}
                </p>
                {speaker.organization && (
                  <>
                    <p className="text-sm">{speaker.organization}</p>
                    <p className="text-sm mb-2" dir="rtl">{speaker.organizationAr}</p>
                  </>
                )}
                {speaker.position && (
                  <>
                    <p className="text-sm">{speaker.position}</p>
                    <p className="text-sm mb-2" dir="rtl">{speaker.positionAr}</p>
                  </>
                )}
                <div className="text-sm">
                  <p className="mb-2">{speaker.bio}</p>
                  <p dir="rtl">{speaker.bioAr}</p>
                </div>
                <div className="flex gap-2 mt-4">
                  <Button
                    variant="ghost"
                    size="icon"
                    onClick={() => {
                      setEditingSpeaker(speaker);
                      setIsAdding(false);
                      resetForm(speaker);
                    }}
                  >
                    <Edit className="h-4 w-4" />
                  </Button>
                  <AlertDialog>
                    <AlertDialogTrigger asChild>
                      <Button
                        variant="ghost"
                        size="icon"
                        className="text-destructive"
                        onClick={() => setSpeakerToDelete(speaker)}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </AlertDialogTrigger>
                    <AlertDialogContent>
                      <AlertDialogHeader>
                        <AlertDialogTitle>Delete Speaker</AlertDialogTitle>
                        <AlertDialogDescription>
                          Are you sure you want to delete this speaker? This action cannot be undone.
                        </AlertDialogDescription>
                      </AlertDialogHeader>
                      <AlertDialogFooter>
                        <AlertDialogCancel onClick={() => setSpeakerToDelete(null)}>
                          Cancel
                        </AlertDialogCancel>
                        <AlertDialogAction
                          onClick={() => speaker.id && deleteSpeakerMutation.mutate(speaker.id)}
                          className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                        >
                          {deleteSpeakerMutation.isPending ? (
                            <Loader2 className="h-4 w-4 animate-spin" />
                          ) : (
                            "Delete"
                          )}
                        </AlertDialogAction>
                      </AlertDialogFooter>
                    </AlertDialogContent>
                  </AlertDialog>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
}