import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import {
  ArrowRight,
  Clock,
  Eye,
  EyeOff,
  Headphones,
  KeyRound,
  Lock,
  Mail,
  MessageCircle,
  Phone,
  ShieldCheck,
  User,
  UserPlus,
} from "lucide-react";

import { BrandLogo, PoweredBy } from "@/components/BrandLogo";
import { ForgotPasswordDialog } from "@/components/ForgotPasswordDialog";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { signIn, getSession, getRemembered, saveRemembered, clearRemembered } from "@/lib/auth";

export const Route = createFileRoute("/")({
  head: () => ({
    meta: [
      { title: "Ingia | SmartHR Payroll - WAMAKINDA MICROFINANCE" },
      {
        name: "description",
        content:
          "Mfumo wa kisasa wa SmartHR Payroll Manager wa WAMAKINDA MICROFINANCE LTD: wafanyakazi, mahudhurio, mishahara na ripoti.",
      },
      { property: "og:title", content: "SmartHR Payroll - WAMAKINDA MICROFINANCE LTD" },
      {
        property: "og:description",
        content: "Ingia kwenye mfumo salama wa usimamizi wa wafanyakazi na mishahara.",
      },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
  }),
  component: LoginPage,
});

function LoginPage() {
  const navigate = useNavigate();
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [confirm, setConfirm] = useState("");
  const [show, setShow] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const [remember, setRemember] = useState(true);
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);
  const [forgot, setForgot] = useState(false);
  const [contact, setContact] = useState(false);

  useEffect(() => {
    if (getSession()) {
      navigate({ to: "/app" });
      return;
    }
    const saved = getRemembered();
    if (saved) {
      setUsername(saved.user);
      setPassword(saved.pass);
      setConfirm(saved.pass);
      const res = signIn(saved.user, saved.pass, saved.pass);
      if (res.ok) navigate({ to: "/app" });
    }
  }, [navigate]);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    setBusy(true);
    try {
      const res = signIn(username, password, confirm);
      if (!res.ok) {
        setError(res.error);
        setBusy(false);
        return;
      }
      if (remember) saveRemembered(username.trim(), password);
      else {
        clearRemembered();
        window.sessionStorage.setItem("wamakinda.temp", "1");
      }
      navigate({ to: "/app" });
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="relative min-h-screen overflow-hidden bg-background">
      <ForgotPasswordDialog open={forgot} onOpenChange={setForgot} />
      <div className="pointer-events-none absolute -left-40 -top-56 h-[36rem] w-[36rem] rounded-full brand-gradient opacity-25 blur-3xl" />
      <div className="pointer-events-none absolute -bottom-52 -right-32 h-[30rem] w-[30rem] rounded-full brand-gradient opacity-20 blur-3xl" />

      <header className="relative z-10 flex flex-wrap items-center justify-between gap-3 px-4 py-5 sm:px-8">
        <BrandLogo size={52} />
        <div className="flex items-center gap-3 rounded-full border border-border bg-card px-4 py-2 card-shadow">
          <span className="flex size-9 items-center justify-center rounded-full brand-gradient text-primary-foreground">
            <User className="size-5" />
          </span>
          <div className="leading-tight">
            <p className="text-sm font-semibold">Jina la Mtumiaji</p>
            <p className="text-xs text-muted-foreground">Karibu tena!</p>
          </div>
        </div>
      </header>

      <main className="relative z-10 mx-auto w-full max-w-lg px-4 pb-10 sm:px-6">
        <section className="rounded-3xl border border-border/70 bg-card/90 p-6 backdrop-blur float-shadow sm:p-8">
          <div className="flex justify-center">
            <span className="flex size-16 items-center justify-center rounded-full bg-secondary">
              <span className="flex size-12 items-center justify-center rounded-full brand-gradient text-primary-foreground">
                <Lock className="size-6" />
              </span>
            </span>
          </div>

          <h1 className="mt-4 text-center text-3xl font-extrabold tracking-tight">
            <span className="block text-lg font-bold text-primary">Karibu tena!</span>
            Ingia kwenye Akaunti
          </h1>
          <div className="mx-auto mt-3 h-1 w-16 rounded-full brand-gradient" />
          <p className="mt-4 text-center text-sm text-muted-foreground">
            Tafadhali weka taarifa zako za kuingia ili kuendelea.
          </p>

          <form onSubmit={onSubmit} className="mt-6 space-y-4">
            <div className="space-y-2">
              <Label htmlFor="username">Jina la Mtumiaji</Label>
              <div className="relative">
                <User className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-primary" />
                <Input
                  id="username"
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                  placeholder="Weka jina la mtumiaji"
                  autoComplete="username"
                  className="h-12 rounded-xl pl-10"
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="password">Nenosiri</Label>
              <div className="relative">
                <KeyRound className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-primary" />
                <Input
                  id="password"
                  type={show ? "text" : "password"}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="Weka nenosiri"
                  autoComplete="current-password"
                  className="h-12 rounded-xl px-10"
                />
                <button
                  type="button"
                  onClick={() => setShow((s) => !s)}
                  aria-label="Onyesha nenosiri"
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-primary"
                >
                  {show ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
                </button>
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="confirm">Thibitisha Nenosiri</Label>
              <div className="relative">
                <ShieldCheck className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-primary" />
                <Input
                  id="confirm"
                  type={showConfirm ? "text" : "password"}
                  value={confirm}
                  onChange={(e) => setConfirm(e.target.value)}
                  placeholder="Rudia nenosiri lako"
                  autoComplete="off"
                  className="h-12 rounded-xl px-10"
                />
                <button
                  type="button"
                  onClick={() => setShowConfirm((s) => !s)}
                  aria-label="Onyesha uthibitisho wa nenosiri"
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-primary"
                >
                  {showConfirm ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
                </button>
              </div>
            </div>

            {error && (
              <p
                role="alert"
                className="rounded-xl border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm font-semibold text-destructive"
              >
                {error}
              </p>
            )}

            <div className="flex items-center justify-between">
              <label className="flex items-center gap-2 text-sm">
                <Checkbox
                  checked={remember}
                  onCheckedChange={(v) => setRemember(Boolean(v))}
                  aria-label="Nikumbuke"
                />
                Nikumbuke
              </label>
              <button
                type="button"
                onClick={() => setForgot(true)}
                className="text-sm font-semibold text-primary hover:underline"
              >
                Umesahau nenosiri?
              </button>
            </div>

            <Button
              type="submit"
              disabled={busy}
              className="h-13 w-full rounded-xl brand-gradient py-6 text-base font-bold text-primary-foreground card-shadow hover:opacity-95"
            >
              <Lock className="size-5" />
              {busy ? "Inathibitisha..." : "Ingia"}
              <ArrowRight className="size-5" />
            </Button>


            <div className="flex items-center gap-3 pt-1">
              <span className="h-px flex-1 bg-border" />
              <span className="text-xs text-muted-foreground">Usipo na akaunti?</span>
              <span className="h-px flex-1 bg-border" />
            </div>

            <button
              type="button"
              onClick={() => setContact(true)}
              className="flex h-12 w-full items-center justify-center gap-2 rounded-xl border-2 border-primary/40 text-sm font-bold text-primary transition-colors hover:bg-accent"
            >
              <UserPlus className="size-4" />
              Wasiliana nasi kujiandikisha
            </button>
          </form>
        </section>

        <Dialog open={contact} onOpenChange={setContact}>
          <DialogContent className="rounded-3xl sm:max-w-md">
            <DialogHeader>
              <div className="mx-auto flex size-14 items-center justify-center rounded-full brand-gradient text-primary-foreground">
                <Headphones className="size-7" />
              </div>
              <DialogTitle className="text-center text-xl font-extrabold">Wasiliana nasi</DialogTitle>
              <DialogDescription className="text-center">
                Chagua njia unayopendelea — tutakusajili haraka.
              </DialogDescription>
            </DialogHeader>

            <div className="grid gap-3">
              <a
                href="tel:+255612929319"
                className="flex items-center gap-3 rounded-2xl border border-border bg-card px-4 py-3 transition-colors hover:border-primary/50 hover:bg-accent"
              >
                <span className="flex size-10 shrink-0 items-center justify-center rounded-full brand-gradient text-primary-foreground">
                  <Phone className="size-5" />
                </span>
                <span className="min-w-0">
                  <span className="block text-xs text-muted-foreground">Namba ya simu</span>
                  <span className="block text-sm font-bold">+255 612 929 319</span>
                </span>
              </a>

              <a
                href="https://wa.me/255612929319"
                target="_blank"
                rel="noopener noreferrer"
                className="flex items-center gap-3 rounded-2xl border border-border bg-card px-4 py-3 transition-colors hover:border-primary/50 hover:bg-accent"
              >
                <span className="flex size-10 shrink-0 items-center justify-center rounded-full bg-primary/15 text-primary">
                  <MessageCircle className="size-5" />
                </span>
                <span className="min-w-0">
                  <span className="block text-xs text-muted-foreground">WhatsApp</span>
                  <span className="block text-sm font-bold">Tuma ujumbe sasa</span>
                </span>
              </a>

              <a
                href="mailto:info@selvix.online"
                className="flex items-center gap-3 rounded-2xl border border-border bg-card px-4 py-3 transition-colors hover:border-primary/50 hover:bg-accent"
              >
                <span className="flex size-10 shrink-0 items-center justify-center rounded-full bg-primary/15 text-primary">
                  <Mail className="size-5" />
                </span>
                <span className="min-w-0">
                  <span className="block text-xs text-muted-foreground">Barua pepe</span>
                  <span className="block truncate text-sm font-bold">info@selvix.online</span>
                </span>
              </a>
            </div>
          </DialogContent>
        </Dialog>

        <div className="mt-6 text-center">
          <p className="flex items-center justify-center gap-2 text-sm font-semibold">
            <ShieldCheck className="size-4 text-primary" /> Secure Login
          </p>
          <p className="mt-1 text-xs text-muted-foreground">
            Taarifa zako zinalindwa kwa usalama wa hali ya juu.
          </p>
        </div>
      </main>

      <footer className="relative z-10 mt-6">
        <div className="grid gap-6 bg-primary-deep px-6 py-8 text-primary-foreground sm:grid-cols-3">
          {[
            { icon: ShieldCheck, t: "Salama", d: "Taarifa zako zinalindwa kwa usalama wa hali ya juu." },
            { icon: Headphones, t: "Msaada", d: "Tupo kusaidia wakati wowote." },
            { icon: Clock, t: "Haraka", d: "Huduma zetu ni za haraka na rahisi." },
          ].map((f) => (
            <div key={f.t} className="flex items-start gap-3">
              <span className="flex size-11 shrink-0 items-center justify-center rounded-full bg-primary-foreground/15">
                <f.icon className="size-5" />
              </span>
              <div>
                <p className="font-bold">{f.t}</p>
                <p className="text-sm opacity-85">{f.d}</p>
              </div>
            </div>
          ))}
        </div>
        <div className="bg-muted px-6 py-5 text-center text-xs text-muted-foreground">
          <p>
            Copyright © {new Date().getFullYear()} WAMAKINDA MICROFINANCE COMPANY LIMITED. All
            rights reserved.
          </p>
          <p className="mt-1">
            Powered by <PoweredBy />
          </p>
        </div>
      </footer>
    </div>
  );
}
