import { useParams } from "wouter";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useToast } from "@/hooks/use-toast";
import { Loader2 } from "lucide-react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { apiRequest } from "@/lib/queryClient";
import { useEffect } from "react";
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";

const activateAccountSchema = z.object({
  password: z.string().min(8, "Password must be at least 8 characters"),
  confirmPassword: z.string(),
  name: z.string().min(1, "Name is required"),
  email: z.string().email("Invalid email format"),
  organization: z.string().optional(),
  position: z.string().optional(),
  phoneNumber: z.string().optional(),
  profileImage: z.string().optional(),
}).refine((data) => data.password === data.confirmPassword, {
  message: "Passwords do not match",
  path: ["confirmPassword"],
});

type FormValues = z.infer<typeof activateAccountSchema>;

export default function ActivateAccountPage() {
  const { token } = useParams();
  const { toast } = useToast();

  const form = useForm<FormValues>({
    resolver: zodResolver(activateAccountSchema),
    defaultValues: {
      password: "",
      confirmPassword: "",
      name: "",
      email: "",
      organization: "",
      position: "",
      phoneNumber: "",
      profileImage: "",
    },
  });

  // Fetch current user data
  const { data: userData, isLoading: isLoadingUser, error: userError } = useQuery({
    queryKey: ['/api/users/current', token],
    queryFn: async () => {
      console.log("Fetching user data for token:", token);
      const res = await apiRequest("GET", `/api/users/current/${token}`);
      if (!res.ok) {
        const error = await res.json();
        throw new Error(error.message || 'Failed to fetch user data');
      }
      const data = await res.json();
      console.log("Received user data:", data);

      // Check if user is already activated
      if (data.isActive) {
        throw new Error("This account has already been activated. Please log in.");
      }

      return data;
    },
    retry: false
  });

  // Handle user data error
  useEffect(() => {
    if (userError) {
      toast({
        title: "Error",
        description: userError instanceof Error ? userError.message : "Invalid or expired activation link",
        variant: "destructive",
      });
      // Redirect to auth page after a short delay
      setTimeout(() => {
        window.location.href = "/auth";
      }, 3000);
    }
  }, [userError, toast]);

  // Update form when userData loads
  useEffect(() => {
    if (userData) {
      console.log("Setting form values with user data:", userData);
      form.reset({
        password: "",
        confirmPassword: "",
        name: userData.name || "",
        email: userData.email || "",
        organization: userData.organization || "",
        position: userData.position || "",
        phoneNumber: userData.phoneNumber || "",
        profileImage: userData.profileImage || "",
      });
    }
  }, [userData, form]);

  const activateAccountMutation = useMutation({
    mutationFn: async (data: FormValues) => {
      console.log("Submitting activation form with data:", {
        ...data,
        password: "[REDACTED]",
        confirmPassword: "[REDACTED]"
      });
      const res = await apiRequest("POST", `/api/activate-account/${token}`, data);
      if (!res.ok) {
        const error = await res.json();
        throw new Error(error.message || 'Failed to activate account');
      }
      return res.json();
    },
    onSuccess: () => {
      toast({
        title: "Account Activated",
        description: "Your account has been activated successfully. Please login.",
      });
      // Add a small delay before redirect to ensure the toast is visible
      setTimeout(() => {
        window.location.href = "/auth";
      }, 2000);
    },
    onError: (error: Error) => {
      console.error("Activation error:", error);
      toast({
        title: "Error",
        description: error.message || "Failed to activate account. Please try again or request a new activation link.",
        variant: "destructive",
      });
      if (error.message?.includes("already activated")) {
        setTimeout(() => {
          window.location.href = "/auth";
        }, 2000);
      }
    },
  });

  const onSubmit = (data: FormValues) => {
    console.log("Form submission:", {
      ...data,
      password: "[REDACTED]",
      confirmPassword: "[REDACTED]"
    });
    activateAccountMutation.mutate(data);
  };

  if (isLoadingUser) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Loader2 className="h-8 w-8 animate-spin text-border" />
      </div>
    );
  }

  // Don't render the form if there's a user error
  if (userError) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Card className="w-full max-w-md">
          <CardHeader>
            <CardTitle className="text-center text-red-500">Activation Error</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-center">
              {userError instanceof Error ? userError.message : "Invalid or expired activation link"}
            </p>
            <p className="text-center mt-4">
              Redirecting to login page...
            </p>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="container mx-auto max-w-md py-8">
      <Card>
        <CardHeader>
          <CardTitle>Complete Your Profile</CardTitle>
        </CardHeader>
        <CardContent>
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
              <div className="flex justify-center mb-6">
                <Avatar className="h-24 w-24">
                  <AvatarImage src={form.getValues("profileImage")} />
                  <AvatarFallback>{userData?.name?.charAt(0)?.toUpperCase()}</AvatarFallback>
                </Avatar>
              </div>

              <FormField
                control={form.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Full Name</FormLabel>
                    <FormControl>
                      <Input {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="email"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Email</FormLabel>
                    <FormControl>
                      <Input {...field} type="email" />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="organization"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Organization</FormLabel>
                    <FormControl>
                      <Input {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="position"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Position</FormLabel>
                    <FormControl>
                      <Input {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="phoneNumber"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Phone Number</FormLabel>
                    <FormControl>
                      <Input {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="password"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Password</FormLabel>
                    <FormControl>
                      <Input type="password" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="confirmPassword"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Confirm Password</FormLabel>
                    <FormControl>
                      <Input type="password" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="profileImage"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Profile Image</FormLabel>
                    <FormControl>
                      <Input
                        type="file"
                        accept="image/*"
                        onChange={async (e) => {
                          const file = e.target.files?.[0];
                          if (file) {
                            const formData = new FormData();
                            formData.append("file", file);

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

                              if (!res.ok) {
                                throw new Error("Failed to upload image");
                              }

                              const { url } = await res.json();
                              form.setValue("profileImage", url, {
                                shouldDirty: true,
                                shouldValidate: true,
                              });
                            } catch (error) {
                              console.error("Error uploading image:", error);
                              toast({
                                title: "Error",
                                description: "Failed to upload image",
                                variant: "destructive",
                              });
                            }
                          }
                        }}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <Button
                type="submit"
                className="w-full"
                disabled={activateAccountMutation.isPending}
              >
                {activateAccountMutation.isPending ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                  "Activate Account"
                )}
              </Button>
            </form>
          </Form>
        </CardContent>
      </Card>
    </div>
  );
}