// src/app/(auth)/register/page.tsx
// ─────────────────────────────────────────────────────────────────────────────
// Registration Page
//
// API call: POST {{base_url}}/ads/register
// Body: { company_name, name, email, password }
//
// On success:
//   → if API returns a token, saves it and redirects to /dashboard
//   → otherwise redirects to /login with a success message
// ─────────────────────────────────────────────────────────────────────────────

"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import axios from "axios";
import { Eye, EyeOff, Loader2, UserPlus } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { saveToken } from "@/lib/auth";

// ─── Validation Schema ────────────────────────────────────────────────────────
const registerSchema = z
  .object({
    company_name: z
      .string()
      .min(1, "Company name is required")
      .min(2, "Company name must be at least 2 characters"),
    name: z
      .string()
      .min(1, "Your name is required")
      .min(2, "Name must be at least 2 characters"),
    email: z
      .string()
      .min(1, "Email is required")
      .email("Please enter a valid email address"),
    password: z
      .string()
      .min(1, "Password is required")
      .min(6, "Password must be at least 6 characters"),
    confirm_password: z.string().min(1, "Please confirm your password"),
  })
  .refine((data) => data.password === data.confirm_password, {
    message: "Passwords do not match",
    path: ["confirm_password"], // attach error to confirm_password field
  });

type RegisterFormValues = z.infer<typeof registerSchema>;

// ─── Component ────────────────────────────────────────────────────────────────
export default function RegisterPage() {
  const router = useRouter();
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const [serverError, setServerError] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<RegisterFormValues>({
    resolver: zodResolver(registerSchema),
    defaultValues: {
      company_name: "",
      name: "",
      email: "",
      password: "",
      confirm_password: "",
    },
  });

  const onSubmit = async (values: RegisterFormValues) => {
    setIsLoading(true);
    setServerError(null);

    try {
      // POST to the registration endpoint
      // Note: confirm_password is NOT sent to the API — it's only for client-side validation
      const response = await axios.post(
        `${process.env.NEXT_PUBLIC_API_BASE_URL}/ads/register`,
        {
          company_name: values.company_name,
          name: values.name,
          email: values.email,
          password: values.password,
        }
      );

      // ── Handle response ────────────────────────────────────────────────────
      // Some APIs return a token on register (auto-login), others don't.
      const token =
        response.data?.token ||
        response.data?.data?.token ||
        response.data?.access_token;

      if (token) {
        // API returned a token → log the user in immediately
        saveToken(token);
        router.push("/dashboard");
        router.refresh();
      } else {
        // No token → redirect to login with success message
        router.push("/login?registered=true");
      }

    } catch (error: unknown) {
      if (axios.isAxiosError(error)) {
        // Handle validation errors (e.g. "email already taken")
        const apiErrors = error.response?.data?.errors;
        if (apiErrors && typeof apiErrors === "object") {
          // Laravel-style validation errors: { email: ["already taken"] }
          const firstError = Object.values(apiErrors).flat()[0];
          setServerError(String(firstError));
        } else {
          const msg =
            error.response?.data?.message ||
            error.response?.data?.error ||
            "Registration failed. Please try again.";
          setServerError(msg);
        }
      } else {
        setServerError("An unexpected error occurred. Please try again.");
      }
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Card className="border border-slate-700/50 bg-slate-800/80 backdrop-blur-sm shadow-2xl">
      {/* ── Card Header ── */}
      <CardHeader className="space-y-1 pb-4">
        <div className="flex justify-center mb-2">
          <div className="w-10 h-10 rounded-xl bg-emerald-500 flex items-center justify-center shadow-lg shadow-emerald-500/30">
            <UserPlus className="w-5 h-5 text-white" />
          </div>
        </div>
        <CardTitle className="text-2xl font-bold text-center text-white">
          Create an account
        </CardTitle>
        <CardDescription className="text-center text-slate-400">
          Fill in the details below to get started
        </CardDescription>
      </CardHeader>

      {/* ── Card Body / Form ── */}
      <CardContent>
        <form onSubmit={handleSubmit(onSubmit)} noValidate className="space-y-4">

          {/* Server-side error banner */}
          {serverError && (
            <div className="rounded-lg bg-red-500/10 border border-red-500/30 px-4 py-3 text-sm text-red-400">
              {serverError}
            </div>
          )}

          {/* ── Company Name ── */}
          <div className="space-y-1.5">
            <Label htmlFor="company_name" className="text-slate-300 text-sm font-medium">
              Company name
            </Label>
            <Input
              id="company_name"
              type="text"
              placeholder="ABC Ltd"
              autoComplete="organization"
              disabled={isLoading}
              className={`
                bg-slate-900/60 border-slate-600 text-white placeholder:text-slate-500
                focus-visible:ring-emerald-500 focus-visible:border-emerald-500
                ${errors.company_name ? "border-red-500 focus-visible:ring-red-500" : ""}
              `}
              {...register("company_name")}
            />
            {errors.company_name && (
              <p className="text-red-400 text-xs">{errors.company_name.message}</p>
            )}
          </div>

          {/* ── Full Name ── */}
          <div className="space-y-1.5">
            <Label htmlFor="name" className="text-slate-300 text-sm font-medium">
              Your name
            </Label>
            <Input
              id="name"
              type="text"
              placeholder="Razib"
              autoComplete="name"
              disabled={isLoading}
              className={`
                bg-slate-900/60 border-slate-600 text-white placeholder:text-slate-500
                focus-visible:ring-emerald-500 focus-visible:border-emerald-500
                ${errors.name ? "border-red-500 focus-visible:ring-red-500" : ""}
              `}
              {...register("name")}
            />
            {errors.name && (
              <p className="text-red-400 text-xs">{errors.name.message}</p>
            )}
          </div>

          {/* ── Email ── */}
          <div className="space-y-1.5">
            <Label htmlFor="email" className="text-slate-300 text-sm font-medium">
              Email address
            </Label>
            <Input
              id="email"
              type="email"
              placeholder="you@company.com"
              autoComplete="email"
              disabled={isLoading}
              className={`
                bg-slate-900/60 border-slate-600 text-white placeholder:text-slate-500
                focus-visible:ring-emerald-500 focus-visible:border-emerald-500
                ${errors.email ? "border-red-500 focus-visible:ring-red-500" : ""}
              `}
              {...register("email")}
            />
            {errors.email && (
              <p className="text-red-400 text-xs">{errors.email.message}</p>
            )}
          </div>

          {/* ── Password ── */}
          <div className="space-y-1.5">
            <Label htmlFor="password" className="text-slate-300 text-sm font-medium">
              Password
            </Label>
            <div className="relative">
              <Input
                id="password"
                type={showPassword ? "text" : "password"}
                placeholder="Min. 6 characters"
                autoComplete="new-password"
                disabled={isLoading}
                className={`
                  bg-slate-900/60 border-slate-600 text-white placeholder:text-slate-500
                  focus-visible:ring-emerald-500 focus-visible:border-emerald-500 pr-10
                  ${errors.password ? "border-red-500 focus-visible:ring-red-500" : ""}
                `}
                {...register("password")}
              />
              <button
                type="button"
                onClick={() => setShowPassword((p) => !p)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-300 transition-colors"
                tabIndex={-1}
              >
                {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
              </button>
            </div>
            {errors.password && (
              <p className="text-red-400 text-xs">{errors.password.message}</p>
            )}
          </div>

          {/* ── Confirm Password ── */}
          <div className="space-y-1.5">
            <Label htmlFor="confirm_password" className="text-slate-300 text-sm font-medium">
              Confirm password
            </Label>
            <div className="relative">
              <Input
                id="confirm_password"
                type={showConfirm ? "text" : "password"}
                placeholder="Re-enter your password"
                autoComplete="new-password"
                disabled={isLoading}
                className={`
                  bg-slate-900/60 border-slate-600 text-white placeholder:text-slate-500
                  focus-visible:ring-emerald-500 focus-visible:border-emerald-500 pr-10
                  ${errors.confirm_password ? "border-red-500 focus-visible:ring-red-500" : ""}
                `}
                {...register("confirm_password")}
              />
              <button
                type="button"
                onClick={() => setShowConfirm((p) => !p)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-300 transition-colors"
                tabIndex={-1}
              >
                {showConfirm ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
              </button>
            </div>
            {errors.confirm_password && (
              <p className="text-red-400 text-xs">{errors.confirm_password.message}</p>
            )}
          </div>

          {/* ── Submit Button ── */}
          <Button
            type="submit"
            disabled={isLoading}
            className="w-full bg-emerald-600 hover:bg-emerald-500 text-white font-semibold h-11 transition-all shadow-lg shadow-emerald-900/40 mt-2"
          >
            {isLoading ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Creating account…
              </>
            ) : (
              "Create account"
            )}
          </Button>
        </form>
      </CardContent>

      {/* ── Card Footer ── */}
      <CardFooter className="flex justify-center pt-0 pb-6">
        <p className="text-sm text-slate-400">
          Already have an account?{" "}
          <Link
            href="/login"
            className="text-emerald-400 hover:text-emerald-300 font-medium transition-colors"
          >
            Sign in
          </Link>
        </p>
      </CardFooter>
    </Card>
  );
}
