"use client";
import React, { SyntheticEvent, useEffect, useState } from "react";
import { Input } from "@/components/ui/input";
import { PasswordInput } from "@/components/ui/password-input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import Link from "next/link";
import { useRegisterMutation } from "@/redux/api";
import { toast } from "sonner";
import { ArrowRight } from "lucide-react";
import type { AuthIdentityMode } from "@/lib/auth-identity";
import { PhoneInput } from "@/components/ui/phone-input";
import { authPageHref, setAuthReturnTo, readNextFromSearch } from "@/lib/auth-return";

const RegisterForm = () => {
  const [registerMutation, { isLoading, reset }] = useRegisterMutation();
  const [mode, setMode] = useState<AuthIdentityMode>("phone");
  const [acceptTerms, setAcceptTerms] = useState(true);
  const [userData, setUserData] = useState({
    firstname: "",
    lastname: "",
    identity: "",
    password: "",
    confirmpassword: "",
  });

  useEffect(() => {
    reset();
  }, [reset]);

  useEffect(() => {
    const next = readNextFromSearch();
    if (next) setAuthReturnTo(next);
  }, []);

  const handleSubmit = async (e: SyntheticEvent) => {
    e.preventDefault();
    if (
      !userData.firstname?.trim() ||
      !userData.lastname?.trim() ||
      !userData.identity?.trim()
    ) {
      toast.error("Please fill in all fields.");
      return;
    }
    if (!acceptTerms) {
      toast.error("Please accept the Terms & Conditions and Privacy Policy.");
      return;
    }
    if (userData.password !== userData.confirmpassword) {
      toast.error("Passwords do not match.");
      return;
    }
    const identity = userData.identity.trim();
    registerMutation({
      password: userData.password,
      firstname: userData.firstname,
      lastname: userData.lastname,
      role: "user",
      ...(mode === "phone" ? { phone: identity } : { email: identity }),
    });
  };

  const signInHref = authPageHref("sign-in", readNextFromSearch());

  return (
    <form onSubmit={handleSubmit} className="flex flex-col gap-3" noValidate>
      <h1 className="font-bold text-lg">Register on Nizamify</h1>
      <p className="text-gray-500 text-sm">
        Create an account with your phone number or email
      </p>
      <div className="text-left flex flex-col gap-2">
        <Label htmlFor="firstname">First Name</Label>
        <Input
          placeholder=""
          name="firstname"
          onChange={(e) =>
            setUserData({ ...userData, firstname: e.target.value })
          }
          value={userData.firstname}
        />
        <Label htmlFor="lastname">Last Name</Label>
        <Input
          placeholder=""
          name="lastname"
          onChange={(e) =>
            setUserData({ ...userData, lastname: e.target.value })
          }
          value={userData.lastname}
        />
        <div className="flex items-center justify-between gap-2">
          <Label htmlFor="identity">
            {mode === "phone" ? "Mobile number" : "Email"}
          </Label>
          <button
            type="button"
            className="text-xs text-primary underline-offset-2 hover:underline"
            onClick={() => {
              setMode((m) => (m === "phone" ? "email" : "phone"));
              setUserData((d) => ({ ...d, identity: "" }));
            }}
          >
            {mode === "phone" ? "Use email instead" : "Use phone instead"}
          </button>
        </div>
        {mode === "phone" ? (
          <PhoneInput
            id="identity"
            name="identity"
            value={userData.identity}
            onChange={(phone) => setUserData({ ...userData, identity: phone })}
          />
        ) : (
          <Input
            id="identity"
            type="email"
            inputMode="email"
            autoComplete="email"
            placeholder="you@example.com"
            name="identity"
            onChange={(e) =>
              setUserData({ ...userData, identity: e.target.value })
            }
            value={userData.identity}
          />
        )}
        <Label htmlFor="password">Enter Password</Label>
        <PasswordInput
          id="password"
          placeholder=""
          name="password"
          onChange={(e) =>
            setUserData({ ...userData, password: e.target.value })
          }
          value={userData.password}
          autoComplete="new-password"
        />
        <Label htmlFor="confirmpassword">Re-Enter Password</Label>
        <PasswordInput
          id="confirmpassword"
          placeholder=""
          name="confirmpassword"
          onChange={(e) =>
            setUserData({ ...userData, confirmpassword: e.target.value })
          }
          value={userData.confirmpassword}
          autoComplete="new-password"
        />
        <label className="mt-1 flex items-start gap-2 text-sm text-gray-600">
          <input
            type="checkbox"
            className="mt-1 size-4 shrink-0 accent-primary"
            checked={acceptTerms}
            onChange={(e) => setAcceptTerms(e.target.checked)}
          />
          <span>
            I accept the{" "}
            <Link href="/terms" className="text-primary underline-offset-2 hover:underline" target="_blank">
              Terms &amp; Conditions
            </Link>{" "}
            and{" "}
            <Link href="/privacy" className="text-primary underline-offset-2 hover:underline" target="_blank">
              Privacy Policy
            </Link>
          </span>
        </label>
      </div>
      <Button className="w-full" type="submit" disabled={isLoading}>
        {isLoading ? "Please wait…" : "Sign Up"}
      </Button>
      <div className="flex items-center justify-end">
        <Link href={signInHref} className="flex items-center text-sm">
          Login <ArrowRight className="w-4 h-4" />
        </Link>
      </div>
    </form>
  );
};

export default RegisterForm;
