import { useState } from "react";
import { useNavigate } from "react-router-dom";
import {
  Eye,
  EyeOff,
  LogIn,
  Leaf,
  ShieldCheck,
  Building2,
  School,
  Landmark,
  Sparkles,
  Truck,
  UtensilsCrossed,
  ArrowRight,
  PackageCheck,
  ClipboardList,
  MapPin,
  BadgeCheck,
} from "lucide-react";

const roleCards = [
  {
    label: "Admin",
    username: "admin",
    password: "admin123",
    icon: ShieldCheck,
  },
  {
    label: "SPPG",
    username: "sppg",
    password: "sppg123",
    icon: Building2,
  },
  {
    label: "Validator",
    username: "validator",
    password: "validator123",
    icon: School,
  },
  {
    label: "Pemerintah",
    username: "pemerintah",
    password: "pemerintah123",
    icon: Landmark,
  },
];

const sppgDetails = [
  {
    icon: Building2,
    title: "SPPG Terdata",
    desc: "Profil, wilayah, status, dan penerima manfaat tercatat dalam sistem.",
  },
  {
    icon: PackageCheck,
    title: "Omprengan & Bahan",
    desc: "Inventaris dapur, stok bahan, dan perlengkapan distribusi ikut dipantau.",
  },
  {
    icon: ClipboardList,
    title: "Laporan Operasional",
    desc: "Porsi harian, kendala distribusi, dan penggunaan dana dapat dievaluasi.",
  },
];

export default function Login() {
  const navigate = useNavigate();

  const [username, setUsername] = useState("admin");
  const [password, setPassword] = useState("admin123");
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  const redirectByRole = (role) => {
    if (role === "admin") {
      navigate("/admin");
    } else if (role === "sppg") {
      navigate("/sppg");
    } else if (role === "validator") {
      navigate("/validator");
    } else if (role === "pemerintah") {
      navigate("/pemerintah");
    } else if (role === "masyarakat") {
      navigate("/");
    } else {
      navigate("/login");
    }
  };

  const handleUseDemo = (item) => {
    setUsername(item.username);
    setPassword(item.password);
    setError("");
  };

     const handleLogin = async (e) => {
  e.preventDefault();

  setError("");
  setLoading(true);

  try {
    const res = await fetch("https://openplate.my.id/api/login.php", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Accept": "application/json",
      },
      body: JSON.stringify({
        username: username?.trim(),
        password: password,
      }),
    });

    // 1. Cek status HTTP
    if (!res) {
      throw new Error("No response from server");
    }

    if (res.status === 0) {
      throw new Error("Network error / CORS / server unreachable");
    }

    if (res.status === 401) {
      throw new Error("401 Unauthorized - Username atau password salah");
    }

    if (res.status === 403) {
      throw new Error("403 Forbidden - Akses ditolak oleh server");
    }

    if (res.status === 404) {
      throw new Error("404 Not Found - API login tidak ditemukan");
    }

    if (res.status >= 500) {
      throw new Error(`Server error ${res.status} - masalah di backend`);
    }

    // 2. Ambil response text dulu (buat debugging JSON error)
    const text = await res.text();

    let data;
    try {
      data = JSON.parse(text);
    } catch (err) {
      console.error("Response bukan JSON valid:", text);
      throw new Error("Server tidak mengembalikan JSON valid");
    }

    // 3. Validasi struktur API
    if (!data) {
      throw new Error("Response kosong dari server");
    }

    if (typeof data.success === "undefined") {
      throw new Error("Format API salah: field 'success' tidak ada");
    }

    if (!data.success) {
      throw new Error(data.message || "Login gagal (tanpa pesan dari server)");
    }

    if (!data.data) {
      throw new Error("Data user tidak ditemukan di response");
    }

    if (!data.data.token) {
      throw new Error("Token tidak ditemukan dari server");
    }

    // 4. Simpan session
    localStorage.setItem("token", data.data.token);
    localStorage.setItem("role", data.data.role || "");
    localStorage.setItem("username", data.data.username || "");
    localStorage.setItem("user_id", data.data.id || "");

    // 5. Redirect
    redirectByRole(data.data.role);

  } catch (error) {
    console.error("LOGIN ERROR DETAIL:", {
      message: error.message,
      stack: error.stack,
    });

    setError(
      error.message ||
      "Tidak bisa terhubung ke server (unknown error)"
    );

  } finally {
    setLoading(false);
  }
};

  return (
    <div className="relative min-h-screen overflow-hidden bg-slate-950 px-4 py-8">
      <div className="absolute inset-0 bg-gradient-to-br from-sky-950 via-blue-900 to-cyan-900" />
      <div className="absolute -left-10 top-16 h-56 w-56 rounded-full bg-sky-400/20 blur-3xl animate-pulse" />
      <div className="absolute right-0 top-24 h-72 w-72 rounded-full bg-blue-300/20 blur-3xl animate-pulse" />
      <div className="absolute bottom-10 left-1/3 h-64 w-64 rounded-full bg-cyan-300/10 blur-3xl animate-pulse" />

      <div className="absolute inset-0 opacity-10 [background-image:linear-gradient(rgba(255,255,255,0.2)_1px,transparent_1px),linear-gradient(90deg,rgba(255,255,255,0.2)_1px,transparent_1px)] [background-size:40px_40px]" />

      <div className="pointer-events-none absolute left-0 right-0 top-20 hidden h-36 overflow-hidden lg:block">
        <div className="absolute left-[-18rem] top-8 flex animate-[drive_16s_linear_infinite] items-center gap-4">
          <div
            className="relative h-16 w-36 rounded-2xl border border-sky-200/70 bg-white/95 shadow-2xl"
            style={{ animation: "neonPulse 2.2s ease-in-out infinite" }}
          >
            <div className="absolute inset-0 rounded-2xl bg-sky-400/15 blur-xl" />

            <div
              className="absolute -left-16 bottom-2 h-3 w-16 origin-right rounded-full bg-cyan-300/40 blur-md"
              style={{ animation: "neonTrail 1.8s ease-in-out infinite" }}
            />

            <div className="absolute inset-x-2 -bottom-1 h-3 rounded-full bg-cyan-300/40 blur-md" />

            <div className="absolute left-3 top-3 h-8 w-14 rounded-lg border border-sky-200/80 bg-gradient-to-br from-sky-200 to-cyan-100 shadow-inner" />

            <div className="absolute left-3 bottom-3 h-1.5 w-20 rounded-full bg-gradient-to-r from-sky-400 to-blue-500 shadow-[0_0_10px_rgba(59,130,246,0.8)]" />

            <div className="absolute right-3 top-4 text-xs font-black tracking-wide text-blue-700">
              MBG
            </div>

            <div className="absolute -right-1 top-6 h-3 w-3 rounded-full bg-cyan-300 shadow-[0_0_12px_rgba(34,211,238,0.95),0_0_24px_rgba(56,189,248,0.8)]" />

            <div className="absolute -right-8 bottom-1 h-8 w-10 rounded-lg border border-blue-300/60 bg-gradient-to-br from-sky-500 to-blue-600 shadow-[0_0_14px_rgba(59,130,246,0.55)]" />

            <div
              className="absolute bottom-[-10px] left-6 h-6 w-6 rounded-full border-4 border-slate-900 bg-slate-700"
              style={{ animation: "wheelGlow 1.8s ease-in-out infinite" }}
            />

            <div
              className="absolute bottom-[-10px] right-6 h-6 w-6 rounded-full border-4 border-slate-900 bg-slate-700"
              style={{
                animation: "wheelGlow 1.8s ease-in-out infinite 0.2s",
              }}
            />
          </div>

          {[1, 2, 3].map((item) => (
            <div
              key={item}
              className="flex h-10 w-10 items-center justify-center rounded-xl border border-sky-200/40 bg-white/20 text-white shadow-lg backdrop-blur"
              style={{ animation: "neonPulse 2.4s ease-in-out infinite" }}
            >
              <UtensilsCrossed className="h-5 w-5" />
            </div>
          ))}
        </div>
      </div>

      <style>
        {`
          @keyframes drive {
            0% { transform: translateX(0); }
            100% { transform: translateX(calc(100vw + 36rem)); }
          }

          @keyframes floatBox {
            0%, 100% { transform: translateY(0px) rotate(-2deg); }
            50% { transform: translateY(-12px) rotate(2deg); }
          }

          @keyframes shine {
            0% { transform: translateX(-120%); }
            100% { transform: translateX(220%); }
          }

          @keyframes neonPulse {
            0%, 100% {
              filter: drop-shadow(0 0 6px rgba(56, 189, 248, 0.55))
                      drop-shadow(0 0 12px rgba(59, 130, 246, 0.45))
                      drop-shadow(0 0 20px rgba(14, 165, 233, 0.35));
            }
            50% {
              filter: drop-shadow(0 0 10px rgba(56, 189, 248, 0.9))
                      drop-shadow(0 0 18px rgba(59, 130, 246, 0.75))
                      drop-shadow(0 0 30px rgba(14, 165, 233, 0.55));
            }
          }

          @keyframes wheelGlow {
            0%, 100% {
              box-shadow:
                0 0 0 2px rgba(15, 23, 42, 0.9),
                0 0 8px rgba(56, 189, 248, 0.35);
            }
            50% {
              box-shadow:
                0 0 0 2px rgba(15, 23, 42, 0.9),
                0 0 16px rgba(56, 189, 248, 0.7),
                0 0 28px rgba(59, 130, 246, 0.45);
            }
          }

          @keyframes neonTrail {
            0%, 100% {
              opacity: 0.45;
              transform: scaleX(0.9);
            }
            50% {
              opacity: 0.9;
              transform: scaleX(1.05);
            }
          }
        `}
      </style>

      <div className="relative mx-auto grid min-h-[calc(100vh-4rem)] max-w-6xl items-center gap-10 lg:grid-cols-[1.1fr_0.9fr]">
        <div className="hidden text-white lg:block">
          <div className="mb-5 inline-flex items-center gap-2 rounded-full border border-white/20 bg-white/10 px-4 py-2 text-sm font-semibold backdrop-blur-md">
            <Sparkles className="h-4 w-4 text-sky-300" />
            Akses Internal OPEN PLATE
          </div>

          <h1 className="max-w-2xl text-5xl font-black uppercase leading-tight tracking-tight">
            LOGIN KE
            <span className="relative mt-1 block overflow-hidden bg-gradient-to-r from-sky-300 via-cyan-200 to-blue-100 bg-clip-text text-transparent">
              OPEN PLATE MBG
              <span className="absolute inset-y-0 left-0 w-20 -skew-x-12 bg-white/40 blur-sm animate-[shine_3.8s_ease-in-out_infinite]" />
            </span>
          </h1>

          <p className="mt-5 max-w-xl text-base leading-relaxed text-blue-100/90">
            Halaman login ini digunakan oleh admin, operator SPPG, validator,
            dan pemerintah untuk mengelola data operasional MBG. Masyarakat
            dapat langsung mengakses dashboard publik tanpa login.
          </p>

          <div className="relative mt-10 max-w-xl rounded-[2rem] border border-white/15 bg-white/10 p-6 backdrop-blur-md shadow-2xl">
            <div className="absolute -right-5 -top-5 rounded-2xl bg-sky-400/20 p-4 backdrop-blur animate-bounce">
              <Truck className="h-8 w-8 text-sky-100" />
            </div>

            <div className="absolute -bottom-4 right-16 flex h-16 w-16 items-center justify-center rounded-3xl border border-white/20 bg-white/15 text-white shadow-xl backdrop-blur animate-[floatBox_4s_ease-in-out_infinite]">
              <PackageCheck className="h-8 w-8" />
            </div>

            <div className="mb-4 flex items-center gap-3">
              <div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-white/15">
                <Truck className="h-7 w-7 text-white" />
              </div>

              <div>
                <h3 className="text-xl font-bold">Armada & Omprengan MBG</h3>
                <p className="text-sm text-blue-100/80">
                  Distribusi makanan bergizi dipantau melalui data SPPG yang
                  terukur.
                </p>
              </div>
            </div>

            <div className="grid grid-cols-3 gap-3">
              <div className="rounded-2xl bg-white/10 p-4">
                <p className="text-2xl font-black">SPPG</p>
                <p className="mt-1 text-xs text-blue-100/75">Profil dapur</p>
              </div>

              <div className="rounded-2xl bg-white/10 p-4">
                <p className="text-2xl font-black">Live</p>
                <p className="mt-1 text-xs text-blue-100/75">Data monitoring</p>
              </div>

              <div className="rounded-2xl bg-white/10 p-4">
                <p className="text-2xl font-black">MBG</p>
                <p className="mt-1 text-xs text-blue-100/75">
                  Distribusi aktif
                </p>
              </div>
            </div>

            <div className="mt-5 space-y-3">
              {sppgDetails.map((item) => {
                const Icon = item.icon;

                return (
                  <div
                    key={item.title}
                    className="flex items-start gap-3 rounded-2xl border border-white/10 bg-white/10 p-3"
                  >
                    <div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-sky-400/20">
                      <Icon className="h-5 w-5 text-sky-100" />
                    </div>

                    <div>
                      <p className="text-sm font-bold">{item.title}</p>
                      <p className="mt-0.5 text-xs leading-relaxed text-blue-100/75">
                        {item.desc}
                      </p>
                    </div>
                  </div>
                );
              })}
            </div>

            <div className="mt-5 flex items-center gap-2 text-sm text-blue-100/85">
              <MapPin className="h-4 w-4" />
              SPPG dipantau berdasarkan wilayah, penerima, laporan, dan
              distribusi.
            </div>
          </div>
        </div>

        <div className="mx-auto w-full max-w-md">
          <form
            onSubmit={handleLogin}
            className="rounded-[2rem] border border-white/20 bg-white/90 p-6 shadow-2xl shadow-slate-950/40 backdrop-blur-xl sm:p-8"
          >
            <div className="mb-6 text-center">
              <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-3xl bg-gradient-to-br from-sky-500 to-blue-700 text-white shadow-lg shadow-blue-300/40">
                <Leaf className="h-8 w-8" />
              </div>

              <h1 className="text-3xl font-black uppercase tracking-tight text-slate-900">
                LOGIN OPEN PLATE
              </h1>

              <p className="mx-auto mt-2 max-w-xs text-sm leading-relaxed text-slate-500">
                Masuk sebagai admin, SPPG, validator, atau pemerintah untuk
                mengelola sistem OPEN PLATE MBG.
              </p>
            </div>

            {error && (
              <div className="mb-4 rounded-2xl border border-red-200 bg-red-50 px-4 py-3 text-sm font-medium text-red-600">
                {error}
              </div>
            )}

            <div className="mb-4">
              <label className="mb-2 block text-sm font-bold text-slate-700">
                Username
              </label>

              <input
                className="w-full rounded-2xl border border-slate-200 bg-white px-4 py-3 text-sm outline-none transition focus:border-blue-500 focus:ring-4 focus:ring-blue-100"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                placeholder="Masukkan username"
                required
              />
            </div>

            <div className="mb-5">
              <label className="mb-2 block text-sm font-bold text-slate-700">
                Password
              </label>

              <div className="relative">
                <input
                  className="w-full rounded-2xl border border-slate-200 bg-white px-4 py-3 pr-12 text-sm outline-none transition focus:border-blue-500 focus:ring-4 focus:ring-blue-100"
                  type={showPassword ? "text" : "password"}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="Masukkan password"
                  required
                />

                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-500 transition hover:text-slate-900"
                  aria-label={
                    showPassword ? "Sembunyikan password" : "Tampilkan password"
                  }
                >
                  {showPassword ? (
                    <EyeOff className="h-4 w-4" />
                  ) : (
                    <Eye className="h-4 w-4" />
                  )}
                </button>
              </div>
            </div>

            <button
              type="submit"
              disabled={loading}
              className="inline-flex w-full items-center justify-center gap-2 rounded-2xl bg-gradient-to-r from-sky-600 to-blue-700 px-4 py-3 text-sm font-bold text-white shadow-lg shadow-blue-300/30 transition hover:from-sky-700 hover:to-blue-800 disabled:cursor-not-allowed disabled:opacity-70"
            >
              <LogIn className="h-4 w-4" />
              {loading ? "Memproses..." : "Masuk"}
            </button>

            <div className="mt-5 grid grid-cols-3 gap-2 rounded-3xl border border-blue-100 bg-blue-50/70 p-3">
              <div className="rounded-2xl bg-white p-3 text-center shadow-sm">
                <Building2 className="mx-auto h-5 w-5 text-blue-700" />
                <p className="mt-1 text-[11px] font-bold text-slate-700">
                  SPPG
                </p>
              </div>

              <div className="rounded-2xl bg-white p-3 text-center shadow-sm">
                <UtensilsCrossed className="mx-auto h-5 w-5 text-blue-700" />
                <p className="mt-1 text-[11px] font-bold text-slate-700">
                  Omprengan
                </p>
              </div>

              <div className="rounded-2xl bg-white p-3 text-center shadow-sm">
                <BadgeCheck className="mx-auto h-5 w-5 text-blue-700" />
                <p className="mt-1 text-[11px] font-bold text-slate-700">
                  Validasi
                </p>
              </div>
            </div>

            <div className="mt-6 rounded-3xl border border-blue-100 bg-gradient-to-br from-sky-50 to-blue-50 p-4">
              <div className="mb-3 flex items-center justify-between gap-2">
                <p className="text-sm font-black text-slate-800">
                  Akun percobaan
                </p>

                <span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-bold text-blue-700 shadow-sm">
                  Klik untuk isi otomatis
                </span>
              </div>

              <div className="grid gap-2">
                {roleCards.map((item) => {
                  const Icon = item.icon;

                  return (
                    <button
                      key={item.username}
                      type="button"
                      onClick={() => handleUseDemo(item)}
                      className="group flex items-center justify-between gap-3 rounded-2xl border border-blue-100 bg-white/90 px-3 py-2 text-left shadow-sm transition hover:-translate-y-0.5 hover:border-blue-200 hover:bg-white hover:shadow-md"
                    >
                      <div className="flex items-center gap-3">
                        <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-gradient-to-br from-sky-500 to-blue-700 text-white shadow-sm">
                          <Icon className="h-4 w-4" />
                        </div>

                        <div>
                          <p className="text-xs font-bold text-slate-900">
                            {item.label}
                          </p>

                          <p className="text-[11px] text-slate-500">
                            {item.username} / {item.password}
                          </p>
                        </div>
                      </div>

                      <ArrowRight className="h-4 w-4 text-slate-400 transition group-hover:translate-x-1 group-hover:text-blue-600" />
                    </button>
                  );
                })}
              </div>
            </div>
          </form>

          <p className="mt-4 text-center text-xs text-white/75">
            OPEN PLATE MBG • TRANSPARANSI • MONITORING • PELAPORAN
          </p>
        </div>
      </div>
    </div>
  );
}