import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Eye, EyeOff, Loader2 } from "lucide-react";
import { useAuth } from "@/contexts/AuthContext";
import { useToast } from "@/hooks/use-toast";
import { ApiError } from "@/lib/api-client";
import type { UserRole } from "@/types/auth";
import { LanguageToggle } from "@/components/LanguageToggle";

/** Keep in sync with `ProtectedRoute` post-login targets */
function getRoleDashboard(role: string): string {
  switch (role as UserRole) {
    case "student":
      return "/student/dashboard";
    case "teacher":
      return "/teacher/dashboard";
    case "admin":
    case "developer":
      return "/admin/dashboard";
    case "corporate":
    case "mastercorporate":
    case "agent":
      return "/admin/platform";
    default:
      return "/admin/dashboard";
  }
}

function loginErrorMessage(err: unknown): string {
  if (err instanceof ApiError && err.data && typeof err.data === "object" && err.data !== null && "error" in err.data) {
    return String((err.data as { error: string }).error);
  }
  if (err instanceof Error) {
    return err.message;
  }
  return "Login failed";
}

export default function Login() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const { login } = useAuth();
  const { toast } = useToast();
  const { t } = useTranslation();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!email || !password) {
      toast({
        title: t("auth.errorTitle"),
        description: t("auth.missingCredentials"),
        variant: "destructive",
      });
      return;
    }

    setLoading(true);
    try {
      const user = await login(email, password);
      navigate(getRoleDashboard(user.user_type));
    } catch (err: unknown) {
      toast({
        title: t("auth.loginFailedTitle"),
        description: loginErrorMessage(err),
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-background p-4">
      <div className="absolute top-4 right-4">
        <LanguageToggle />
      </div>
      <div className="w-full max-w-md">
        <div className="flex items-center justify-center mb-8">
          <img
            src="/logo.png"
            alt="EnCoach — Unlock your potential with AI powered platform"
            className="h-36 w-auto object-contain"
          />
        </div>

        <Card className="shadow-lg border-0 bg-card">
          <CardHeader className="text-center pb-4">
            <CardTitle className="text-xl">{t("auth.welcomeBack")}</CardTitle>
            <CardDescription>{t("auth.signInDescription")}</CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="email">{t("auth.email")}</Label>
                <Input
                  id="email"
                  type="text"
                  placeholder={t("auth.emailPlaceholder")}
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  disabled={loading}
                  dir="ltr"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="password">{t("auth.password")}</Label>
                <div className="relative">
                  <Input
                    id="password"
                    type={showPassword ? "text" : "password"}
                    placeholder="••••••••"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    disabled={loading}
                    dir="ltr"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    aria-label={showPassword ? t("auth.password") : t("auth.password")}
                    className="absolute end-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                  >
                    {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </button>
                </div>
              </div>
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Checkbox id="remember" />
                  <Label htmlFor="remember" className="text-sm font-normal cursor-pointer">
                    {t("auth.rememberMe")}
                  </Label>
                </div>
                <Link to="/forgot-password" className="text-sm text-primary hover:underline">
                  {t("auth.forgotPassword")}
                </Link>
              </div>
              <Button type="submit" className="w-full" disabled={loading}>
                {loading && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
                {t("auth.signIn")}
              </Button>
            </form>

            <p className="mt-6 text-center text-sm text-muted-foreground">
              {t("auth.needAccount")}{" "}
              <Link to="/register" className="text-primary font-medium hover:underline">
                {t("auth.signUp")}
              </Link>
            </p>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
