"use client";

import Link from "next/link";
import { Controller } from "react-hook-form";
import { CheckCircle2, Info, Mail } from "lucide-react";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Spinner } from "@/components/ui/spinner";
import { AuthLayout } from "@/components/app/auth-layout";
import { AuthError, AuthHeading, IconField, PasswordField } from "../auth/auth-ui";
import { useRedirectIfSignedIn } from "../auth/auth-redirect";
import { useLoginForm } from "./useLoginForm";

export default function LoginForm() {
  useRedirectIfSignedIn();
  const { form, submit, notice, errorKind, clearServerError } = useLoginForm();
  const { errors, isSubmitting } = form.formState;
  const email = form.watch("email");
  const forgotHref = email ? `/forgot-password?email=${encodeURIComponent(email)}` : "/forgot-password";

  return <AuthLayout>
    <AuthHeading title="Welcome back">Sign in to your buying house workspace.</AuthHeading>

    <form onSubmit={submit} noValidate className="grid gap-6">
      <AuthError message={errors.root?.server?.message} action={errorKind === "credentials" && <span>Check both and try again, or <Link href={forgotHref} className="font-medium underline underline-offset-4">reset your password</Link>.</span>} />
      {notice && !errors.root && <Alert>{notice.tone === "success" ? <CheckCircle2 className="text-success" /> : <Info />}<AlertDescription className="text-foreground">{notice.text}</AlertDescription></Alert>}

      <FieldGroup className="gap-5">
        <IconField control={form.control} name="email" id="login-email" label="Work email" icon={Mail} type="email" autoComplete="username" placeholder="name@company.com" onType={clearServerError} inputProps={{ inputMode: "email", autoCapitalize: "none", spellCheck: false }} />
        <PasswordField control={form.control} name="password" id="login-password" placeholder="Enter your password" onType={clearServerError}
          labelAction={<Link href={forgotHref} className="rounded-sm text-xs font-medium text-muted-foreground underline-offset-4 outline-none hover:text-foreground hover:underline focus-visible:ring-[3px] focus-visible:ring-ring/50">Forgot password?</Link>} />

        <Controller control={form.control} name="remember" render={({ field }) => <Field orientation="horizontal">
          <Checkbox id="login-remember" checked={field.value} onCheckedChange={(checked) => field.onChange(checked === true)} />
          <FieldLabel htmlFor="login-remember" className="font-normal">Keep me signed in on this device</FieldLabel>
        </Field>} />
      </FieldGroup>

      <Button type="submit" size="lg" className="w-full" disabled={isSubmitting}>{isSubmitting && <Spinner />} {isSubmitting ? "Signing in…" : "Sign in"}</Button>
    </form>

    <div className="mt-8 grid gap-3 border-t pt-6 text-center text-sm text-muted-foreground">
      <p>New to Order Flow? <Link href="/register" className="font-medium text-foreground underline-offset-4 hover:underline">Create a workspace</Link></p>
      <p className="text-xs">Buyer or factory contact? Use the portal link from your invitation email.</p>
    </div>
  </AuthLayout>;
}
