/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable react/no-unescaped-entities */
"use client";

import React, { useRef, useState, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import { toast } from "sonner";
import { loginSchema } from "@/zod/auth.validation";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";

export default function LoginForm() {
  const identifierRef = useRef<HTMLInputElement>(null);
  const passwordRef = useRef<HTMLInputElement>(null);
  const router = useRouter();
  const searchParams = useSearchParams();

  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<{ identifier?: string; password?: string }>({});

  useEffect(() => {
    const errorParam = searchParams.get("error");
    if (errorParam) {
      toast.error(decodeURIComponent(errorParam));
    }
  }, [searchParams]);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrors({});

    const identifier = identifierRef.current?.value || "";
    const password = passwordRef.current?.value || "";

    const result = loginSchema.safeParse({ identifier, password });
    if (!result.success) {
      const fieldErrors = result.error.flatten().fieldErrors;
      setErrors({
        identifier: fieldErrors.identifier?.[0],
        password: fieldErrors.password?.[0],
      });
      return;
    }

    setLoading(true);
    const toastId = toast.loading("Verifying credentials...");
    try {
      const response = await fetch("/api/client/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(result.data),
      });
      const apiResult = await response.json().catch(() => null);
      toast.dismiss(toastId);
      if (!response.ok || !apiResult?.success) {
        const errorMsg = apiResult?.message || "";
        if (errorMsg.toLowerCase().includes("no password set")) {
          toast.error(
            <div>
              Your account has no password set.{" "}
              <Link
                href="/set-password"
                onClick={(e) => {
                  e.preventDefault();
                  router.push("/set-password");
                }}
                className="underline font-bold text-amber-500 hover:text-amber-400"
              >
                Click here to set/reset password
              </Link>
            </div>,
            { duration: 10000 }
          );
        } else {
          toast.error(errorMsg || "Login failed. Please check credentials.");
        }
        return;
      }
      toast.success("Welcome back!");
      router.push("/");
      router.refresh();
    } catch (err: any) {
      toast.dismiss(toastId);
      const errMsg = err.message || "";
      if (errMsg.toLowerCase().includes("no password set")) {
        toast.error(
          <div>
            Your account has no password set.{" "}
            <Link
              href="/set-password"
              onClick={(e) => {
                e.preventDefault();
                router.push("/set-password");
              }}
              className="underline font-bold text-amber-500 hover:text-amber-400"
            >
              Click here to set/reset password
            </Link>
          </div>,
          { duration: 10000 }
        );
      } else {
        toast.error(errMsg || "Something went wrong");
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card className="mx-auto w-full max-w-sm border border-zinc-200/80 bg-white/70 shadow-xl backdrop-blur-md dark:border-zinc-800/80 dark:bg-zinc-900/70 rounded-md">
      <CardHeader className="space-y-1 text-center">
        <CardTitle className="text-xl lg:text-2xl font-black text-zinc-900 dark:text-white uppercase tracking-wider">
          Sign In
        </CardTitle>
        <CardDescription className="text-zinc-500 dark:text-zinc-400 text-xs">
          Access your personal account
        </CardDescription>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleLogin} noValidate className="space-y-5">
          <div className="space-y-2">
            <Label htmlFor="identifier" className="text-xs uppercase tracking-wider font-bold text-zinc-700 dark:text-zinc-300">
              Email or Mobile Number
            </Label>
            <Input
              id="identifier"
              ref={identifierRef}
              type="text"
              placeholder="e.g. you@example.com or 017XXXXXXXX"
              className="bg-zinc-50/50 border border-zinc-200/80 dark:bg-zinc-950/50 dark:border-zinc-800 text-zinc-900 dark:text-white focus-visible:ring-brand-accent placeholder:text-zinc-400 rounded-md"
            />
            {errors.identifier && (
              <p className="text-red-500 text-xs mt-1">{errors.identifier}</p>
            )}
          </div>

          <div className="space-y-2">
            <Label htmlFor="password" className="text-xs uppercase tracking-wider font-bold text-zinc-700 dark:text-zinc-300">Password</Label>
            <Input
              id="password"
              ref={passwordRef}
              type="password"
              placeholder="••••••••"
              className="bg-zinc-50/50 border border-zinc-200/80 dark:bg-zinc-950/50 dark:border-zinc-800 text-zinc-900 dark:text-white focus-visible:ring-brand-accent placeholder:text-zinc-400 rounded-md"
            />
            {errors.password && (
              <p className="text-red-500 text-xs mt-1">{errors.password}</p>
            )}
          </div>

          <Button
            type="submit"
            disabled={loading}
            className="w-full rounded-md bg-brand-accent hover:bg-brand-accent-hover text-white font-bold hover:font-black text-xs uppercase tracking-wider h-9 transition-all duration-300 ease-out hover:shadow-[0_4px_10px_rgba(245,158,11,0.25)] border-none"
          >
            {loading ? "Signing in..." : "Sign In"}
          </Button>

          <div className="relative flex py-1 items-center">
            <div className="flex-grow border-t border-zinc-200 dark:border-zinc-800"></div>
            <span className="flex-shrink mx-4 text-zinc-400 text-[10px] uppercase font-bold tracking-wider">Or</span>
            <div className="flex-grow border-t border-zinc-200 dark:border-zinc-800"></div>
          </div>

          <Button
            type="button"
            onClick={() => {
              const backendUrl = process.env.NEXT_PUBLIC_BACKEND_URL || "http://localhost:3001/api/v1";
              window.location.href = `${backendUrl}/client/auth/google`;
            }}
            variant="outline"
            className="w-full rounded-md border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-950 text-zinc-700 dark:text-zinc-300 font-bold text-xs uppercase tracking-wider h-9 hover:bg-zinc-50 dark:hover:bg-zinc-900 transition-all duration-300 flex items-center justify-center gap-2"
          >
            <svg className="h-4 w-4 text-red-500" aria-hidden="true" focusable="false" data-prefix="fab" data-icon="google" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 488 512">
              <path fill="currentColor" d="M488 261.8C488 403.3 391.1 504 248 504 110.8 504 0 393.2 0 256S110.8 8 248 8c66.8 0 123 24.5 166.3 64.9l-67.5 64.9C258.5 52.6 94.3 116.6 94.3 256c0 86.5 69.1 156.6 153.7 156.6 98.2 0 135-70.4 140.8-106.9H248v-85.3h236.1c2.3 12.7 3.9 24.9 3.9 41.4z"></path>
            </svg>
            Continue with Google Login
          </Button>

          <div className="text-center text-[11px] text-zinc-500 dark:text-zinc-400 mt-4 space-y-1">
            <div>
              Don't have an account?{" "}
              <Link
                href="/register"
                onClick={(e) => {
                  e.preventDefault();
                  router.push("/register");
                }}
                className="font-bold text-brand-accent hover:text-brand-accent-hover transition-colors uppercase tracking-wider text-[10px]"
              >
                Sign Up
              </Link>
            </div>
            <div>
              Having trouble logging in?{" "}
              <Link
                href="/set-password"
                onClick={(e) => {
                  e.preventDefault();
                  router.push("/set-password");
                }}
                className="font-bold text-brand-accent hover:text-brand-accent-hover transition-colors uppercase tracking-wider text-[10px]"
              >
                Set / Reset Password
              </Link>
            </div>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}
