"use client";

import React, { useState } from "react";
import { useRouter } from "next/navigation";
import { BACKEND_URL } from "@/lib/api";
import { saveAuthTokens } from "@/lib/auth";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Loader2, ArrowRight, MessageCircle, HelpCircle, Building2 } from "lucide-react";
import Link from "next/link";

export default function LoginPage() {
    const [username, setUsername] = useState("");
    const [password, setPassword] = useState("");
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState("");
    const router = useRouter();

    const handleLogin = async (e: React.FormEvent) => {
        e.preventDefault();
        setLoading(true);
        setError("");

        try {
            const res = await fetch(`${BACKEND_URL}/api/auth/token/`, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ username, password })
            });

            if (res.ok) {
                const data = await res.json();
                saveAuthTokens(data.access, data.refresh);
                router.push("/");
            } else {
                setError("Invalid username or password. Please try again.");
            }
        } catch (err) {
            setError("Failed to connect to authentication server.");
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="min-h-screen flex flex-col items-center justify-center bg-slate-50 relative overflow-hidden px-4 py-12">

            {/* Background decorative blobs */}
            <div className="absolute inset-0 overflow-hidden z-0 pointer-events-none">
                <div className="absolute -top-40 -right-40 w-96 h-96 bg-indigo-100 rounded-full blur-3xl opacity-60" />
                <div className="absolute -bottom-40 -left-40 w-96 h-96 bg-emerald-100 rounded-full blur-3xl opacity-60" />
                <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[600px] bg-violet-50 rounded-full blur-3xl opacity-30" />
            </div>

            {/* === LOGIN CARD === */}
            <Card className="w-full max-w-sm z-10 shadow-2xl border-slate-200/60 rounded-2xl overflow-hidden backdrop-blur-sm bg-slate-50/90">
                {/* Brand gradient bar */}
                <div className="h-1.5 w-full bg-gradient-to-r from-indigo-500 via-violet-500 to-emerald-400" />

                <CardHeader className="space-y-3 pb-6 pt-8 text-center">
                    {/* App icon */}
                    <div className="w-14 h-14 bg-gradient-to-br from-indigo-500 to-violet-600 text-white rounded-2xl flex items-center justify-center mx-auto mb-1 shadow-lg shadow-indigo-500/30">
                        <Building2 className="w-7 h-7" />
                    </div>
                    <CardTitle className="text-xl font-black tracking-tight text-slate-900">
                        Property Management
                    </CardTitle>
                    <CardDescription className="text-slate-500 font-medium">
                        Secure staff authentication portal
                    </CardDescription>
                </CardHeader>

                <CardContent className="pb-8">
                    <form onSubmit={handleLogin} className="space-y-4">
                        {error && (
                            <div className="bg-red-50 text-red-600 text-sm p-3 rounded-xl border border-red-100 font-medium">
                                {error}
                            </div>
                        )}
                        <div className="space-y-2">
                            <Label htmlFor="username" className="text-slate-700 font-semibold text-sm">Username</Label>
                            <Input
                                id="username"
                                autoComplete="username"
                                placeholder="Enter your username"
                                value={username}
                                onChange={(e) => setUsername(e.target.value)}
                                required
                                className="bg-white border-slate-300 hover:border-slate-400 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20 focus:shadow-sm h-11 rounded-xl text-slate-800 placeholder:text-slate-400 transition-all"
                            />
                        </div>
                        <div className="space-y-2">
                            <Label htmlFor="password" className="text-slate-700 font-semibold text-sm">Password</Label>
                            <Input
                                id="password"
                                type="password"
                                autoComplete="current-password"
                                placeholder="••••••••"
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                                required
                                className="bg-white border-slate-300 hover:border-slate-400 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20 focus:shadow-sm h-11 rounded-xl text-slate-800 placeholder:text-slate-400 transition-all"
                            />
                        </div>
                        <Button
                            type="submit"
                            disabled={loading}
                            className="w-full h-11 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl shadow-md shadow-indigo-500/20 transition-all active:scale-95 mt-2 font-bold"
                        >
                            {loading
                                ? <Loader2 className="w-5 h-5 animate-spin mx-auto" />
                                : <span className="flex items-center justify-center gap-2">Sign In <ArrowRight className="w-4 h-4" /></span>
                            }
                        </Button>
                    </form>

                    {/* Divider + quick links inside the card */}
                    <div className="mt-6 pt-5 border-t border-slate-100 flex flex-col gap-2.5">
                        <a
                            href="https://wa.me/2349164601810"
                            target="_blank"
                            rel="noopener noreferrer"
                            className="flex items-center justify-center gap-2 w-full h-10 rounded-xl border border-emerald-200 bg-emerald-50 text-emerald-700 hover:bg-emerald-100 transition-all text-sm font-bold"
                        >
                            <MessageCircle className="w-4 h-4" />
                            Contact Developer on WhatsApp
                        </a>
                        <Link
                            href="/contact"
                            className="flex items-center justify-center gap-2 w-full h-10 rounded-xl border border-slate-200 bg-slate-50 text-slate-600 hover:bg-slate-100 transition-all text-sm font-semibold"
                        >
                            <HelpCircle className="w-4 h-4" />
                            Help Center &amp; Feature Guide
                        </Link>
                    </div>
                </CardContent>
            </Card>

            {/* Footer below card */}
            <p className="z-10 mt-5 text-center text-xs text-slate-400 font-medium">
                &copy; {new Date().getFullYear()} Contract Management System. All rights reserved.
            </p>
        </div>
    );
}
