"use client"

import { Suspense, useState } from "react"
import Image from "next/image"
import Link from "next/link"
import { useRouter, useSearchParams } from "next/navigation"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { Eye, EyeOff } from "lucide-react"
import { loginSchema, LoginValues } from "@/lib/validations"
import { authApi } from "@/lib/api/auth"
import { setStoredUser } from "@/lib/auth-session"
import { errorMessage } from "@/lib/error-map"

import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"

export default function LoginPage() {
  return (
    <Suspense fallback={null}>
      <LoginForm />
    </Suspense>
  )
}

function LoginForm() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const [showPassword, setShowPassword] = useState(false)
  const [remember, setRemember] = useState(false)
  const [submitError, setSubmitError] = useState<string | null>(null)
  const returnTo = searchParams.get("next")
  const sessionNotice = returnTo ? "Your session is missing or expired. Sign in again to continue." : null

  const form = useForm<LoginValues>({
    resolver: zodResolver(loginSchema),
    defaultValues: { email: "", password: "" },
  })

  const onSubmit = form.handleSubmit(async (values) => {
    setSubmitError(null)
    try {
      // The session arrives as httpOnly cookies; the body carries only the user profile.
      const session = await authApi.login({ identifier: values.email, password: values.password })
      setStoredUser(session.user)
      // Honour the path the guard bounced us from, but only same-origin paths — an
      // attacker-supplied absolute URL here would be an open redirect.
      const next = searchParams.get("next")
      router.push(next?.startsWith("/") && !next.startsWith("//") ? next : "/dashboard")
    } catch (err) {
      setSubmitError(errorMessage(err))
    }
  })

  return (
    <div className="relative min-h-screen overflow-hidden">
      {/* Full-page background photo — right side only. Dark mode swaps to the backdrop-free
          cutout (whithoutbackground.png) so there's no white scene box floating on the
          dark panel. */}
      <div className="absolute inset-y-0 left-[45%] right-0 bg-white dark:bg-background">
        <Image
          src="/images/loginerps.png"
          alt="ERP Illustration"
          fill
          className="object-contain object-center dark:hidden"
          priority
        />
        <Image
          src="/images/whithoutbackground.png"
          alt="ERP Illustration"
          fill
          className="hidden object-contain object-center dark:block"
          priority
        />
      </div>

      {/* Login panel — overlays left side, no hard border with the photo */}
      <main className="relative z-10 flex min-h-screen w-full flex-col justify-center bg-white dark:bg-background px-6 py-12 sm:px-12 md:w-[45%]">
        <div className="mb-8 flex justify-center">
          <Link href="/" className="inline-flex items-center">
            <Image src="/images/logo%20(2).png" alt="Hexa ERP" width={300} height={150} />
          </Link>
        </div>

        <div className="text-center">
          <h1 className="text-3xl font-bold text-foreground">Sign in to your account</h1>
          <p className="mt-3 text-base text-muted-foreground">Access your ERP dashboard and manage your business</p>
          {sessionNotice ? (
            <div className="mt-4 rounded-lg border border-amber-300 bg-amber-50 px-4 py-3 text-sm text-amber-900">
              {sessionNotice}
            </div>
          ) : null}
        </div>

        <form onSubmit={onSubmit} noValidate className="mt-10 space-y-6" aria-describedby="form-errors" aria-live="polite">
          {submitError && (
            <div role="alert" className="rounded-lg border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive">
              {submitError}
            </div>
          )}
          <FieldGroup className="space-y-5">
            <Field data-invalid={!!form.formState.errors.email}>
              <FieldLabel htmlFor="email" className="text-sm font-semibold text-foreground">
                Email Address
              </FieldLabel>
              <Input
                id="email"
                type="email"
                autoComplete="email"
                className="mt-2 h-11 rounded-lg px-4 text-base"
                placeholder="you@example.com"
                aria-invalid={!!form.formState.errors.email}
                {...form.register("email")}
              />
              <FieldError errors={[form.formState.errors.email]} />
            </Field>

            <Field data-invalid={!!form.formState.errors.password}>
              <FieldLabel htmlFor="password" className="text-sm font-semibold text-foreground">
                Password
              </FieldLabel>
              <div className="relative mt-2">
                <Input
                  id="password"
                  type={showPassword ? "text" : "password"}
                  autoComplete="current-password"
                  className="h-11 rounded-lg px-4 pr-11 text-base"
                  placeholder="Enter your password"
                  aria-invalid={!!form.formState.errors.password}
                  {...form.register("password")}
                />
                <button
                  type="button"
                  onClick={() => setShowPassword((v) => !v)}
                  aria-label={showPassword ? "Hide password" : "Show password"}
                  className="absolute inset-y-0 right-3 flex items-center text-muted-foreground hover:text-foreground transition-colors"
                >
                  {showPassword ? (
                    <EyeOff className="size-5" />
                  ) : (
                    <Eye className="size-5" />
                  )}
                </button>
              </div>
              <FieldError errors={[form.formState.errors.password]} />
              <div className="flex justify-end mt-1">
                <Link href="/login/forgot" className="text-sm font-medium text-foreground hover:text-foreground/70 transition-colors">
                  Forgot password?
                </Link>
              </div>
            </Field>

            <Field>
              <label className="flex items-center gap-3">
                <Checkbox checked={remember} onCheckedChange={(v) => setRemember(v === true)} />
                <span className="text-sm font-medium text-foreground">Remember me</span>
              </label>
            </Field>

            <Button
              type="submit"
              className="w-1/2 mx-auto mt-8 h-12 text-sm font-medium rounded-full bg-foreground text-background hover:bg-foreground/90"
              disabled={form.formState.isSubmitting}
            >
              {form.formState.isSubmitting ? "Signing in…" : "Sign in"}
            </Button>

          </FieldGroup>
        </form>

        <div id="form-errors" className="sr-only" aria-live="polite">
          {Object.values(form.formState.errors).length > 0 && "There are errors in the form."}
        </div>

        <div className="mt-12 text-center">
          <p className="text-sm text-muted-foreground">
            Don&apos;t have an account? <Link href="#" className="font-semibold text-foreground hover:text-foreground/80 transition-colors">Create an account</Link>
          </p>
        </div>
      </main>
    </div>
  )
}
