import { createFileRoute, useNavigate, Link } from "@tanstack/react-router";
import { useServerFn } from "@tanstack/react-start";
import { useState, useEffect } from "react";
import { customerPortalLogin } from "@/lib/customer-portal.functions";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { toast } from "sonner";
import { Eye, EyeOff, Loader2, AlertCircle, Languages, Download, Smartphone } from "lucide-react";
import logo from "@/assets/niyamah-logo.png";
import { useLanguage } from "@/hooks/use-language";
import { useInstallPrompt } from "@/hooks/use-install-prompt";


const L = {
  title: { bn: "আপনার নিয়ামাহ্ একাউন্টে লগইন করুন", en: "Login to your Niyamah account" },
  mobile: { bn: "মোবাইল নম্বর", en: "Mobile Number" },
  password: { bn: "পাসওয়ার্ড", en: "Password" },
  login: { bn: "লগইন", en: "Login" },
  processing: { bn: "প্রক্রিয়াধীন...", en: "Processing..." },
  welcome: { bn: "স্বাগতম!", en: "Welcome!" },
  mobileShort: { bn: "মোবাইল নম্বর কমপক্ষে ৬ অক্ষরের হতে হবে", en: "Mobile number must be at least 6 characters" },
  pwShort: { bn: "পাসওয়ার্ড কমপক্ষে ৪ অক্ষরের হতে হবে", en: "Password must be at least 4 characters" },
  errInvalid: { bn: "মোবাইল নম্বর অথবা পাসওয়ার্ড ভুল", en: "Incorrect mobile number or password" },
  errPortal: { bn: "এই অ্যাকাউন্টের পোর্টাল অ্যাক্সেস চালু নেই", en: "Portal access is not enabled for this account" },
  errInactive: { bn: "অ্যাকাউন্টটি সক্রিয় নয়", en: "Account is not active" },
  errNotFound: { bn: "এই মোবাইল নম্বরে কোনো অ্যাকাউন্ট পাওয়া যায়নি", en: "No account found with this mobile number" },
  errNetwork: { bn: "ইন্টারনেট সংযোগে সমস্যা হচ্ছে", en: "Network connection problem" },
  errGeneric: { bn: "লগইন ব্যর্থ হয়েছে", en: "Login failed" },
  contactLine1: { bn: "🔐 অ্যাকাউন্ট অ্যাক্সেসের জন্য অনুমোদিত প্রতিষ্ঠানের সাথে যোগাযোগ করুন।", en: "🔐 Contact the authorized organization for account access." },
  contactLine2: { bn: "📞 নিয়ামাহ্ ইলেকট্রিক হার্ডওয়্যার প্রোডাক্টস", en: "📞 Niyamah Electric Hardware Products" },
  installApp: { bn: "অ্যাপ ইনস্টল করুন", en: "Install App" },
  installDesc: { bn: "দ্রুত অ্যাক্সেসের জন্য হোম স্ক্রিনে যোগ করুন", en: "Add to home screen for quick access" },
  installed: { bn: "ইনস্টল করা হয়েছে", en: "Installed" },
  reinstallTitle: { bn: "অ্যাপটি পুনরায় ইনস্টল করুন", en: "Please Re-install the App" },
  reinstallBody: {
    bn: "আমরা অ্যাপের থিম, রঙ ও আইকন আপডেট করেছি। নতুন ডিজাইন পেতে অনুগ্রহ করে পুরানো অ্যাপটি মুছে ফেলুন এবং আবার ইনস্টল করুন।",
    en: "We have updated the app theme, colors and icon. To get the new design, please uninstall the old app and install it again."
  },
  reinstallOk: { bn: "বুঝেছি", en: "Got it" },
} as const;

export const Route = createFileRoute("/portal/login")({
  head: () => ({ meta: [{ title: "Customer Portal Login — Niyamah" }] }),
  validateSearch: (s: Record<string, unknown>) => ({ mobile: typeof s.mobile === "string" ? s.mobile : "" }),
  component: PortalLoginPage,
});

function PortalLoginPage() {
  const login = useServerFn(customerPortalLogin);
  const navigate = useNavigate();
  const { lang, toggleLang } = useLanguage();
  const tt = (k: keyof typeof L) => L[k][lang];
  const { mobile: prefillMobile } = Route.useSearch();
  const [form, setForm] = useState({ mobile: prefillMobile || "", password: "" });
  const [showPw, setShowPw] = useState(false);
  const [logoSpin, setLogoSpin] = useState(false);
  const [busy, setBusy] = useState(false);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const [splash, setSplash] = useState(true);
  const [splashMsgIdx, setSplashMsgIdx] = useState(0);
  const { evt: installEvt, prompt: installPrompt } = useInstallPrompt();
  const [installed, setInstalled] = useState(false);
  const [showReinstall, setShowReinstall] = useState(false);

  useEffect(() => {
    if (typeof window === "undefined") return;
    const dismissed = localStorage.getItem("reinstall_notice_v2");
    const isStandalone =
      window.matchMedia?.("(display-mode: standalone)").matches ||
      (window.navigator as any).standalone === true;
    if (isStandalone && !dismissed) {
      const t = setTimeout(() => setShowReinstall(true), 15500);
      return () => clearTimeout(t);
    }
  }, []);

  const dismissReinstall = () => {
    localStorage.setItem("reinstall_notice_v2", "1");
    setShowReinstall(false);
  };


  const splashMessages = lang === "bn"
    ? [
      "স্বাগতম",
      "নিয়ামাহ্ কাস্টমার পোর্টাল",
      "আপনার অ্যাকাউন্ট লোড হচ্ছে...",
      "দয়া করে অপেক্ষা করুন",
      "শীঘ্রই প্রস্তুত হচ্ছে",
    ]
    : [
      "Welcome",
      "Niyamah Customer Portal",
      "Loading your account...",
      "Please wait a moment",
      "Almost ready",
    ];

  useEffect(() => {
    const t = setTimeout(() => setSplash(false), 15000);
    const i = setInterval(() => setSplashMsgIdx((v) => v + 1), 2500);
    return () => { clearTimeout(t); clearInterval(i); };
  }, []);


  const translateError = (raw?: string) => {
    const m = (raw || "").toLowerCase();
    if (m.includes("invalid")) return tt("errInvalid");
    if (m.includes("not enabled") || m.includes("portal")) return tt("errPortal");
    if (m.includes("not active") || m.includes("inactive")) return tt("errInactive");
    if (m.includes("not found")) return tt("errNotFound");
    if (m.includes("network") || m.includes("fetch")) return tt("errNetwork");
    return raw || tt("errGeneric");
  };

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMsg(null);
    const mobile = form.mobile.trim();
    const password = form.password;
    if (mobile.length < 6) { const msg = tt("mobileShort"); setErrorMsg(msg); toast.error(msg); return; }
    if (password.length < 4) { const msg = tt("pwShort"); setErrorMsg(msg); toast.error(msg); return; }
    setBusy(true);
    try {
      const res = await login({ data: { mobile, password } });
      if (!res.ok || !res.token) {
        const msg = translateError(res.error ?? undefined);
        setErrorMsg(msg);
        toast.error(msg);
        return;
      }
      localStorage.setItem("customer_portal_token", res.token);
      localStorage.setItem("customer_portal_customer", JSON.stringify(res.customer));
      toast.success(tt("welcome"));
      navigate({ to: "/portal" });
    } catch (e: any) {
      const msg = translateError(e?.message);
      setErrorMsg(msg);
      toast.error(msg);
    } finally { setBusy(false); }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-white p-4 relative overflow-hidden">
      {/* Re-install popup */}
      {showReinstall && (
        <div className="fixed inset-0 z-[60] flex items-center justify-center bg-slate-900/60 backdrop-blur-sm p-4 animate-in fade-in">
          <div className="relative w-full max-w-sm rounded-3xl bg-gradient-to-br from-violet-500/40 via-purple-500/40 to-fuchsia-500/40 p-[1px] shadow-2xl">
            <div className="rounded-3xl bg-white p-6 text-center">
              <div className="mx-auto mb-4 h-14 w-14 rounded-2xl bg-gradient-to-br from-violet-500 to-fuchsia-600 grid place-items-center shadow-lg shadow-violet-500/40">
                <Download className="h-7 w-7 text-white" />
              </div>
              <h3 className="text-lg font-bold text-slate-900 mb-2">{tt("reinstallTitle")}</h3>
              <p className="text-sm text-slate-600 leading-relaxed mb-5">{tt("reinstallBody")}</p>
              <Button
                onClick={dismissReinstall}
                className="w-full h-11 bg-gradient-to-r from-violet-500 to-fuchsia-600 hover:from-violet-600 hover:to-fuchsia-700 text-white font-bold shadow-lg shadow-violet-500/30"
              >
                {tt("reinstallOk")}
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* Splash overlay — big logo shrinks into card over 10 seconds */}
      {splash && (
        <div
          className="fixed inset-0 z-50 flex flex-col items-center bg-white p-4"
          style={{ animation: "splashFade 15s ease-in-out forwards" }}
        >
          <div className="absolute -top-40 -left-20 h-96 w-96 rounded-full bg-violet-400/20 blur-3xl" />
          <div className="absolute -bottom-40 -right-20 h-96 w-96 rounded-full bg-fuchsia-400/20 blur-3xl" />

          <div className="flex-1 flex items-center justify-center w-full min-h-0">
            <div
              className="relative h-[min(48vh,48vw)] w-[min(48vh,48vw)] max-h-[320px] max-w-[320px] rounded-full bg-white grid place-items-center shadow-2xl shadow-violet-500/50 ring-4 ring-violet-400/40 overflow-hidden"
              style={{ animation: "splashLogo 15s cubic-bezier(.7,0,.3,1) forwards" }}
            >
              <img src={logo} alt="Niyamah" className="h-full w-full object-cover scale-110" />
            </div>
          </div>

          {/* Bottom content — never empty */}
          <div className="flex flex-col items-center gap-4 shrink-0 pb-4">
            {/* Dots spinner */}
            <div className="flex items-center gap-2">
              <span className="inline-block h-2.5 w-2.5 rounded-full bg-violet-400 animate-bounce" style={{ animationDelay: "0ms", animationDuration: "1.2s" }} />
              <span className="inline-block h-2.5 w-2.5 rounded-full bg-fuchsia-400 animate-bounce" style={{ animationDelay: "200ms", animationDuration: "1.2s" }} />
              <span className="inline-block h-2.5 w-2.5 rounded-full bg-violet-400 animate-bounce" style={{ animationDelay: "400ms", animationDuration: "1.2s" }} />
            </div>

            {/* Subtle progress bar */}
            <div className="w-48 h-1.5 rounded-full bg-slate-200 overflow-hidden">
            <div
                className="h-full bg-gradient-to-r from-violet-400 to-fuchsia-400 rounded-full"
                style={{ animation: "splashProgress 15s linear forwards" }}
              />
            </div>
          </div>
        </div>
      )}

      <style>{`
        @keyframes splashLogo {
          0%   { transform: scale(1.6); opacity: 0; }
          6%   { transform: scale(1.45); opacity: 1; }
          55%  { transform: scale(1.1); opacity: 1; }
          85%  { transform: scale(0.5); opacity: 1; }
          100% { transform: scale(0.28); opacity: 0; }
        }
        @keyframes splashFade {
          0%, 90% { opacity: 1; }
          100%    { opacity: 0; visibility: hidden; }
        }
        @keyframes splashProgress {
          0%   { width: 0%; }
          100% { width: 100%; }
        }
        @keyframes logoPulse {
          0%, 100% { transform: scale(0.95); opacity: 0.6; }
          50%      { transform: scale(1.15); opacity: 1; }
        }
        @keyframes logoFloat {
          0%, 100% { transform: translateY(0); }
          50%      { transform: translateY(-6px); }
        }
        @keyframes logoRing1 {
          0%, 100% { transform: scale(1); opacity: 0.3; }
          50%      { transform: scale(1.08); opacity: 0.6; }
        }
        @keyframes logoRing2 {
          0%, 100% { transform: scale(1); opacity: 0.2; }
          50%      { transform: scale(1.12); opacity: 0.4; }
        }
        @keyframes logoRing3 {
          0%, 100% { transform: scale(1); opacity: 0.1; }
          50%      { transform: scale(1.18); opacity: 0.25; }
        }
      `}</style>

      <div className="absolute inset-0 pointer-events-none">
        <div className="absolute -top-40 -left-20 h-96 w-96 rounded-full bg-violet-400/15 blur-3xl" />
        <div className="absolute -bottom-40 -right-20 h-96 w-96 rounded-full bg-fuchsia-400/15 blur-3xl" />
        <div className="absolute top-1/3 left-1/2 h-72 w-72 rounded-full bg-purple-400/10 blur-3xl" />
      </div>

      <div className="relative w-full max-w-md">
        <div className="rounded-3xl bg-gradient-to-br from-violet-500/40 via-purple-500/40 to-fuchsia-500/40 p-[1px] shadow-2xl shadow-violet-900/20">
          <div className="relative rounded-3xl bg-white/90 backdrop-blur-xl p-8 text-slate-900">
            {/* Language toggle — top-right of card */}
            <button
              type="button"
              onClick={toggleLang}
              className="absolute top-4 right-4 z-20 inline-flex items-center gap-1.5 rounded-full bg-slate-100 hover:bg-slate-200 border border-slate-200 backdrop-blur px-3 py-1.5 text-xs font-semibold text-slate-700 shadow-sm transition-colors"
              aria-label="Toggle language"
            >
              <Languages className="h-3.5 w-3.5" />
              <span className={lang === "bn" ? "opacity-100" : "opacity-50"}>বাংলা</span>
              <span className="opacity-40">/</span>
              <span className={lang === "en" ? "opacity-100" : "opacity-50"}>EN</span>
            </button>

            <div className="text-center mb-7 pt-2">
              {/* Animated Big Logo */}
              <div className="relative mx-auto mb-5" style={{ width: "min(140px, 35vw)", height: "min(140px, 35vw)" }}>
                {/* Outer animated rings */}
                <div className="absolute inset-0 rounded-full border-2 border-violet-400/30 animate-[logoRing1_3s_ease-in-out_infinite]" />
                <div className="absolute inset-[-8px] rounded-full border border-fuchsia-400/20 animate-[logoRing2_3s_ease-in-out_infinite_0.5s]" />
                <div className="absolute inset-[-16px] rounded-full border border-violet-300/10 animate-[logoRing3_3s_ease-in-out_infinite_1s]" />

                {/* Glow behind */}
                <div className="absolute inset-0 rounded-full bg-gradient-to-br from-violet-500/30 to-fuchsia-500/30 blur-xl animate-[logoPulse_2.5s_ease-in-out_infinite]" />

                {/* Logo container */}
                <button
                  type="button"
                  onClick={() => { setLogoSpin(false); requestAnimationFrame(() => setLogoSpin(true)); }}
                  className="relative z-10 block w-full h-full rounded-full bg-white grid place-items-center shadow-2xl shadow-violet-500/30 ring-4 ring-violet-400/30 overflow-hidden transition-transform hover:scale-105 active:scale-95 animate-[logoFloat_4s_ease-in-out_infinite]"
                  aria-label="Niyamah"
                >
                  <img
                    src={logo}
                    alt="Niyamah"
                    onAnimationEnd={() => setLogoSpin(false)}
                    className={`h-full w-full object-cover scale-110 ${logoSpin ? "animate-[spin_0.8s_ease-in-out_1]" : ""}`}
                  />

                </button>
              </div>
              <h1 className="text-2xl font-bold text-slate-900">{tt("title")}</h1>
            </div>
            <form onSubmit={onSubmit} className="space-y-4" autoComplete="off">
              {errorMsg && (
                <div className="flex items-start gap-2 rounded-lg border border-red-400/40 bg-red-50 px-3 py-2.5 text-sm text-red-700">
                  <AlertCircle className="h-4 w-4 mt-0.5 shrink-0" />
                  <span>{errorMsg}</span>
                </div>
              )}
              <div>
                <Label className="text-xs text-slate-500">{tt("mobile")}</Label>
                <Input
                  value={form.mobile}
                  onChange={(e) => setForm({ ...form, mobile: e.target.value })}
                  placeholder="01XXXXXXXXX"
                  minLength={6}
                  required
                  inputMode="tel"
                  autoComplete="off"
                  className="mt-1 bg-white border-slate-200 text-slate-900 h-11"
                />
              </div>
              <div>
                <Label className="text-xs text-slate-500">{tt("password")}</Label>
                <div className="relative mt-1">
                  <Input
                    type={showPw ? "text" : "password"}
                    value={form.password}
                    onChange={(e) => setForm({ ...form, password: e.target.value })}
                    minLength={4}
                    required
                    autoComplete="new-password"
                    autoCorrect="off"
                    autoCapitalize="off"
                    spellCheck={false}
                    className="bg-white border-slate-200 text-slate-900 h-11 pr-10"
                  />

                  <button
                    type="button"
                    onClick={() => setShowPw((v) => !v)}
                    className="absolute right-2 top-1/2 -translate-y-1/2 h-7 w-7 grid place-items-center rounded-md text-slate-400 hover:text-slate-600 hover:bg-slate-100"
                    tabIndex={-1}
                  >
                    {showPw ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </button>
                </div>
              </div>
              <Button
                type="submit"
                className="w-full h-11 bg-gradient-to-r from-violet-500 to-fuchsia-600 hover:from-violet-600 hover:to-fuchsia-700 text-white font-bold shadow-lg shadow-violet-500/30"
                disabled={busy}
              >
                {busy ? (
                  <>
                    <Loader2 className="h-4 w-4 animate-spin" />
                    <span>{tt("processing")}</span>
                  </>
                ) : (
                  tt("login")
                )}
              </Button>
            </form>
            <p className="text-xs text-center text-slate-600 mt-6 leading-relaxed">
              {tt("contactLine1")}<br />
              {tt("contactLine2")}
            </p>
            <div className="text-center mt-3 hidden">
              <Link to="/login" className="text-xs text-violet-600 hover:text-violet-700 hover:underline">স্টাফ/অ্যাডমিন লগইন →</Link>
            </div>

            {/* Install App card */}
            {installEvt && !installed && (
              <div className="mt-5 rounded-2xl bg-gradient-to-r from-emerald-500/30 to-teal-500/30 p-[1px]">
                <div className="rounded-2xl bg-emerald-50/60 backdrop-blur-sm px-4 py-3 flex items-center gap-3">
                  <div className="h-10 w-10 rounded-xl bg-emerald-500/10 grid place-items-center shrink-0">
                    <Smartphone className="h-5 w-5 text-emerald-700" />
                  </div>
                  <div className="flex-1 min-w-0 text-left">
                    <p className="text-sm font-semibold text-emerald-800 leading-tight">{tt("installApp")}</p>
                    <p className="text-xs text-emerald-600 leading-snug">{tt("installDesc")}</p>
                  </div>
                  <button
                    onClick={async () => {
                      const res = await installPrompt();
                      if (res.outcome === "accepted") setInstalled(true);
                    }}
                    className="shrink-0 rounded-lg bg-emerald-500 text-white text-xs font-bold px-3 py-2 hover:bg-emerald-400 flex items-center gap-1.5"
                  >
                    <Download className="h-3.5 w-3.5" />
                    {tt("installApp")}
                  </button>
                </div>
              </div>
            )}
            {installed && (
              <div className="mt-5 rounded-2xl bg-emerald-50 border border-emerald-200 px-4 py-3 text-center">
                <p className="text-sm font-semibold text-emerald-700">{tt("installed")} ✓</p>
              </div>
            )}

          </div>
        </div>
      </div>
    </div>
  );
}
