"use client";

import { useState, type FormEvent } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Mail, Lock, Loader2, Check } from "lucide-react";
import type { AxiosError } from "axios";
import { loginApi } from "@/api/client";
import { useAuthStore } from "@/store/authStore";

// ─── Toast helper ─────────────────────────────────────────────────────────────

type ToastState = { message: string; variant: "success" | "error" } | null;

function Toast({ toast }: { toast: ToastState }) {
  if (!toast) return null;
  const isSuccess = toast.variant === "success";
  return (
    <div
      className={`fixed top-12 left-1/2 -translate-x-1/2 z-50 flex items-center gap-2 px-5 py-2.5 rounded-full shadow-xl text-white text-[13px] font-medium whitespace-nowrap transition-all ${
        isSuccess ? "bg-[#16A34A]" : "bg-[#E32636]"
      }`}
      aria-live="polite"
    >
      {isSuccess && <Check size={14} strokeWidth={2.5} />}
      {toast.message}
    </div>
  );
}

// ─── Input field ──────────────────────────────────────────────────────────────

function Field({
  id,
  label,
  type,
  value,
  onChange,
  placeholder,
  icon: Icon,
  autoComplete,
}: {
  id: string;
  label: string;
  type: string;
  value: string;
  onChange: (v: string) => void;
  placeholder: string;
  icon: React.ElementType;
  autoComplete?: string;
}) {
  return (
    <div className="flex flex-col gap-1.5">
      <label htmlFor={id} className="text-[13px] font-medium text-[#8E8E93]">
        {label}
      </label>
      <div className="flex items-center gap-3 bg-[#1C1C1E] border border-[#2C2C2E] focus-within:border-[#E32636] rounded-xl px-4 py-3.5 transition-colors">
        <Icon size={16} className="text-[#8E8E93] flex-shrink-0" strokeWidth={2} />
        <input
          id={id}
          type={type}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder}
          autoComplete={autoComplete}
          required
          className="flex-1 bg-transparent text-[15px] text-white placeholder-[#4B5563] outline-none"
        />
      </div>
    </div>
  );
}

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function LoginPage() {
  const router   = useRouter();
  const setToken = useAuthStore((s) => s.setToken);

  const [email, setEmail]       = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading]   = useState(false);
  const [toast, setToast]       = useState<ToastState>(null);

  function showToast(message: string, variant: "success" | "error") {
    setToast({ message, variant });
    setTimeout(() => setToast(null), 3000);
  }

  async function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    if (loading) return;

    setLoading(true);
    try {
      const { access_token } = await loginApi(email, password);
      setToken(access_token);
      showToast("Успешно", "success");
      // Short delay so the user sees the success toast before navigation
      setTimeout(() => router.push("/tickets"), 900);
    } catch (err) {
      const axiosErr = err as AxiosError;
      const status = axiosErr.response?.status;
      if (status === 401 || status === 422) {
        showToast("Ошибка авторизации", "error");
      } else {
        showToast("Ошибка сети. Попробуйте снова.", "error");
      }
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="flex justify-center min-h-screen bg-[#121212]">
      <div className="w-full max-w-[390px] flex flex-col px-5 pt-20 pb-10">

        <Toast toast={toast} />

        {/* ── Brand ── */}
        <div className="mb-10">
          <div className="w-12 h-12 bg-[#E32636] rounded-2xl flex items-center justify-center mb-5">
            <span className="text-white text-[22px] font-extrabold leading-none">F</span>
          </div>
          <h1 className="text-[30px] font-bold text-white leading-tight">
            Вход в аккаунт
          </h1>
          <p className="text-[14px] text-[#8E8E93] mt-1">
            Войдите, чтобы управлять билетами
          </p>
        </div>

        {/* ── Form ── */}
        <form onSubmit={handleSubmit} noValidate className="flex flex-col gap-4">
          <Field
            id="email"
            label="Email"
            type="email"
            value={email}
            onChange={setEmail}
            placeholder="you@example.com"
            icon={Mail}
            autoComplete="email"
          />
          <Field
            id="password"
            label="Пароль"
            type="password"
            value={password}
            onChange={setPassword}
            placeholder="Минимум 8 символов"
            icon={Lock}
            autoComplete="current-password"
          />

          <button
            type="submit"
            disabled={loading}
            className="mt-2 w-full flex items-center justify-center gap-2 bg-[#E32636] hover:bg-[#C41E2A] disabled:opacity-60 disabled:cursor-not-allowed active:scale-95 transition-all text-white text-[16px] font-bold py-4 rounded-2xl"
          >
            {loading ? (
              <>
                <Loader2 size={18} className="animate-spin" />
                Вход…
              </>
            ) : (
              "Войти"
            )}
          </button>
        </form>

        {/* ── Footer links ── */}
        <div className="mt-6 flex flex-col items-center gap-3">
          <p className="text-[14px] text-[#8E8E93]">
            Нет аккаунта?{" "}
            <Link
              href="/register"
              className="text-white font-semibold hover:text-[#E32636] transition-colors"
            >
              Создать
            </Link>
          </p>
          <Link
            href="/"
            className="text-[13px] text-[#8E8E93] hover:text-white transition-colors"
          >
            ← Вернуться к событиям
          </Link>
        </div>

      </div>
    </div>
  );
}
