"use client";

import Image from "next/image";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Eye, EyeOff, Lock, Mail } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { useToast } from "@/components/ui/toast";
import { loginSuperAdmin } from "@/lib/auth/client";
import { getSuperAdminSession } from "@/lib/api/superadmin";

function OudelaaMark() {
  return (
    <div className="flex items-center justify-center">
      <Image
        src="/logo.png"
        alt="Oudelaa Logo"
        width={144}
        height={144}
        priority
        className="h-36 w-36 object-contain drop-shadow-[0_14px_30px_rgba(0,0,0,0.25)]"
      />
    </div>
  );
}

export default function LoginPage() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();
  const router = useRouter();

  useEffect(() => {
    void getSuperAdminSession()
      .then(() => {
        router.replace("/dashboard");
      })
      .catch(() => {});
  }, [router]);

  const onSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    setLoading(true);
    try {
      await loginSuperAdmin(email, password);
      toast({ title: "تم تسجيل الدخول", description: "مرحبًا بك في لوحة SuperAdmin.", variant: "success" });
      router.replace("/dashboard");
    } catch (error) {
      toast({ title: "فشل تسجيل الدخول", description: String(error), variant: "danger" });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-shell login-theme flex min-h-screen items-center justify-center p-6">
      <div className="grid w-full max-w-5xl gap-8 lg:grid-cols-[1.05fr_0.95fr]">
        <Card className="login-card order-2 lg:order-1">
          <CardContent className="space-y-7 p-9 text-right">
            <div className="space-y-2">
              <p className="text-xs uppercase tracking-[0.35em] text-muted-foreground">Oudelaa SuperAdmin</p>
              <h1 className="font-heading text-3xl font-bold text-[rgb(88,61,36)]">بوابة الإدارة العليا</h1>
              <p className="text-xm text-muted-foreground">
                تحكم فخم في التجربة الموسيقية. ادخل لإدارة المستخدمين، المحتوى، والقرارات الحساسة بأمان.
              </p>
            </div>
            <div className="gold-divider" />
            <form className="space-y-4" onSubmit={onSubmit}>
              <div className="space-y-2">
                <label className="text-xm text-muted-foreground">البريد الإلكتروني</label>
                <div className="relative">
                  <Mail className="pointer-events-none absolute right-3 top-3 h-4 w-4 text-muted-foreground" />
                  <Input
                    className="pr-9"
                    type="email"
                    placeholder="superadmin@oudelaa.com"
                    value={email}
                    onChange={(event) => setEmail(event.target.value)}
                  />
                </div>
              </div>
              <div className="space-y-2">
                <label className="text-xm text-muted-foreground">كلمة المرور</label>
                <div className="relative">
                  <Lock className="pointer-events-none absolute right-3 top-3 h-4 w-4 text-muted-foreground" />
                  <Input
                    type={showPassword ? "text" : "password"}
                    className="pr-9 pl-10"
                    value={password}
                    onChange={(event) => setPassword(event.target.value)}
                  />
                  <button
                    type="button"
                    className="absolute left-3 top-3 text-muted-foreground hover:text-foreground"
                    onClick={() => setShowPassword((prev) => !prev)}
                    aria-label={showPassword ? "إخفاء كلمة المرور" : "إظهار كلمة المرور"}
                  >
                    {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </button>
                </div>
              </div>
              <div className="flex items-center justify-between text-xs text-muted-foreground">
                <span>تسجيل دخول آمن بتوثيق SuperAdmin</span>
                <span>{new Intl.DateTimeFormat("ar-SA", { dateStyle: "medium" }).format(new Date())}</span>
              </div>
              <Button className="w-full text-base" type="submit" disabled={loading}>
                {loading ? "جارٍ التحقق..." : "دخول اللوحة"}
              </Button>
            </form>
          </CardContent>
        </Card>

        <div className="login-card order-1 flex flex-col justify-between p-9 lg:order-2">
          <div className="space-y-5">
            <OudelaaMark />
            <div className="text-center">
              <h2 className="font-heading text-2xl font-bold text-[rgb(88,61,36)]">
                <b>Oudelaa</b>
              </h2>
              <p className="text-sm text-muted-foreground">Heritage Music Command Suite</p>
            </div>
          </div>
          <div className="space-y-4 text-sm text-muted-foreground">
            <div className="rounded-2xl border border-border/70 bg-secondary/50 p-4">
              <p className="text-xl uppercase tracking-[0.2em] text-primary">
                <b>جلسة إشراف</b>
              </p>
              <p className="mt-2 text-sm text-foreground">بوابة الإدارة العليا مخصصة للعمليات الحساسة ومراجعة المنصة بالكامل.</p>
              <p className="mt-1 text-xs">استخدم حساب SuperAdmin الصحيح دون بيانات افتراضية محفوظة داخل الواجهة.</p>
            </div>
            <div className="grid gap-3 sm:grid-cols-2">
              <div className="rounded-2xl border border-border/70 bg-secondary/30 p-3">
                <p className="text-xm text-muted-foreground">البيئة</p>
                <p className="mt-1 text-sm text-foreground">Connected API</p>
              </div>
              <div className="rounded-2xl border border-border/70 bg-secondary/30 p-3">
                <p className="text-xm text-muted-foreground">الحالة</p>
                <p className="mt-1 text-sm text-foreground">Secure</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
