"use client";

import { motion } from "framer-motion";
import { ArrowRight, BadgeCheck, LockKeyhole, Mail, Phone, ShieldCheck, Sparkles } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { useParams, useSearchParams } from "next/navigation";
import { useCallback, useEffect, useMemo, useState } from "react";
import { getSupabaseClient } from "@/lib/supabase";
import { entrarComGoogle } from "@/lib/login-com-google";
import { getAccessibleAccent, getReadableTextColor } from "@/lib/color-contrast";

type Mode = "login" | "register";

function isLikelyEmail(value: string) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(value || "").trim());
}

function hexToRgba(hex: string, alpha: number) {
  const normalized = String(hex || "").trim().replace("#", "");
  const safe = normalized.length === 3
    ? normalized
        .split("")
        .map((char) => `${char}${char}`)
        .join("")
    : normalized;
  if (!/^[0-9a-fA-F]{6}$/.test(safe)) return `rgba(68, 37, 167, ${alpha})`;
  const int = parseInt(safe, 16);
  const r = (int >> 16) & 255;
  const g = (int >> 8) & 255;
  const b = int & 255;
  return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}

function GoogleIcon() {
  return (
    <svg
      aria-hidden="true"
      width="18"
      height="18"
      viewBox="0 0 24 24"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      className="shrink-0"
    >
      <path
        d="M23.5 12.27c0-.82-.07-1.61-.22-2.36H12v4.47h6.45a5.51 5.51 0 0 1-2.39 3.62v3h3.87c2.26-2.08 3.57-5.15 3.57-8.73z"
        fill="#4285F4"
      />
      <path
        d="M12 24c3.24 0 5.96-1.07 7.95-2.9l-3.87-3A7.2 7.2 0 0 1 12 19.26a7.18 7.18 0 0 1-6.76-4.95H1.24v3.1A12 12 0 0 0 12 24z"
        fill="#34A853"
      />
      <path
        d="M5.24 14.31A7.2 7.2 0 0 1 4.86 12c0-.8.14-1.58.38-2.31v-3.1H1.24A12 12 0 0 0 0 12c0 1.93.46 3.76 1.24 5.41l4-3.1z"
        fill="#FBBC05"
      />
      <path
        d="M12 4.74c1.77 0 3.35.61 4.6 1.8l3.44-3.44C17.95 1.14 15.23 0 12 0 7.31 0 3.27 2.69 1.24 6.59l4 3.1A7.18 7.18 0 0 1 12 4.74z"
        fill="#EA4335"
      />
    </svg>
  );
}

export default function ClientPortalAuthCard({
  slug,
  storeName,
  logoUrl,
  primaryColor,
  modoDeCadastro = "open",
  exigirCnpj = false,
  mensagemDeLogin = null,
  precoSoParaClientes = false,
}: {
  slug: string;
  storeName: string;
  logoUrl: string;
  primaryColor: string;
  /* Regras da loja: cadastro livre, com aprovacao ou fechado (so a loja cria o acesso). */
  modoDeCadastro?: "open" | "approval" | "closed";
  exigirCnpj?: boolean;
  mensagemDeLogin?: string | null;
  precoSoParaClientes?: boolean;
}) {
  const cadastroFechado = modoDeCadastro === "closed";
  const params = useParams<{ slug: string }>();
  const searchParams = useSearchParams();
  const resolvedSlug = String(params?.slug || slug || "");
  const nextUrl = searchParams.get("next") || "";
  const veioDoCheckout = nextUrl.includes("/checkout");
  const supabase = useMemo(() => getSupabaseClient(), []);

  const goToClientPortal = useCallback(
    (url?: string) => {
      window.location.assign(url || `/${resolvedSlug}/cliente`);
    },
    [resolvedSlug]
  );

  const [mode, setMode] = useState<Mode>("login");
  const [loading, setLoading] = useState(false);
  const [googleLoading, setGoogleLoading] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");
  const [identifier, setIdentifier] = useState("");
  const [password, setPassword] = useState("");
  const [document, setDocument] = useState("");
  const [name, setName] = useState("");
  const resetHref = useMemo(() => {
    const query = isLikelyEmail(identifier) ? `?email=${encodeURIComponent(identifier.trim())}` : "";
    return `/${resolvedSlug}/cliente/redefinir-senha${query}`;
  }, [identifier, resolvedSlug]);

  useEffect(() => {
    const nextMode = searchParams.get("mode");
    const nextError = searchParams.get("error");
    const nextSuccess = searchParams.get("success");
    if (nextMode === "login" || (nextMode === "register" && !cadastroFechado)) {
      setMode(nextMode);
    }
    setError(nextError || "");
    setSuccess(nextSuccess || "");
  }, [searchParams, cadastroFechado]);

  useEffect(() => {
    let active = true;
    async function finishGoogleLogin() {
      if (searchParams.get("oauth") !== "google") return;
      setGoogleLoading(true);
      setError("");
      try {
        const { data, error } = await supabase.auth.getSession();
        if (error || !data?.session?.access_token) {
          throw new Error("Não foi possível validar sua conta Google.");
        }
        const response = await fetch("/api/client-portal/google-login", {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({
            slug: resolvedSlug,
            access_token: data.session.access_token,
            next: nextUrl,
          }),
        });
        const payload = (await response.json()) as { error?: string; redirect_url?: string };
        if (!response.ok || payload.error) {
          throw new Error(
            payload.error ||
              "Seu Google não está vinculado a um cliente desta loja. Peça para a loja cadastrar esse e-mail no seu cliente."
          );
        }
        if (!active) return;
        goToClientPortal(payload.redirect_url);
      } catch (err) {
        if (!active) return;
        const message =
          typeof err === "object" && err && "message" in err && typeof err.message === "string"
            ? err.message
            : "Falha no login com Google.";
        setError(message);
      } finally {
        if (active) setGoogleLoading(false);
      }
    }
    finishGoogleLogin();
    return () => {
      active = false;
    };
  }, [goToClientPortal, resolvedSlug, searchParams, supabase.auth]);

  function handleSubmit(event: React.FormEvent) {
    if (loading || !resolvedSlug) {
      event.preventDefault();
      return;
    }
    setLoading(true);
    setError("");
    setSuccess("");
  }

  async function handleGoogleLogin() {
    if (googleLoading) return;
    setGoogleLoading(true);
    setError("");
    try {
      /* Em loja com dominio proprio, a sessao volta para ca por uma passagem
         (lib/login-com-google.ts): o carrinho continua onde estava. */
      await entrarComGoogle({ slug: resolvedSlug, next: nextUrl });
    } catch (err) {
      const message =
        typeof err === "object" && err && "message" in err && typeof err.message === "string"
          ? err.message
          : "Não foi possível iniciar o login com Google.";
      setError(message);
      setGoogleLoading(false);
    }
  }

  return (
    <div className="relative min-h-screen bg-white selection:bg-zinc-100">
      <div className="flex min-h-screen flex-col items-center justify-center p-4 sm:p-8">
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.4 }}
          className="w-full max-w-[440px]"
        >
          <div className="mb-10 text-center">
            {logoUrl ? (
              <Image
                src={logoUrl}
                alt={storeName}
                width={80}
                height={80}
                className="mx-auto mb-6 h-16 w-auto object-contain"
                unoptimized
              />
            ) : (
              <div
                className="mx-auto mb-6 flex h-16 w-16 items-center justify-center rounded-[20px] text-xl font-bold"
                style={{ color: getAccessibleAccent(primaryColor), backgroundColor: hexToRgba(primaryColor, 0.08) }}
              >
                {storeName.slice(0, 2).toUpperCase()}
              </div>
            )}
            {/* Quem vem do carrinho era jogado nesta tela sem uma palavra de
                explicacao, do nada, com o pedido pela metade. Aqui ele entende
                por que precisa entrar e que o carrinho continua guardado. */}
            <h2 className="text-2xl font-semibold tracking-tight text-zinc-900">
              {veioDoCheckout
                ? mode === "login"
                  ? "Falta pouco para fechar o pedido"
                  : "Crie sua conta para fechar o pedido"
                : mode === "login"
                  ? "Acesse sua conta"
                  : "Crie sua conta"}
            </h2>
            <p className="mt-2 text-sm text-zinc-500">
              {veioDoCheckout
                ? "Identifique-se para emitir o pedido e acompanhar a entrega. Seu carrinho está guardado."
                : precoSoParaClientes && mode === "login"
                  ? "Entre para ver os preços e comprar."
                  : mode === "login"
                    ? "Acompanhe seus pedidos e gerencie seus dados."
                    : "Seu acesso para acompanhar compras e entregas."}
            </p>
            {mensagemDeLogin ? (
              /* O recado que o lojista escreveu para esta tela (regras da loja). */
              <p
                className="mx-auto mt-4 max-w-sm rounded-xl px-4 py-3 text-sm leading-relaxed"
                style={{ color: getAccessibleAccent(primaryColor), backgroundColor: hexToRgba(primaryColor, 0.08) }}
              >
                {mensagemDeLogin}
              </p>
            ) : null}
          </div>

          {cadastroFechado ? (
            /* Cadastro fechado: so a loja cria o acesso. A aba "Primeiro
               acesso" some e a pessoa entende o caminho. */
            <p className="mb-6 rounded-xl border border-zinc-200 bg-zinc-50 px-4 py-3 text-center text-[13px] text-zinc-600">
              Esta loja libera o acesso por convite. Se você ainda não tem conta, peça o seu acesso à loja.
            </p>
          ) : (
          <div className="mb-8 grid grid-cols-2 gap-1 rounded-full bg-zinc-100 p-1">
            <button
              type="button"
              onClick={() => setMode("login")}
              className={`rounded-full py-2 text-sm font-medium transition-colors ${
                mode === "login" ? "bg-white text-zinc-900 shadow-sm" : "text-zinc-500 hover:text-zinc-700"
              }`}
            >
              Entrar
            </button>
            <button
              type="button"
              onClick={() => setMode("register")}
              className={`rounded-full py-2 text-sm font-medium transition-colors ${
                mode === "register" ? "bg-white text-zinc-900 shadow-sm" : "text-zinc-500 hover:text-zinc-700"
              }`}
            >
              Primeiro acesso
            </button>
          </div>
          )}

          <button
            type="button"
            onClick={handleGoogleLogin}
            disabled={googleLoading}
            className="mb-6 flex w-full items-center justify-center gap-3 rounded-xl border border-zinc-200 bg-white py-3 text-sm font-medium text-zinc-700 transition-colors hover:bg-zinc-50 focus:outline-none focus:ring-2 focus:ring-zinc-200 focus:ring-offset-2 disabled:opacity-60"
          >
            <GoogleIcon />
            {googleLoading ? "Conectando..." : "Continuar com Google"}
          </button>

          <div className="mb-6 flex items-center gap-4">
            <div className="h-px flex-1 bg-zinc-200" />
            <span className="text-xs text-zinc-400">ou com e-mail/telefone</span>
            <div className="h-px flex-1 bg-zinc-200" />
          </div>

          <form
            action={mode === "login" ? "/api/client-portal/login" : "/api/client-portal/register"}
            method="post"
            onSubmit={handleSubmit}
            className="space-y-4"
          >
            <input type="hidden" name="slug" value={resolvedSlug} />
            <input type="hidden" name="next" value={nextUrl} />

            <div className="space-y-1">
              <label className="text-[13px] font-medium text-zinc-700">E-mail ou Telefone</label>
              <input
                name="identifier"
                value={identifier}
                onChange={(e) => setIdentifier(e.target.value)}
                placeholder="nome@email.com ou (11) 99999-9999"
                className="w-full rounded-xl border border-zinc-200 bg-white px-4 py-3 text-sm text-zinc-900 outline-none transition-colors placeholder:text-zinc-400 focus:border-zinc-400 focus:ring-0"
                required
              />
            </div>

            {mode === "register" && (
              <>
                <div className="space-y-1">
                  <label className="text-[13px] font-medium text-zinc-700">Nome Completo</label>
                  <input
                    name="name"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    placeholder="Seu nome"
                    className="w-full rounded-xl border border-zinc-200 bg-white px-4 py-3 text-sm text-zinc-900 outline-none transition-colors placeholder:text-zinc-400 focus:border-zinc-400 focus:ring-0"
                    required
                  />
                </div>
                <div className="space-y-1">
                  <label className="text-[13px] font-medium text-zinc-700">{exigirCnpj ? "CNPJ" : "CPF ou CNPJ"}</label>
                  <input
                    name="document"
                    value={document}
                    onChange={(e) => setDocument(e.target.value)}
                    placeholder={exigirCnpj ? "CNPJ da sua empresa" : "Somente números ou formatado"}
                    className="w-full rounded-xl border border-zinc-200 bg-white px-4 py-3 text-sm text-zinc-900 outline-none transition-colors placeholder:text-zinc-400 focus:border-zinc-400 focus:ring-0"
                    required
                  />
                </div>
                {modoDeCadastro === "approval" ? (
                  <p className="rounded-xl border border-sky-100 bg-sky-50 px-4 py-3 text-[13px] text-sky-800">
                    Depois do cadastro, a loja aprova o seu acesso. Enquanto isso você já navega, mas os preços e a compra
                    ficam liberados só com a aprovação.
                  </p>
                ) : null}
              </>
            )}

            <div className="space-y-1">
              <label className="text-[13px] font-medium text-zinc-700">Senha</label>
              <input
                name="password"
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="Mínimo 8 caracteres"
                className="w-full rounded-xl border border-zinc-200 bg-white px-4 py-3 text-sm text-zinc-900 outline-none transition-colors placeholder:text-zinc-400 focus:border-zinc-400 focus:ring-0"
                minLength={8}
                required
              />
            </div>

            {mode === "login" ? (
              <div className="flex justify-end">
                <Link href={resetHref} className="text-[13px] font-medium text-zinc-500 transition hover:text-zinc-900">
                  Esqueci minha senha
                </Link>
              </div>
            ) : null}

            {error && (
              <div className="rounded-xl border border-rose-100 bg-rose-50 px-4 py-3 text-[13px] text-rose-600">
                {error}
              </div>
            )}

            {success && (
              <div className="rounded-xl border border-emerald-100 bg-emerald-50 px-4 py-3 text-[13px] text-emerald-600">
                {success}
              </div>
            )}

            <button
              type="submit"
              disabled={loading}
              className="mt-2 flex w-full items-center justify-center rounded-xl px-4 py-3 text-sm font-semibold text-white transition-opacity hover:opacity-90 disabled:opacity-60"
              style={{ backgroundColor: primaryColor, color: getReadableTextColor(primaryColor) }}
            >
              {loading ? "Processando..." : mode === "login" ? "Entrar" : "Criar conta"}
            </button>
          </form>

          <div className="mt-8 text-center">
            <Link 
              href={`/${resolvedSlug}`} 
              className="text-[13px] font-medium text-zinc-500 hover:text-zinc-900"
            >
              &larr; Voltar ao catálogo
            </Link>
          </div>
        </motion.div>
      </div>
    </div>
  );
}
