"use client";

import React, { useState, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import {
  Lock,
  Mail,
  ShieldCheck,
  Compass,
  ArrowLeft,
  LogIn,
  AlertCircle,
  UserCheck,
} from "lucide-react";

function LoginFormContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const callbackUrl = searchParams.get("callbackUrl") || "/erp";

  const [email, setEmail] = useState("david.kyalo@muajiri.com");
  const [password, setPassword] = useState("Davally@2026");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setLoading(true);

    try {
      const res = await fetch("/api/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password }),
      });

      const data = await res.json();
      if (!res.ok) {
        setError(data.error || "Invalid credentials.");
        setLoading(false);
        return;
      }

      router.push(callbackUrl);
      router.refresh();
    } catch {
      setError("Network error while signing in.");
      setLoading(false);
    }
  };

  const fillCredentials = (demoEmail: string, demoPass: string) => {
    setEmail(demoEmail);
    setPassword(demoPass);
    setError(null);
  };

  return (
    <div className="min-h-screen bg-hive-950 text-white flex flex-col justify-between p-4 sm:p-8">
      {/* Top Bar */}
      <div className="max-w-6xl w-full mx-auto flex items-center justify-between">
        <Link
          href="/"
          className="inline-flex items-center gap-2 text-xs font-bold text-slate-300 hover:text-honey-400 transition"
        >
          <ArrowLeft className="w-4 h-4" />
          Back to Public Website
        </Link>
        <div className="text-xs text-slate-400">
          Davally Apiculture ERP & Field Security Gateway
        </div>
      </div>

      {/* Main Card */}
      <div className="max-w-4xl w-full mx-auto my-8 grid md:grid-cols-12 bg-hive-900 rounded-3xl border border-slate-800 overflow-hidden shadow-2xl">
        {/* Left Brand & Security Column */}
        <div className="md:col-span-5 bg-gradient-to-br from-hive-900 via-hive-950 to-amber-950/30 p-8 border-b md:border-b-0 md:border-r border-slate-800 flex flex-col justify-between space-y-6">
          <div className="space-y-4">
            <div className="flex items-center gap-3">
              <img
                src="/images/logo-icon.png"
                alt="Davally Logo"
                className="w-12 h-12 rounded-xl bg-white p-1 object-contain"
              />
              <div>
                <div className="font-black text-lg text-white leading-none">
                  DAVALLY <span className="text-honey-400">ERP</span>
                </div>
                <div className="text-[11px] text-honey-400 font-semibold mt-0.5">
                  Authorized Staff & Apiarist Portal
                </div>
              </div>
            </div>

            <h1 className="text-2xl font-black text-white pt-2">
              Role-Based Field & GIS Access
            </h1>
            <p className="text-xs text-slate-300 leading-relaxed">
              Guests can explore the public website, price catalogue, and shareable client report
              links. Logging field activities, uploading geo-located photos, and managing ERP
              records requires staff authentication.
            </p>

            <div className="space-y-2.5 pt-2 text-xs">
              <div className="p-3 rounded-xl bg-white/5 border border-white/10">
                <div className="font-extrabold text-honey-400 flex items-center gap-1.5">
                  <ShieldCheck className="w-4 h-4" />
                  ADMIN / MANAGER ROLE
                </div>
                <div className="text-slate-300 text-[11px] mt-1">
                  Full access to Clients & Sites, Field Activity Collector, Report Approval &
                  Client Email Dispatch, Dynamic Dropdowns, Price Catalogue, and Staff Roles.
                </div>
              </div>

              <div className="p-3 rounded-xl bg-white/5 border border-white/10">
                <div className="font-extrabold text-emerald-400 flex items-center gap-1.5">
                  <Compass className="w-4 h-4" />
                  FIELD TECHNICIAN ROLE
                </div>
                <div className="text-slate-300 text-[11px] mt-1">
                  Access to Mobile Field Dropdown Collector, GPS Photo Capture, Area/Perimeter
                  Tracing, and Site Maps. Reports submit to Admin Review queue.
                </div>
              </div>
            </div>
          </div>

          <div className="text-[11px] text-slate-500">
            Tala Town, Machakos County • Reg: BN-79S6OBMR
          </div>
        </div>

        {/* Right Login Form Column */}
        <div className="md:col-span-7 p-8 bg-white text-slate-900 flex flex-col justify-center space-y-6">
          <div>
            <div className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-amber-100 text-amber-900 text-[11px] font-extrabold uppercase">
              <Lock className="w-3 h-3" /> Staff Authentication Required
            </div>
            <h2 className="text-2xl font-black text-slate-900 mt-2">
              Sign In to Davally Apiculture
            </h2>
            {callbackUrl && callbackUrl !== "/erp" && (
              <p className="text-xs text-amber-700 font-semibold mt-1">
                Please sign in to access <span className="font-mono">{callbackUrl}</span>
              </p>
            )}
          </div>

          {error && (
            <div className="p-3.5 rounded-xl bg-rose-50 border border-rose-200 text-rose-800 text-xs font-bold flex items-center gap-2">
              <AlertCircle className="w-4 h-4 text-rose-600 shrink-0" />
              <span>{error}</span>
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-xs font-extrabold text-slate-700 mb-1">
                Staff Email Address
              </label>
              <div className="relative">
                <Mail className="w-4 h-4 text-slate-400 absolute left-3.5 top-3" />
                <input
                  type="email"
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="name@davallyapiculture.co.ke"
                  className="w-full rounded-xl border border-slate-300 pl-10 pr-4 py-2.5 text-sm font-semibold text-slate-900 focus:border-amber-500 focus:outline-none"
                />
              </div>
            </div>

            <div>
              <label className="block text-xs font-extrabold text-slate-700 mb-1">
                Password
              </label>
              <div className="relative">
                <Lock className="w-4 h-4 text-slate-400 absolute left-3.5 top-3" />
                <input
                  type="password"
                  required
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="••••••••••••"
                  className="w-full rounded-xl border border-slate-300 pl-10 pr-4 py-2.5 text-sm font-semibold text-slate-900 focus:border-amber-500 focus:outline-none"
                />
              </div>
            </div>

            <button
              type="submit"
              disabled={loading}
              className="w-full py-3.5 rounded-xl bg-hive-900 hover:bg-hive-800 text-honey-400 font-black text-sm flex items-center justify-center gap-2 shadow-lg transition"
            >
              <LogIn className="w-4 h-4" />
              {loading ? "Verifying Credentials..." : "Sign In to ERP & Field System"}
            </button>
          </form>

          {/* Quick Role Switcher / Demo Accounts Box */}
          <div className="border-t border-slate-200 pt-4 space-y-2.5">
            <div className="text-[11px] font-extrabold uppercase text-slate-500 flex items-center gap-1.5">
              <UserCheck className="w-3.5 h-3.5 text-amber-600" />
              Quick-Fill Staff Accounts (Click to Select Role)
            </div>
            <div className="grid sm:grid-cols-2 gap-2.5">
              <button
                type="button"
                onClick={() =>
                  fillCredentials("david.kyalo@muajiri.com", "Davally@2026")
                }
                className={`text-left p-2.5 rounded-xl border text-xs transition ${
                  email === "david.kyalo@muajiri.com"
                    ? "border-amber-500 bg-amber-50/70"
                    : "border-slate-200 hover:bg-slate-50"
                }`}
              >
                <div className="flex items-center justify-between">
                  <span className="font-extrabold text-slate-900">Mr. David Kyalo</span>
                  <span className="text-[10px] font-black px-1.5 py-0.5 rounded bg-hive-900 text-honey-400">
                    ADMIN
                  </span>
                </div>
                <div className="text-[11px] text-slate-500 truncate mt-0.5">
                  david.kyalo@muajiri.com
                </div>
              </button>

              <button
                type="button"
                onClick={() =>
                  fillCredentials(
                    "peter.mutua@davallyapiculture.co.ke",
                    "Field@2026"
                  )
                }
                className={`text-left p-2.5 rounded-xl border text-xs transition ${
                  email === "peter.mutua@davallyapiculture.co.ke"
                    ? "border-emerald-500 bg-emerald-50/70"
                    : "border-slate-200 hover:bg-slate-50"
                }`}
              >
                <div className="flex items-center justify-between">
                  <span className="font-extrabold text-slate-900">Peter Mutua</span>
                  <span className="text-[10px] font-black px-1.5 py-0.5 rounded bg-emerald-700 text-white">
                    TECHNICIAN
                  </span>
                </div>
                <div className="text-[11px] text-slate-500 truncate mt-0.5">
                  peter.mutua@davallyapiculture.co.ke
                </div>
              </button>
            </div>
          </div>
        </div>
      </div>

      <div className="text-center text-xs text-slate-500">
        Sustaining ecosystems, one queen at a time • Davally Apiculture Limited
      </div>
    </div>
  );
}

export default function LoginPage() {
  return (
    <Suspense
      fallback={
        <div className="min-h-screen bg-hive-950 text-honey-400 flex items-center justify-center text-sm font-bold">
          Loading Security Gateway...
        </div>
      }
    >
      <LoginFormContent />
    </Suspense>
  );
}
