"use client";

import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { ArrowRight, KeyRound, MonitorSmartphone, ShieldCheck } from "lucide-react";

import { Button } from "../ui/button";
import { Card } from "../ui/card";
import { Input } from "../ui/input";
import { loginRequest } from "../../lib/api";
import { useSessionContext } from "../layout/session-provider";

export const LoginPageContent = () => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const router = useRouter();
  const searchParams = useSearchParams();
  const { session, setSession } = useSessionContext();

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

    try {
      const nextSession = await loginRequest(email, password);
      setSession(nextSession);
      router.replace(nextSession.user.role === "technik" ? "/operations" : searchParams.get("next") || "/dashboard");
    } catch (requestError) {
      setError(requestError instanceof Error ? requestError.message : "Nie udało się zalogować");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex min-h-screen items-start justify-center px-4 py-6 sm:py-8 lg:items-center">
      <div className="grid w-full max-w-6xl gap-4 lg:grid-cols-[1.2fr_0.9fr] lg:gap-6">
        <Card className="order-2 overflow-hidden lg:order-1">
          <div className="h-full bg-[linear-gradient(135deg,#176a65_0%,#1e4f5b_48%,#d2a55a_100%)] p-6 text-white sm:p-8 lg:p-10">
            <p className="text-xs uppercase tracking-[0.28em] text-white/70">Rental operations</p>
            <h1 className="mt-3 max-w-xl text-3xl font-semibold leading-tight sm:text-4xl lg:text-5xl">
              Oś czasu wynajmu sprzętu IT gotowa do pracy operacyjnej.
            </h1>
            <p className="mt-5 max-w-2xl text-base text-white/82 sm:text-lg">
              Jedna aplikacja do planowania dostępności, pracy mobilnej na telefonie i pełnej administracji flotą.
            </p>

            <div className="mt-8 grid gap-4 sm:grid-cols-3 lg:mt-10">
              <div className="rounded-3xl border border-white/15 bg-white/10 p-4">
                <MonitorSmartphone className="h-5 w-5" />
                <p className="mt-4 text-sm font-semibold">Desktop i telefon</p>
                <p className="mt-1 text-sm text-white/75">Ten sam timeline i ta sama logika rezerwacji na każdym urządzeniu.</p>
              </div>
              <div className="rounded-3xl border border-white/15 bg-white/10 p-4">
                <KeyRound className="h-5 w-5" />
                <p className="mt-4 text-sm font-semibold">Role i bezpieczeństwo</p>
                <p className="mt-1 text-sm text-white/75">JWT, kontrola dostępu i bezpieczne hasła dla admina, operatora i viewerów.</p>
              </div>
              <div className="rounded-3xl border border-white/15 bg-white/10 p-4">
                <ShieldCheck className="h-5 w-5" />
                <p className="mt-4 text-sm font-semibold">Brak konfliktów</p>
                <p className="mt-1 text-sm text-white/75">Rezerwacje nie mogą nachodzić na siebie dla tego samego egzemplarza.</p>
              </div>
            </div>
          </div>
        </Card>

        <Card className="order-1 p-5 sm:p-6 lg:order-2 lg:p-8">
          <p className="text-xs uppercase tracking-[0.28em] text-muted">Logowanie</p>
          <h2 className="mt-3 text-2xl font-semibold text-ink">Zaloguj się do systemu</h2>
          <p className="mt-2 text-sm text-muted">
            Podaj konto przypisane do tego serwera. Na telefonie formularz nie używa autokorekty ani automatycznej zmiany wielkości liter.
          </p>
          {session ? (
            <p className="mt-3 rounded-2xl bg-[#edf6ee] px-4 py-3 text-sm text-[#2f6940]">
              W przeglądarce jest już zapisana sesja. Możesz zalogować się ponownie tym formularzem, jeśli poprzedni token był nieaktualny.
            </p>
          ) : null}

          <form className="mt-6 space-y-4 sm:mt-8" onSubmit={onSubmit}>
            <label className="block space-y-2">
              <span className="text-sm font-medium text-ink">E-mail</span>
              <Input
                autoCapitalize="none"
                autoComplete="username"
                autoCorrect="off"
                inputMode="email"
                placeholder="admin@rental.local"
                spellCheck={false}
                type="email"
                value={email}
                onChange={(event) => setEmail(event.target.value)}
              />
            </label>

            <label className="block space-y-2">
              <span className="text-sm font-medium text-ink">Hasło</span>
              <Input
                autoCapitalize="none"
                autoComplete="current-password"
                autoCorrect="off"
                placeholder="Hasło"
                spellCheck={false}
                type="password"
                value={password}
                onChange={(event) => setPassword(event.target.value)}
              />
            </label>

            {error ? <p className="rounded-2xl bg-[#f8d9d3] px-4 py-3 text-sm text-[#8d2f20]">{error}</p> : null}

            <Button className="w-full" type="submit" disabled={loading}>
              {loading ? "Logowanie..." : "Wejdź do systemu"}
              <ArrowRight className="h-4 w-4" />
            </Button>
          </form>
        </Card>
      </div>
    </div>
  );
};
