"use client";

import { useState, FormEvent } from "react";
import { useRouter } from "next/navigation";
import { UserPlus, Mail, ArrowLeft } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { AuthFormWrapper } from "@/components/auth/auth-form-wrapper";
import { useAdminInit } from "@/lib/api/hooks/useAuth";
import { ApiRequestError } from "@/lib/api";
import { ROUTES } from "@/lib/constants";

export default function AdminInitPage() {
  const router = useRouter();
  const adminInit = useAdminInit();

  const [email, setEmail] = useState("");
  const [error, setError] = useState("");

  function handleSubmit(e: FormEvent) {
    e.preventDefault();
    setError("");

    if (!email) {
      setError("Email is required");
      return;
    }

    adminInit.mutate(
      { email },
      {
        onSuccess: () => {
          router.push(
            `${ROUTES.VERIFY_EMAIL}?email=${encodeURIComponent(email)}&type=verification`
          );
        },
        onError: (err) => {
          if (err instanceof ApiRequestError) {
            setError(err.message);
          } else {
            setError("Something went wrong. Please try again.");
          }
        },
      }
    );
  }

  return (
    <AuthFormWrapper
      icon={UserPlus}
      title="New Admin Login"
      subtitle="Enter your email to get started"
      backLabel="Back to login"
      onBack={() => router.push(ROUTES.LOGIN)}
    >
      <form onSubmit={handleSubmit} className="space-y-6">
        <div className="space-y-2">
          <Label htmlFor="email" className="text-gray-300">
            Email Address
          </Label>
          <div className="relative">
            <Mail className="absolute left-4 top-1/2 -translate-y-1/2 size-5 text-gray-400" />
            <Input
              id="email"
              type="email"
              placeholder="admin@examportal.com"
              value={email}
              onChange={(e) => {
                setEmail(e.target.value);
                setError("");
              }}
              className={`pl-12 bg-gray-800 border-gray-700 text-white placeholder:text-gray-500 ${
                error ? "border-red-500" : ""
              }`}
            />
          </div>
          {error && <p className="text-red-400 text-sm mt-1">{error}</p>}
        </div>

        <Button
          type="submit"
          disabled={adminInit.isPending}
          className="w-full text-lg py-6"
        >
          {adminInit.isPending ? "Sending OTP..." : "Continue"}
        </Button>

        <p className="text-xs text-gray-500 text-center">
          A verification code will be sent to your email.
        </p>
      </form>
    </AuthFormWrapper>
  );
}
