"use client";

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

const SignInForm = () => {
  const [login, { isLoading, reset }] = useLoginMutation();
  const [mode, setMode] = useState<AuthIdentityMode>("phone");
  const [userData, setUserData] = useState({ identity: "", password: "" });

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

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

  const handleSubmit = async (e: SyntheticEvent) => {
    e.preventDefault();
    const identity = userData.identity.trim();
    if (mode === "phone") {
      login({
        password: userData.password,
        phone: identity,
        username: identity,
      });
    } else {
      login({
        password: userData.password,
        email: identity,
        username: identity,
      });
    }
  };

  return (
    <form onSubmit={handleSubmit} className="flex flex-col gap-3">
      <div className="text-left flex flex-col gap-3">
        <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
            required
            id="identity"
            name="identity"
            value={userData.identity}
            onChange={(phone) => setUserData({ ...userData, identity: phone })}
          />
        ) : (
          <Input
            required
            id="identity"
            type="email"
            inputMode="email"
            autoComplete="email"
            placeholder="you@example.com"
            name="identity"
            value={userData.identity}
            onChange={(e) =>
              setUserData({ ...userData, identity: e.target.value })
            }
          />
        )}
        <Label htmlFor="password">Enter Password</Label>
        <PasswordInput
          required
          id="password"
          placeholder=""
          name="password"
          value={userData.password}
          onChange={(e) =>
            setUserData({ ...userData, password: e.target.value })
          }
          autoComplete="current-password"
        />
        <div className="w-full flex justify-end text-end">
          <Link href="/forgot-password" className="text-sm">
            Forgot Password
          </Link>
        </div>
      </div>
      <Button className="w-full" type="submit" disabled={isLoading}>
        {isLoading ? "Signing in…" : "Sign In"}
      </Button>
    </form>
  );
};

export default SignInForm;
