// src/app/(auth)/login/page.tsx
// ─────────────────────────────────────────────────────────────────────────────
// Login Page
//
// API call: POST {{base_url}}/ads/login
// Body: { email, password, device_name: "web" }
//
// On success:
//   → saves token via saveToken() (localStorage + cookie)
//   → redirects to /dashboard
// ─────────────────────────────────────────────────────────────────────────────

"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 } 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";
import Image from "next/image";
// import axiosInstance from '@/lib/axios';

// ─── Validation Schema ────────────────────────────────────────────────────────
const loginSchema = z.object({
    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"),
});

// Infer the TypeScript type from the schema
type LoginFormValues = z.infer<typeof loginSchema>;

// ─── Component ────────────────────────────────────────────────────────────────
export default function LoginPage() {
    const router = useRouter();
    const [showPassword, setShowPassword] = useState(false);
    const [serverError, setServerError] = useState<string | null>(null);
    const [isLoading, setIsLoading] = useState(false);

    // Set up react-hook-form with zod validation
    const {
        register,
        handleSubmit,
        formState: { errors },
    } = useForm<LoginFormValues>({
        resolver: zodResolver(loginSchema),
        defaultValues: { email: "", password: "" },
    });

    // Called when the form passes validation
    const onSubmit = async (values: LoginFormValues) => {
        setIsLoading(true);
        setServerError(null);

        try {
            // POST to your API endpoint
            const response = await axios.post(
                `${process.env.NEXT_PUBLIC_API_BASE_URL}/ads/login`,
                {
                    email: values.email,
                    password: values.password,
                    device_name: "web", // always "web" for browser clients
                }
            );

            // ── Extract token ──────────────────────────────────────────────────────
            // Adjust the path below to match your actual API response structure.
            // Common patterns:
            //   response.data.token
            //   response.data.data.token
            //   response.data.access_token
            const token =
                response.data?.token ||
                response.data?.data?.token ||
                response.data?.access_token;

            if (!token) {
                setServerError("Login failed: no token received from server.");
                return;
            }

            // Save to localStorage (for Axios) and cookie (for middleware)
            saveToken(token);

            // Redirect to the main app
            router.push("/dashboard");
            router.refresh(); // Sync server components with new auth state

        } catch (error: unknown) {
            // Show the API error message or a fallback
            if (axios.isAxiosError(error)) {
                const msg =
                    error.response?.data?.message ||
                    error.response?.data?.error ||
                    "Incorrect email or password.";
                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" >
                {/* Logo / Brand mark */}
                < div className="flex justify-center mb-2" >
                <Image src="/logo.svg" alt="logo" width={220} height={25} />
                    {/* <div className="w-10 h-10 rounded-xl bg-emerald-500 flex items-center justify-center shadow-lg shadow-emerald-500/30" >
                        <LogIn className="w-5 h-5 text-white" />
                    </div> */}
                </div>
                < CardTitle className="text-2xl font-bold text-center text-white" >
                    Ads Manager
                </CardTitle>
                < CardDescription className="text-center text-slate-400" >
                    Sign in to your account to continue
                </CardDescription>
            </CardHeader>

            {/* ── Card Body / Form ── */}
            <CardContent className="pb-6">
                <form onSubmit={handleSubmit(onSubmit)} noValidate className="space-y-5" >

                    {/* 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>
                        )
                    }

                    {/* ── 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" >
                        <div className="flex items-center justify-between" >
                            <Label htmlFor="password" className="text-slate-300 text-sm font-medium" >
                                Password
                            </Label>
                            {/* Forgot password link — hook this up to your reset flow */}
                            {/* <Link
                                href="#"
                                className="text-xs text-emerald-400 hover:text-emerald-300 transition-colors"
                            >
                                Forgot password ?
                            </Link> */}
                        </div>

                        {/* Password input with show/hide toggle */}
                        <div className="relative" >
                            <Input
                                id="password"
                                type={showPassword ? "text" : "password"}
                                placeholder="••••••••"
                                autoComplete="current-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")}
                            />
                            {/* Toggle visibility button */}
                            <button
                                type="button"
                                onClick={() => setShowPassword((prev) => !prev)}
                                className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-300 transition-colors"
                                tabIndex={- 1}
                            // label={showPassword ? "Hide password" : "Show password"} 
                            >
                                {
                                    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>

                    {/* ── 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"
                    >
                        {
                            isLoading ? (
                                <>
                                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                                    Signing in…
                                </>
                            ) : (
                                "Sign in"
                            )}
                    </Button>
                </form>
            </CardContent>

            {/* ── Card Footer ── */}
            {/* <CardFooter className="flex justify-center pt-0 pb-6 " >
                <p className="text-sm text-slate-400" >
                    Don&apos;t have an account ? {" "}
                    < Link
                        href="/register"
                        className="text-emerald-400 hover:text-emerald-300 font-medium transition-colors"
                    >
                        Create now
                    </Link>
                </p>
            </CardFooter> */}
        </Card >
    );
}