
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/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 { Link, useNavigate } from "react-router-dom";
import { useAuth } from "../contexts/AuthContext";
import { useState, useEffect, useCallback } from "react";
import { toast } from "sonner";
import type { Profile } from "@/hooks/useUserProfile";

const loginSchema = z.object({
  email: z.string().email({
    message: "Veuillez entrer une adresse email valide",
  }),
  password: z.string().min(1, {
    message: "Le mot de passe est requis",
  }),
});

export default function Login() {
  const { login, isAuthenticated, currentUser } = useAuth();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const navigate = useNavigate();

  const form = useForm<z.infer<typeof loginSchema>>({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      email: "",
      password: "",
    },
  });

  async function onSubmit(values: z.infer<typeof loginSchema>) {
    setIsSubmitting(true);
    try {
      const result = await login(values.email, values.password);
      if (result.success) {
        toast.success("Bienvenue !");
      } else if ("errorCode" in result && result.errorCode === "email_not_confirmed") {
        toast.error(
          "Votre adresse email n’est pas encore confirmée. Consultez votre boîte mail et cliquez sur le lien de confirmation avant de vous connecter.",
        );
      } else {
        toast.error("Identifiants incorrects");
      }
    } catch (error) {
      console.error("Login error:", error);
      toast.error("Une erreur est survenue lors de la connexion");
    } finally {
      setIsSubmitting(false);
    }
  }

  const redirectToFirstTripOrDashboard = useCallback(async (user: Profile) => {
    try {
      const role = user.role;

      if (role === 'traveler') {
        // Set first login flag if needed (using localStorage instead of checking created_at)
        const isFirstLogin = localStorage.getItem('isFirstLoginCheck') === null;
        if (isFirstLogin) {
          localStorage.setItem('firstLogin', 'true');
          localStorage.setItem('isFirstLoginCheck', 'done');
        }

        navigate('/voyageur/dashboard', { replace: true });
      } else {
        navigate('/dashboard');
      }
    } catch (error) {
      console.error('Error during redirection:', error);
      navigate('/voyageur/dashboard');
    }
  }, [navigate]);

  useEffect(() => {
    if (isAuthenticated && currentUser) {
      redirectToFirstTripOrDashboard(currentUser);
    }
  }, [isAuthenticated, currentUser, redirectToFirstTripOrDashboard]);

  return (
    <div className="flex min-h-[calc(100vh-5rem)] items-center justify-center bg-background px-4 py-12">
      <div className="surface-card w-full max-w-md p-6 sm:p-9">
        <div className="text-center mb-8">
          <img src="/logo-light.svg" alt="TripTales" width="176" height="44" className="mx-auto mb-7 h-11 w-auto" />
          <h1 className="text-3xl font-bold">Heureux de vous revoir</h1>
          <p className="mt-2 text-muted-foreground">
            Connectez-vous pour accéder à votre compte
          </p>
        </div>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
            <FormField
              control={form.control}
              name="email"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Email</FormLabel>
                  <FormControl>
                    <Input placeholder="exemple@email.com" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="password"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Mot de passe</FormLabel>
                  <FormControl>
                    <Input type="password" placeholder="********" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <Button
              type="submit"
              className="w-full"
              disabled={isSubmitting}
            >
              {isSubmitting ? "Connexion en cours…" : "Se connecter"}
            </Button>
          </form>
        </Form>

        <div className="mt-4 text-center">
          <Link to="/forgot-password" className="text-sm font-semibold text-primary hover:underline">
            Mot de passe oublié ?
          </Link>
        </div>

        <div className="mt-6 text-center">
          <p className="text-muted-foreground">
            Vous n'avez pas de compte ?{" "}
            <Link to="/signup" className="font-semibold text-primary hover:underline">
              S'inscrire
            </Link>
          </p>
        </div>
      </div>
    </div>
  );
}
