"use client";

import React, { useState } from "react";
import Link from "next/link";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import {
  Mail,
  Lock,
  Eye,
  EyeOff,
  ArrowRight,
  Loader2,
  Award,
  GraduationCap,
  Users,
  Settings,
  BookOpen,
  Building,
  ChefHat,
  UserCog,
  ShieldCheck,
} from "lucide-react";
import { useAuth } from "@/context/auth-context";
import { toast } from "sonner";

const loginSchema = z.object({
  identifier: z.string().min(1, "Please enter your username or email"),
  password: z.string().min(1, "Please enter your password"),
  rememberMe: z.boolean().optional(),
});

type LoginFormData = z.infer<typeof loginSchema>;

type RoleType = "student" | "faculty" | "dept_admin" | "admin";

export default function LoginPage() {
  const { login, isLoading } = useAuth();
  const [showPassword, setShowPassword] = useState(false);
  const [activeRole, setActiveRole] = useState<RoleType>("student");

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<LoginFormData>({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      identifier: "",
      password: "",
      rememberMe: false,
    },
  });

  const handleRoleSelect = (role: RoleType) => {
    setActiveRole(role);
  };

  const onSubmit = async (data: LoginFormData) => {
    await login({
      identifier: data.identifier,
      password: data.password,
      rememberMe: data.rememberMe,
    });
  };

  const handleSocialLogin = async (provider: "google" | "microsoft") => {
    toast.info(
      `Institutional Single Sign-On (${provider === "google" ? "Google Workspace" : "Microsoft Entra"}) requires your institutional account to be mapped by the administrator.`
    );
  };

  return (
    <div className="min-h-screen w-full flex flex-col lg:flex-row bg-[#FAF8F5] text-slate-800 font-sans selection:bg-[#C8A45D] selection:text-slate-900 overflow-x-hidden">
      {/* ============================================================ */}
      {/* LEFT SECTION: Panoramic Campus + Gold Branding + Highlights  */}
      {/* ============================================================ */}
      <div className="relative w-full lg:w-[54%] min-h-0 lg:min-h-screen flex flex-col justify-between p-6 sm:p-10 lg:p-16 overflow-hidden bg-[#0B1F33]">
        {/* Heritage Campus Background Image */}
        <div
          className="absolute inset-0 bg-cover bg-center transition-transform duration-1000 scale-105"
          style={{ backgroundImage: `url('/images/ihm_campus_bg.jpg')` }}
        />

        {/* Deep Navy Gradient Overlay for optimal contrast */}
        <div className="absolute inset-0 bg-gradient-to-b from-[#0B1F33]/90 via-[#0B1F33]/65 to-[#0B1F33]/85 pointer-events-none" />

        {/* Decorative Golden Curved Edge (Desktop separator) */}
        <div className="hidden lg:block absolute -right-1 top-0 bottom-0 w-24 pointer-events-none overflow-hidden z-20">
          <svg
            viewBox="0 0 100 1000"
            preserveAspectRatio="none"
            className="h-full w-full fill-[#FAF8F5]"
          >
            <path
              d="M0,0 C65,220 85,380 35,520 C-10,640 40,820 100,1000 L100,0 Z"
              className="fill-[#FAF8F5]"
            />
            <path
              d="M0,0 C65,220 85,380 35,520 C-10,640 40,820 100,1000"
              fill="none"
              stroke="#C8A45D"
              strokeWidth="4"
              opacity="0.8"
            />
          </svg>
        </div>

        {/* Top Branding Block */}
        <div className="relative z-10 max-w-lg">
          {/* Institutional Gold Emblem & Typography */}
          <div className="flex flex-col items-start gap-1">
            <div className="w-12 h-12 sm:w-16 sm:h-16 mb-2 flex items-center justify-center rounded-full border-2 border-[#C8A45D] bg-[#0B1F33]/70 backdrop-blur-xs shadow-md">
              <Award className="w-7 h-7 sm:w-9 sm:h-9 text-[#C8A45D]" />
            </div>

            <span className="text-[11px] sm:text-sm font-bold uppercase tracking-[0.2em] text-white">
              Institute of
            </span>
            <span className="text-lg sm:text-2xl lg:text-3xl font-extrabold uppercase tracking-[0.16em] text-white leading-tight">
              Hotel Management
            </span>
            <span className="text-sm sm:text-lg font-bold uppercase tracking-[0.25em] text-white">
              Kolkata
            </span>

            {/* Motto */}
            <div className="pt-1.5 sm:pt-2">
              <span className="text-[10px] sm:text-xs font-semibold tracking-[0.3em] uppercase text-[#C8A45D]">
                Learn • Practice • Excel
              </span>
            </div>
          </div>

          {/* Hero Headline & Subtitle */}
          <div className="mt-5 sm:mt-10 lg:mt-14 space-y-2 sm:space-y-3">
            <h1 className="text-xl sm:text-3xl lg:text-4xl font-extrabold tracking-tight leading-[1.2]" style={{ color: '#ffffff' }}>
              Your Journey to a <br />
              Global Hospitality Career <br />
              <span className="text-[#C8A45D]">Starts Here</span>
            </h1>
            <p className="text-xs sm:text-sm text-slate-200/90 leading-relaxed font-normal max-w-md pt-1">
              Join one of India&apos;s premier hospitality institutes and build a
              successful career in the global hospitality and tourism industry.
            </p>
          </div>
        </div>

        {/* Bottom 4 Feature Badges (Matching screenshot exactly) */}
        <div className="hidden sm:block relative z-10 mt-8 lg:mt-12 pt-4 lg:pt-6 border-t border-white/15 max-w-xl">
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 text-center">
            {/* 1. Infrastructure */}
            <div className="flex flex-col items-center gap-2 p-1">
              <div className="w-9 h-9 rounded-lg flex items-center justify-center text-[#C8A45D]">
                <ChefHat className="w-7 h-7" />
              </div>
              <span className="text-[11px] font-semibold text-white leading-snug">
                World-Class <br /> Infrastructure
              </span>
            </div>

            {/* 2. Curriculum */}
            <div className="flex flex-col items-center gap-2 p-1 border-l sm:border-l border-white/10">
              <div className="w-9 h-9 rounded-lg flex items-center justify-center text-[#C8A45D]">
                <BookOpen className="w-7 h-7" />
              </div>
              <span className="text-[11px] font-semibold text-white leading-snug">
                Industry-Oriented <br /> Curriculum
              </span>
            </div>

            {/* 3. Faculty */}
            <div className="flex flex-col items-center gap-2 p-1 border-l sm:border-l border-white/10">
              <div className="w-9 h-9 rounded-lg flex items-center justify-center text-[#C8A45D]">
                <Users className="w-7 h-7" />
              </div>
              <span className="text-[11px] font-semibold text-white leading-snug">
                Expert <br /> Faculty
              </span>
            </div>

            {/* 4. Placement */}
            <div className="flex flex-col items-center gap-2 p-1 border-l sm:border-l border-white/10">
              <div className="w-9 h-9 rounded-lg flex items-center justify-center text-[#C8A45D]">
                <Building className="w-7 h-7" />
              </div>
              <span className="text-[11px] font-semibold text-white leading-snug">
                Excellent <br /> Placement Support
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* ============================================================ */}
      {/* RIGHT SECTION: Floating Card with 3 Tabs, Form & Social SSO  */}
      {/* ============================================================ */}
      <div className="w-full lg:w-[46%] flex items-center justify-center p-4 sm:p-8 lg:p-12 xl:p-16 relative">
        {/* Subtle Decorative Floral/Chef Background Motif in Corner */}
        <div className="absolute right-0 bottom-0 w-64 h-64 opacity-[0.06] pointer-events-none select-none">
          <ChefHat className="w-full h-full text-[#0B1F33]" />
        </div>

        {/* Centered Floating Login Card */}
        <div className="w-full max-w-[480px] bg-white rounded-2xl border border-slate-200/90 shadow-xl p-5 sm:p-8 lg:p-9 relative z-10">
          {/* Card Title */}
          <div className="mb-6 text-center">
            <h2 className="font-heading font-bold text-2xl sm:text-3xl text-[#0B1F33] tracking-tight">
              Welcome Back
            </h2>
            <div className="w-10 h-0.5 bg-[#C8A45D] mx-auto mt-2 mb-1.5" />
            <p className="text-xs text-slate-500">
              Sign in to your account to continue
            </p>
          </div>

          {/* 4 Role Selection Buttons (Pill Tabs - Matching IHM_UI_Design_Style.md §3) */}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-1.5 p-1.5 bg-slate-50 border border-slate-200 rounded-xl mb-3.5">
            {/* Tab 1: Student / Parent */}
            <button
              type="button"
              onClick={() => handleRoleSelect("student")}
              className={`flex items-center justify-center gap-1 py-2 px-1.5 rounded-lg text-xs font-bold transition-all ${
                activeRole === "student"
                  ? "bg-[#FBF4E4] text-[#8C6D28] border border-[#C8A45D] shadow-xs"
                  : "text-slate-600 hover:text-slate-900 hover:bg-slate-100"
              }`}
            >
              <GraduationCap className="w-3.5 h-3.5 shrink-0" />
              <span className="truncate">Student</span>
            </button>

            {/* Tab 2: Faculty / Staff */}
            <button
              type="button"
              onClick={() => handleRoleSelect("faculty")}
              className={`flex items-center justify-center gap-1 py-2 px-1.5 rounded-lg text-xs font-bold transition-all ${
                activeRole === "faculty"
                  ? "bg-[#FBF4E4] text-[#8C6D28] border border-[#C8A45D] shadow-xs"
                  : "text-slate-600 hover:text-slate-900 hover:bg-slate-100"
              }`}
            >
              <Users className="w-3.5 h-3.5 shrink-0" />
              <span className="truncate">Faculty</span>
            </button>

            {/* Tab 3: Department Administrator */}
            <button
              type="button"
              onClick={() => handleRoleSelect("dept_admin")}
              className={`flex items-center justify-center gap-1 py-2 px-1.5 rounded-lg text-xs font-bold transition-all ${
                activeRole === "dept_admin"
                  ? "bg-[#FBF4E4] text-[#8C6D28] border border-[#C8A45D] shadow-xs"
                  : "text-slate-600 hover:text-slate-900 hover:bg-slate-100"
              }`}
            >
              <UserCog className="w-3.5 h-3.5 shrink-0" />
              <span className="truncate">Dept Admin</span>
            </button>

            {/* Tab 4: Administrator */}
            <button
              type="button"
              onClick={() => handleRoleSelect("admin")}
              className={`flex items-center justify-center gap-1 py-2 px-1.5 rounded-lg text-xs font-bold transition-all ${
                activeRole === "admin"
                  ? "bg-[#FBF4E4] text-[#8C6D28] border border-[#C8A45D] shadow-xs"
                  : "text-slate-600 hover:text-slate-900 hover:bg-slate-100"
              }`}
            >
              <ShieldCheck className="w-3.5 h-3.5 shrink-0" />
              <span className="truncate">Super Admin</span>
            </button>
          </div>

          {/* Contextual Role Scope Badge (Matching IHM_UI_Design_Style.md §3) */}
          <div className="mb-5 p-2.5 rounded-lg bg-amber-50/70 border border-amber-200/80 text-[11px] text-[#785E2F] flex items-start gap-1.5 leading-snug">
            <span className="font-bold shrink-0">Capabilities:</span>
            <span>
              {activeRole === "student" && "Track daily session attendance, subject-wise %, medical adjustments & APR status."}
              {activeRole === "faculty" && "Personalized timetable, student rosters, daily P/A/C attendance marking & APR submission."}
              {activeRole === "dept_admin" && "Academic / Department Administrator: Sessions, courses, semesters, faculty allocation, student groups, timetable, holiday calendar, attendance rules & APR generation."}
              {activeRole === "admin" && "Super Administrator: Full administrative access across all system parameters, RBAC permissions, audit logs & backups."}
            </span>
          </div>

          {/* Form */}
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
            {/* Username / Email Field */}
            <div>
              <label className="block text-xs font-bold text-slate-800 mb-1.5">
                Username / Email
              </label>
              <div className="relative">
                <Mail className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                <input
                  type="text"
                  {...register("identifier")}
                  disabled={isLoading}
                  placeholder="Enter your username or email"
                  className="w-full pl-10 pr-3.5 py-2.5 text-xs sm:text-sm rounded-lg border border-slate-300 bg-white placeholder:text-slate-400 focus:outline-none focus:border-[#C8A45D] focus:ring-2 focus:ring-[#C8A45D]/20 transition-all font-medium text-slate-800"
                />
              </div>
              {errors.identifier && (
                <p className="text-[11px] text-red-600 mt-1 font-medium">
                  {errors.identifier.message}
                </p>
              )}
            </div>

            {/* Password Field */}
            <div>
              <label className="block text-xs font-bold text-slate-800 mb-1.5">
                Password
              </label>
              <div className="relative">
                <Lock className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                <input
                  type={showPassword ? "text" : "password"}
                  {...register("password")}
                  disabled={isLoading}
                  placeholder="Enter your password"
                  className="w-full pl-10 pr-10 py-2.5 text-xs sm:text-sm rounded-lg border border-slate-300 bg-white placeholder:text-slate-400 focus:outline-none focus:border-[#C8A45D] focus:ring-2 focus:ring-[#C8A45D]/20 transition-all font-medium text-slate-800"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 transition-colors"
                  aria-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-[11px] text-red-600 mt-1 font-medium">
                  {errors.password.message}
                </p>
              )}
            </div>

            {/* Remember Me & Forgot Password */}
            <div className="flex items-center justify-between pt-1">
              <label className="flex items-center cursor-pointer select-none">
                <input
                  type="checkbox"
                  {...register("rememberMe")}
                  className="w-4 h-4 rounded border-slate-300 text-[#C8A45D] focus:ring-[#C8A45D] accent-[#C8A45D] cursor-pointer"
                />
                <span className="ml-2 text-xs text-slate-700 font-semibold">
                  Remember me
                </span>
              </label>

              <Link
                href="/forgot-password"
                className="text-xs font-semibold text-blue-600 hover:text-blue-700 hover:underline transition-colors"
              >
                Forgot Password?
              </Link>
            </div>

            {/* Primary Sign In Button (Champagne Gold #C8A45D) */}
            <div className="pt-2">
              <button
                type="submit"
                disabled={isLoading}
                className="w-full py-3 px-4 rounded-lg bg-[#C8A45D] hover:bg-[#b8934c] active:bg-[#a8823b] text-slate-950 font-bold text-sm tracking-wide shadow-md hover:shadow-lg transition-all disabled:opacity-50 flex items-center justify-center gap-2 cursor-pointer"
              >
                {isLoading ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin text-slate-950" />
                    <span>Signing in...</span>
                  </>
                ) : (
                  <>
                    <span>Sign In</span>
                    <ArrowRight className="w-4 h-4" />
                  </>
                )}
              </button>
            </div>
          </form>

          {/* OR Divider */}
          <div className="relative my-5 text-center">
            <div className="absolute inset-0 flex items-center">
              <div className="w-full border-t border-slate-200" />
            </div>
            <span className="relative px-3 bg-white text-[10px] font-bold uppercase tracking-wider text-slate-400">
              OR
            </span>
          </div>

          {/* Social Sign In Buttons: Google & Microsoft */}
          <div className="grid grid-cols-2 gap-2.5">
            {/* Google */}
            <button
              type="button"
              onClick={() => handleSocialLogin("google")}
              disabled={isLoading}
              className="py-2.5 px-3 rounded-lg border border-slate-200 bg-white hover:bg-slate-50 transition-colors flex items-center justify-center gap-2 text-xs font-semibold text-slate-700 shadow-2xs"
            >
              {/* Google 4-color SVG */}
              <svg className="w-4 h-4 shrink-0" viewBox="0 0 24 24">
                <path
                  fill="#4285F4"
                  d="M23.745 12.27c0-.7-.06-1.4-.19-2.07H12v4.51h6.6c-.29 1.52-1.14 2.8-2.4 3.66v3.05h3.88c2.27-2.09 3.665-5.17 3.665-9.15z"
                />
                <path
                  fill="#34A853"
                  d="M12 24c3.24 0 5.95-1.08 7.93-2.91l-3.88-3.05c-1.08.72-2.45 1.16-4.05 1.16-3.12 0-5.77-2.1-6.72-4.93H1.24v3.15C3.26 21.36 7.33 24 12 24z"
                />
                <path
                  fill="#FBBC05"
                  d="M5.28 14.27c-.25-.72-.38-1.49-.38-2.27s.13-1.55.38-2.27V6.58H1.24C.45 8.16 0 9.94 0 12s.45 3.84 1.24 5.42l4.04-3.15z"
                />
                <path
                  fill="#EA4335"
                  d="M12 4.75c1.77 0 3.35.61 4.6 1.8l3.42-3.42C17.95 1.19 15.24 0 12 0 7.33 0 3.26 2.64 1.24 6.58l4.04 3.15c.95-2.83 3.6-4.98 6.72-4.98z"
                />
              </svg>
              <span className="truncate">Sign in with Google</span>
            </button>

            {/* Microsoft */}
            <button
              type="button"
              onClick={() => handleSocialLogin("microsoft")}
              disabled={isLoading}
              className="py-2.5 px-3 rounded-lg border border-slate-200 bg-white hover:bg-slate-50 transition-colors flex items-center justify-center gap-2 text-xs font-semibold text-slate-700 shadow-2xs"
            >
              {/* Microsoft 4-square SVG */}
              <svg className="w-4 h-4 shrink-0" viewBox="0 0 23 23">
                <path fill="#f35325" d="M1 1h10v10H1z" />
                <path fill="#81bc06" d="M12 1h10v10H12z" />
                <path fill="#05a6f0" d="M1 12h10v10H1z" />
                <path fill="#ffba08" d="M12 12h10v10H12z" />
              </svg>
              <span className="truncate">Sign in with Microsoft</span>
            </button>
          </div>

          {/* Contact Institution Link */}
          <div className="text-center pt-5 text-xs text-slate-500 font-medium">
            Don&apos;t have an account?{" "}
            <a
              href="mailto:support@ihmkolkata.ac.in"
              className="text-blue-600 font-bold hover:underline"
            >
              Contact Institution
            </a>
          </div>
        </div>
      </div>
    </div>
  );
}
