"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useAuth } from "@/lib/auth-context";
import { useLanguage } from "@/lib/i18n";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Loader2,
  Mail,
  Lock,
  ArrowRight,
  Eye,
  EyeOff,
  AlertCircle,
  Edit,
  AlertTriangle,
} from "lucide-react";
import { toast } from "react-toastify";

type RejectedAccount = {
  uuid?: string;
  name: string;
  email: string;
  reason: string;
};

export default function LoginPage() {
  const router = useRouter();
  const { login, user, isLoading, isAuthenticated } = useAuth();
  const { language, t } = useLanguage();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [fieldErrors, setFieldErrors] = useState<Record<string, string[]>>({});
  const [loginError, setLoginError] = useState("");
  const [rejectedAccount, setRejectedAccount] =
    useState<RejectedAccount | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setFieldErrors({});
    setLoginError("");
    setRejectedAccount(null);

    const result = await login(email, password);

    if (result.success && result.user) {
      toast.success(result.message || t("auth.loginSuccess"));

      if (result.user.role === "admin") {
        router.push("/admin");
      } else if (result.user.role === "guide") {
        router.push("/dashboard");
      }
    } else {
      if (result.rejectedAccount) {
        setRejectedAccount(result.rejectedAccount);
        return;
      }

      setFieldErrors(result.errors || {});

      const validationMessages = result.errors
        ? Object.values(result.errors).flat()
        : [];
      const apiMessage =
        language === "hi"
          ? result.message_hi || result.message
          : result.message;
      const errorMessage =
        apiMessage || validationMessages.join(" ") || t("auth.loginFailed");

      setLoginError(errorMessage);
    }
  };

  const clearLoginError = () => {
    if (loginError) {
      setLoginError("");
    }
    if (rejectedAccount) {
      setRejectedAccount(null);
    }
  };

  const closeRejectedDialog = () => {
    setRejectedAccount(null);
  };

  const resubmitRejectedProfile = () => {
    const params = new URLSearchParams({ resubmit: "1" });

    if (rejectedAccount?.uuid) {
      params.set("uuid", rejectedAccount.uuid);
    }

    if (rejectedAccount?.email) {
      params.set("email", rejectedAccount.email);
    }

    router.push(`/auth/register?${params}`);
  };

  useEffect(() => {
    if (isLoading || !isAuthenticated || !user) return;

    router.replace(user.role === "admin" ? "/admin" : "/dashboard");
  }, [isAuthenticated, isLoading, router, user]);

  if (isLoading || isAuthenticated) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-[var(--theme-surface)]">
        <div className="h-10 w-10 animate-spin rounded-full border-4 border-[var(--theme-secondary)]/25 border-t-[var(--theme-primary)]" />
      </div>
    );
  }

  return (
    <>
      <Dialog
        open={Boolean(rejectedAccount)}
        onOpenChange={(open) => {
          if (!open) closeRejectedDialog();
        }}
      >
        <DialogContent className="rounded-3xl border-[var(--theme-border-soft)] p-0 sm:max-w-xl">
          <DialogHeader className=" px-6 py-5 text-left">
            <DialogTitle className="mt-4 text-2xl font-black text-[var(--theme-primary)]">
              <span className="text-foreground">Hello,</span>{" "}
              {rejectedAccount?.name || ""}
            </DialogTitle>
            <DialogDescription className="text-base leading-6 text-muted-foreground">
              Your profile has been reviewed and was not approved by the
              administrator due to some issues with the submitted information.
              Please review the rejection reason carefully, update the required
              details, and resubmit your profile for verification. Once your
              corrections are approved, your account will be eligible for
              activation
            </DialogDescription>
          </DialogHeader>

          <div className="px-6 py-5">
            <div className="flex items-start gap-3 rounded-2xl border border-amber-200 bg-amber-50 p-4 text-amber-800">
              <AlertTriangle className="mt-0.5 h-5 w-5 shrink-0 text-amber-600" />
              <div>
                <p className="mb-1 text-sm font-black uppercase tracking-wide">
                  Rejected Reason
                </p>
                <p className="text-sm font-medium leading-6">
                  {rejectedAccount?.reason ||
                    "No rejection reason was provided by admin."}
                </p>
              </div>
            </div>
          </div>

          <DialogFooter className="border-t border-[var(--theme-border-soft)] px-6 py-4">
            <Button
              type="button"
              variant="outline"
              className="h-12 w-full rounded-xl border-[var(--theme-border-soft)] px-6 text-base font-semibold text-foreground hover:bg-[var(--theme-surface-soft)] sm:w-auto"
              onClick={closeRejectedDialog}
            >
              Not Now
            </Button>
            <Button
              type="button"
              className="h-12 w-full rounded-full border-0 bg-gradient-to-r from-[var(--theme-secondary)] to-[var(--theme-accent)] px-6 font-black text-white shadow-lg shadow-[var(--theme-secondary)]/25 hover:from-[var(--theme-primary)] hover:to-[var(--theme-primary-dark)] sm:w-auto"
              onClick={resubmitRejectedProfile}
            >
              <Edit className="mr-2 h-4 w-4" />
              Resubmit Profile
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <div className="relative flex min-h-screen overflow-hidden pb-10 pt-20">
        <Image
          src="https://images.unsplash.com/photo-1626621341517-bbf3d9990a23?w=1800&q=85"
          alt="Uttarakhand Mountains"
          fill
          className="object-cover"
          priority
        />
        <div className="absolute inset-0 bg-gradient-to-r from-background/90 via-background/68 to-background/35" />
        <div className="absolute inset-0 bg-gradient-to-t from-black/35 via-transparent to-white/10" />
        <div className="relative z-10 mx-auto flex w-full max-w-7xl items-center justify-center p-6 lg:p-10">
          <div className="grid w-full overflow-hidden rounded-[28px] bg-white/38 shadow-2xl shadow-black/10 backdrop-blur-md lg:grid-cols-2">
            {/* Left Side - Form */}
            <div className="flex items-center justify-center bg-white p-7 sm:p-10 lg:min-h-[620px] lg:p-14">
              <div className="w-full max-w-md">
                {/* Header */}
                <div className="mb-8">
                  <h1 className="mb-2 text-3xl font-bold text-foreground">
                    {t("auth.welcomeBack")}
                  </h1>
                  <p className="text-muted-foreground">
                    {t("auth.continueJourney")}
                  </p>
                  {loginError && (
                    <Alert
                      variant="destructive"
                      className="mt-5 border-red-200 bg-red-50 text-red-700"
                    >
                      <AlertCircle className="h-4 w-4" />
                      <AlertDescription className="font-semibold text-red-700">
                        {loginError}
                      </AlertDescription>
                    </Alert>
                  )}
                </div>

                {/* Form */}
                <form onSubmit={handleSubmit} className="space-y-5">
                  <div className="space-y-2">
                    <Label htmlFor="email" className="text-sm font-medium">
                      {t("auth.emailAddress")}
                    </Label>
                    <div className="relative">
                      <Mail className="absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                      <Input
                        id="email"
                        type="email"
                        placeholder={t("auth.emailPlaceholder")}
                        value={email}
                        onChange={(e) => {
                          clearLoginError();
                          setEmail(e.target.value);
                        }}
                        className="h-12 rounded-xl border-border/50 pl-11 focus:border-[var(--theme-primary)]/50 focus:ring-[var(--theme-primary)]/20"
                        required
                      />
                    </div>
                    {fieldErrors.email?.map((message, index) => (
                      <p
                        key={`${message}-${index}`}
                        className="text-xs font-medium text-red-600"
                      >
                        {message}
                      </p>
                    ))}
                  </div>

                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <Label htmlFor="password" className="text-sm font-medium">
                        {t("auth.password")}
                      </Label>
                      <Link
                        href="/auth/forgot-password"
                        className="text-xs font-medium text-[var(--theme-primary)] hover:text-[var(--theme-primary-dark)]"
                      >
                        {t("auth.forgotPassword")}
                      </Link>
                    </div>
                    <div className="relative">
                      <Lock className="absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                      <Input
                        id="password"
                        type={showPassword ? "text" : "password"}
                        placeholder={t("auth.passwordPlaceholder")}
                        value={password}
                        onChange={(e) => {
                          clearLoginError();
                          setPassword(e.target.value);
                        }}
                        className="h-12 rounded-xl border-border/50 pl-11 pr-12 focus:border-[var(--theme-primary)]/50 focus:ring-[var(--theme-primary)]/20"
                        required
                      />
                      <button
                        type="button"
                        onClick={() => setShowPassword((value) => !value)}
                        className="absolute right-4 top-1/2 -translate-y-1/2 text-muted-foreground transition-colors hover:text-foreground"
                        aria-label={
                          showPassword ? "Hide password" : "Show password"
                        }
                      >
                        {showPassword ? (
                          <EyeOff className="h-4 w-4" />
                        ) : (
                          <Eye className="h-4 w-4" />
                        )}
                      </button>
                    </div>
                    {fieldErrors.password?.map((message, index) => (
                      <p
                        key={`${message}-${index}`}
                        className="text-xs font-medium text-red-600"
                      >
                        {message}
                      </p>
                    ))}
                  </div>

                  <Button
                    type="submit"
                    className="h-12 w-full rounded-xl border-0 bg-gradient-to-r from-[var(--theme-secondary)] to-[var(--theme-accent)] text-base font-medium text-white shadow-lg shadow-[var(--theme-secondary)]/20 hover:from-[var(--theme-primary)] hover:to-[var(--theme-primary-dark)]"
                    disabled={isLoading}
                  >
                    {isLoading ? (
                      <>
                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                        {t("auth.signingIn")}
                      </>
                    ) : (
                      <>
                        {t("common.signIn")}
                        <ArrowRight className="ml-2 h-4 w-4" />
                      </>
                    )}
                  </Button>
                </form>

                <div className="mt-8 text-center">
                  <p className="text-sm text-muted-foreground">
                    {t("auth.noAccount")}{" "}
                    <Link
                      href="/auth/register"
                      className="font-semibold text-[var(--theme-primary)] hover:text-[var(--theme-primary-dark)]"
                    >
                      {t("common.registerAsGuide")}
                    </Link>
                  </p>
                </div>
              </div>
            </div>

            {/* Right Side - Text */}
            <div className="hidden items-center border-l border-white/35 px-10 py-12 lg:flex xl:px-14">
              <div className="max-w-2xl">
                <div className="mb-6 inline-flex rounded-full border border-[var(--theme-secondary)]/25 bg-white/70 px-4 py-2 text-sm font-semibold text-[var(--theme-primary)] shadow-sm backdrop-blur-md">
                  {t("auth.touristGuides")}
                </div>
                <h2 className="text-5xl font-black leading-tight tracking-tight xl:text-6xl">
                  <span className="block text-foreground">
                    {t("auth.heroTitle1")}
                  </span>
                  <span className="block text-[var(--theme-primary)]">
                    {t("auth.heroTitle2")}
                  </span>
                  <span className="block font-semibold text-foreground/60 text-4xl">
                    {t("auth.heroSubtitle")}
                  </span>
                </h2>
                <p className="mt-6 max-w-xl text-lg leading-8 text-foreground/80">
                  {t("common.footerDescription")}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
