"use client";

import { useState, useEffect } from "react";
import { useForm, UseFormRegister } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
  Mail,
  Lock,
  Eye,
  EyeOff,
  ArrowRight,
  ArrowLeft,
  MapPin,
  User,
} from "lucide-react";
import Link from "next/link";

/* ─── Schema ─── */
export const loginSchema = z.object({
  identifier: z.string().min(1, "Email atau username wajib diisi"),
  password: z.string().min(1, "Password wajib diisi"),
  remember: z.boolean().optional(),
});
export type LoginFormValues = z.infer<typeof loginSchema>;

/* ─── Slides ─── */
const SLIDES = [
  {
    img: "https://images.unsplash.com/photo-1537996194471-e657df975ab4?auto=format&fit=crop&w=2000&q=80",
    location: "Bali, Indonesia",
    emoji: "🌴",
    tag: "Destinasi Favorit",
  },
  {
    img: "https://images.unsplash.com/photo-1520250497591-112f2f40a3f4?auto=format&fit=crop&w=2000&q=80",
    location: "Maladewa",
    emoji: "🏝️",
    tag: "Surga Tersembunyi",
  },
  {
    img: "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?auto=format&fit=crop&w=2000&q=80",
    location: "Swiss Alps",
    emoji: "🏔️",
    tag: "Petualangan Seru",
  },
];



/* ─── LoginCard ─── */
export interface LoginCardProps {
  identifierType: "identifier" | "email";
  redirectTo: string;
  showRegisterLink?: boolean;
  successMessage?: string | null;
  onLogin: (values: LoginFormValues) => Promise<string | null>;
}

export function LoginCard({ identifierType, showRegisterLink, successMessage, onLogin }: LoginCardProps) {
  const [formError, setFormError] = useState<string | null>(null);
  const [showPassword, setShowPassword] = useState(false);
  const [activeSlide, setActiveSlide] = useState(0);

  useEffect(() => {
    const t = setInterval(() => setActiveSlide((p) => (p + 1) % SLIDES.length), 5500);
    return () => clearInterval(t);
  }, []);

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = useForm<LoginFormValues>({ resolver: zodResolver(loginSchema) });

  const onSubmit = async (v: LoginFormValues) => {
    setFormError(null);
    const err = await onLogin(v);
    if (err) setFormError(err);
  };

  const isEmail = identifierType === "email";
  const slide = SLIDES[activeSlide];

  return (
    <div className="flex min-h-screen w-full bg-[#fdf8f5]">

      {/* ═══════════ LEFT — Cheerful Photo Panel ═══════════ */}
      <div className="relative hidden lg:flex flex-col w-2/3 overflow-hidden">

        {/* Slideshow */}
        {SLIDES.map((s, i) => (
          <div
            key={i}
            className="absolute inset-0 bg-cover bg-center transition-opacity duration-[1200ms]"
            style={{ backgroundImage: `url('${s.img}')`, opacity: i === activeSlide ? 1 : 0 }}
          />
        ))}

        {/* Light warm overlay — keep photo visible and bright */}
        <div className="absolute inset-0 bg-gradient-to-br from-black/40 via-black/20 to-black/10" />
        <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent" />

        {/* Content */}
        <div className="relative z-10 flex flex-col h-full px-12 py-10">

          {/* Logo */}
          <Link href="/" className="flex items-center gap-3 w-fit group">
            <div className="w-11 h-11 rounded-2xl bg-white flex items-center justify-center shadow-lg shadow-black/20 group-hover:scale-105 transition-transform">
              <span className="text-[#c62828] font-black text-xl">R</span>
            </div>
            <div>
              <p className="text-white font-black text-[21px] leading-none drop-shadow-md">
                Ranata<span className="text-white/70 font-semibold">Tour</span>
              </p>
              <p className="text-white/60 text-[10px] tracking-widest uppercase mt-0.5">
                Jelajahi Dunia
              </p>
            </div>
          </Link>

          {/* Center hero text */}
          <div className="mt-auto mb-auto pt-24">
            {/* Location tag */}
            <div className="flex items-center gap-2 mb-6">
              <span className="text-2xl">{slide.emoji}</span>
              <span className="bg-white/20 backdrop-blur-md border border-white/30 text-white text-[12px] font-bold px-4 py-1.5 rounded-full">
                {slide.tag}
              </span>
            </div>

            <h2 className="text-5xl xl:text-[58px] font-black text-white leading-[1.05] tracking-tight mb-5 drop-shadow-lg max-w-[480px]">
              Petualangan<br />
              Terbaik<br />
              <span className="text-[#ffcc02] drop-shadow-none" style={{ textShadow: "0 2px 12px rgba(0,0,0,0.3)" }}>
                Menanti Anda!
              </span>
            </h2>

            <p className="text-white/75 text-[16px] leading-relaxed max-w-[380px] mb-10 drop-shadow-sm">
              Bergabung bersama jutaan wisatawan yang telah menemukan pengalaman tak terlupakan bersama Ranata Tour.
            </p>


          </div>

          {/* Bottom: slide dots + location */}
          <div className="flex items-center gap-3">
            {SLIDES.map((_, i) => (
              <button
                key={i}
                onClick={() => setActiveSlide(i)}
                className={`rounded-full transition-all duration-500 ${
                  i === activeSlide
                    ? "w-8 h-1.5 bg-white"
                    : "w-3 h-1.5 bg-white/35 hover:bg-white/60"
                }`}
              />
            ))}
            <div className="ml-2 flex items-center gap-1.5">
              <MapPin className="w-3 h-3 text-white/70" strokeWidth={2} />
              <span className="text-white/70 text-[12px] font-semibold">{slide.location}</span>
            </div>
          </div>
        </div>
      </div>

      {/* ═══════════ RIGHT — Form Panel ═══════════ */}
      <div className="w-full lg:w-1/3 flex-shrink-0 bg-[#fdf8f5] flex flex-col relative overflow-hidden">

        {/* Decorative colorful blobs in corners */}
        <div className="absolute -top-20 -right-20 w-56 h-56 rounded-full bg-orange-200/50 blur-[70px] pointer-events-none" />
        <div className="absolute -bottom-20 -left-20 w-56 h-56 rounded-full bg-red-200/40 blur-[70px] pointer-events-none" />
        <div className="absolute top-1/2 -right-10 w-32 h-32 rounded-full bg-yellow-200/40 blur-[50px] pointer-events-none" />

        {/* Top decorative pattern dots */}
        <div className="absolute top-0 right-0 w-48 h-48 opacity-[0.06] pointer-events-none"
          style={{
            backgroundImage: "radial-gradient(circle, #c62828 1.5px, transparent 1.5px)",
            backgroundSize: "18px 18px",
          }}
        />

        <div className="relative z-10 flex flex-col flex-1 justify-center px-8 sm:px-12 py-10">

          {/* Mobile logo */}
          <Link href="/" className="flex items-center gap-2.5 mb-10 lg:hidden">
            <div className="w-10 h-10 rounded-2xl bg-white shadow-md flex items-center justify-center">
              <span className="text-[#c62828] font-black text-lg">R</span>
            </div>
            <span className="text-slate-800 font-black text-[20px]">
              Ranata<span className="text-slate-400 font-semibold">Tour</span>
            </span>
          </Link>

          {/* Back link */}
          <Link
            href="/"
            className="hidden lg:inline-flex items-center gap-2 text-slate-400 hover:text-[#c62828] text-[12px] font-semibold transition-colors mb-10 w-fit group"
          >
            <ArrowLeft className="w-3.5 h-3.5 group-hover:-translate-x-0.5 transition-transform" />
            Kembali ke Beranda
          </Link>

          {/* Heading */}
          <div className="mb-7">
            <h1 className="text-[30px] font-black text-slate-800 tracking-tight leading-tight mb-2">
              Halo, Selamat Datang! 👋
            </h1>
            <p className="text-[14px] text-slate-400 leading-relaxed">
              {showRegisterLink ? (
                <>
                  Belum punya akun?{" "}
                  <Link href="/register" className="text-[#c62828] font-bold hover:underline transition-colors">
                    Daftar gratis sekarang →
                  </Link>
                </>
              ) : (
                "Masuk untuk melanjutkan perjalanan Anda."
              )}
            </p>
          </div>

          {successMessage && (
            <div className="mb-5 flex items-center gap-3 rounded-2xl bg-green-50 border border-green-200 px-4 py-3.5">
              <span className="text-lg">✅</span>
              <p className="text-[13px] text-green-700 font-semibold">{successMessage}</p>
            </div>
          )}

          {/* Form */}
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate>

            {/* Identifier */}
            <div>
              <label htmlFor="identifier" className="block text-[13px] font-bold text-slate-600 mb-1.5">
                {isEmail ? "Alamat Email" : "Email atau Username"}
              </label>
              <div className="relative">
                <span className="absolute left-4 top-1/2 -translate-y-1/2 pointer-events-none">
                  {isEmail
                    ? <Mail className="w-[17px] h-[17px] text-slate-300" strokeWidth={1.8} />
                    : <User className="w-[17px] h-[17px] text-slate-300" strokeWidth={1.8} />
                  }
                </span>
                <input
                  id="identifier"
                  type={isEmail ? "email" : "text"}
                  autoComplete={isEmail ? "email" : "username"}
                  placeholder={isEmail ? "anda@email.com" : "email atau username Anda"}
                  className={[
                    "w-full h-[52px] rounded-2xl border-2 pl-11 pr-4 text-[14px] text-slate-800",
                    "placeholder:text-slate-300 bg-white outline-none transition-all duration-200",
                    "hover:border-slate-300",
                    "focus:border-[#c62828] focus:shadow-[0_0_0_4px_rgba(198,40,40,0.08)]",
                    errors.identifier
                      ? "border-red-300 bg-red-50"
                      : "border-slate-200",
                  ].join(" ")}
                  {...register("identifier")}
                />
              </div>
              {errors.identifier && (
                <p className="mt-1.5 text-[12px] text-red-500 font-medium">{errors.identifier.message}</p>
              )}
            </div>

            {/* Password */}
            <div>
              <div className="flex items-center justify-between mb-1.5">
                <label htmlFor="password" className="block text-[13px] font-bold text-slate-600">
                  Password
                </label>
                <a href="#" className="text-[12px] text-[#c62828] font-bold hover:underline transition-colors">
                  Lupa password?
                </a>
              </div>
              <div className="relative">
                <span className="absolute left-4 top-1/2 -translate-y-1/2 pointer-events-none">
                  <Lock className="w-[17px] h-[17px] text-slate-300" strokeWidth={1.8} />
                </span>
                <input
                  id="password"
                  type={showPassword ? "text" : "password"}
                  autoComplete="current-password"
                  placeholder="••••••••••••"
                  className={[
                    "w-full h-[52px] rounded-2xl border-2 pl-11 pr-12 text-[16px] text-slate-800",
                    "placeholder:text-slate-300 bg-white outline-none transition-all duration-200",
                    "tracking-[0.18em] font-mono",
                    "hover:border-slate-300",
                    "focus:border-[#c62828] focus:shadow-[0_0_0_4px_rgba(198,40,40,0.08)]",
                    errors.password
                      ? "border-red-300 bg-red-50"
                      : "border-slate-200",
                  ].join(" ")}
                  {...register("password")}
                />
                <button
                  type="button"
                  onClick={() => setShowPassword((v) => !v)}
                  className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-300 hover:text-slate-500 transition-colors focus:outline-none"
                  tabIndex={-1}
                >
                  {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
              </div>
              {errors.password && (
                <p className="mt-1.5 text-[12px] text-red-500 font-medium">{errors.password.message}</p>
              )}
            </div>

            {/* Remember me */}
            <label className="flex items-center gap-2.5 cursor-pointer group/check w-fit pt-1">
              <input
                type="checkbox"
                className="w-4 h-4 rounded-md border-slate-200 text-[#c62828] focus:ring-[#c62828] focus:ring-offset-0 cursor-pointer"
                {...register("remember")}
              />
              <span className="text-[13px] text-slate-400 group-hover/check:text-slate-600 transition-colors select-none font-medium">
                Ingat saya selama 7 hari
              </span>
            </label>

            {/* Error */}
            {formError && (
              <div className="flex items-center gap-3 rounded-2xl bg-red-50 border border-red-200 px-4 py-3.5">
                <span className="text-lg">⚠️</span>
                <p className="text-[13px] text-red-600 font-semibold">{formError}</p>
              </div>
            )}

            {/* Submit button */}
            <button
              type="submit"
              disabled={isSubmitting}
              className="relative w-full h-[54px] overflow-hidden rounded-2xl text-[15px] font-bold text-white transition-all duration-300 group/btn disabled:opacity-60 disabled:cursor-not-allowed mt-2"
              style={{
                background: "linear-gradient(135deg, #ff6b35 0%, #c62828 55%, #b71c1c 100%)",
                boxShadow: "0 6px 20px rgba(198,40,40,0.30), 0 2px 8px rgba(0,0,0,0.08)",
              }}
            >
              {/* Hover lift */}
              <span className="absolute inset-0 bg-white/0 group-hover/btn:bg-white/8 transition-colors duration-200" />
              {/* Shimmer */}
              <span className="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent -translate-x-full group-hover/btn:translate-x-full transition-transform duration-700 ease-in-out" />
              <span className="relative flex items-center justify-center gap-2">
                {isSubmitting ? (
                  <>
                    <svg className="animate-spin w-4 h-4" viewBox="0 0 24 24" fill="none">
                      <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                      <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z" />
                    </svg>
                    Memproses...
                  </>
                ) : (
                  <>
                    Masuk Sekarang
                    <ArrowRight className="w-4 h-4 group-hover/btn:translate-x-1 transition-transform" />
                  </>
                )}
              </span>
            </button>
          </form>



          {/* Footer */}
          <p className="text-center text-[11px] text-slate-300 mt-8 font-medium">
            © 2024 <span className="text-slate-400 font-semibold">Ranata Tour</span>. Seluruh hak dilindungi.
          </p>
        </div>
      </div>
    </div>
  );
}
