import { A, useLocation, useNavigate } from "@solidjs/router";
import { ParentComponent, Show, createSignal, onMount, onCleanup } from "solid-js";
import { useAuth } from "../providers/auth-provider";
import { useI18n } from "../providers/i18n-provider";
import { useTheme } from "../providers/theme-provider";
import { BookraCharacter } from "./bookra-character";
import {
  Button,
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  Input,
} from "./ui";

// Icon components - refined with consistent sizing
const SunIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
    <circle cx="12" cy="12" r="4" />
    <path d="M12 2v2" />
    <path d="M12 20v2" />
    <path d="m4.93 4.93 1.41 1.41" />
    <path d="m17.66 17.66 1.41 1.41" />
    <path d="M2 12h2" />
    <path d="M20 12h2" />
    <path d="m6.34 17.66-1.41 1.41" />
    <path d="m19.07 4.93-1.41 1.41" />
  </svg>
);

const MoonIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
    <path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z" />
  </svg>
);

const GlobeIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
    <circle cx="12" cy="12" r="10" />
    <line x1="2" y1="12" x2="22" y2="12" />
    <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" />
  </svg>
);

const MenuIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
    <line x1="3" y1="12" x2="21" y2="12" />
    <line x1="3" y1="6" x2="21" y2="6" />
    <line x1="3" y1="18" x2="21" y2="18" />
  </svg>
);

const XIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
    <path d="M18 6 6 18" />
    <path d="m6 6 12 12" />
  </svg>
);

const GoogleIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" aria-hidden="true">
    <path fill="#EA4335" d="M12 10.2v3.9h5.4c-.2 1.3-1.5 3.9-5.4 3.9-3.2 0-5.9-2.7-5.9-6s2.7-6 5.9-6c1.8 0 3 .8 3.7 1.5l2.5-2.4C16.7 3.6 14.6 2.7 12 2.7 6.9 2.7 2.8 6.8 2.8 12S6.9 21.3 12 21.3c6.9 0 8.6-6.4 8.6-9.6 0-.6-.1-1-.2-1.5H12Z" />
    <path fill="#34A853" d="M3.9 7 7 9.2c.8-2.2 2.8-3.8 5-3.8 1.8 0 3 .8 3.7 1.5l2.5-2.4C16.7 3.6 14.6 2.7 12 2.7 8.2 2.7 4.9 4.9 3.9 7Z" />
    <path fill="#4A90E2" d="M12 21.3c2.5 0 4.6-.8 6.1-2.2l-2.8-2.3c-.8.6-1.8 1-3.3 1-3.8 0-4.9-2.5-5.2-3.7l-3 2.3c1 2.1 4.2 4.9 8.2 4.9Z" />
    <path fill="#FBBC05" d="M6.8 14.1a6.4 6.4 0 0 1 0-4.1L3.9 7a9.4 9.4 0 0 0 0 10l2.9-2.9Z" />
  </svg>
);

export const Shell: ParentComponent = (props) => {
  const auth = useAuth();
  const i18n = useI18n();
  const theme = useTheme();
  const location = useLocation();
  const navigate = useNavigate();
  const [mobileMenuOpen, setMobileMenuOpen] = createSignal(false);
  const hideHeader = () => location.pathname.startsWith("/dashboard");
  const hideFooter = () => location.pathname.startsWith("/dashboard");
  const [signInOpen, setSignInOpen] = createSignal(false);
  const [authMode, setAuthMode] = createSignal<"sign-in" | "register">("sign-in");
  const [name, setName] = createSignal("");
  const [email, setEmail] = createSignal("");
  const [password, setPassword] = createSignal("");
  const [confirmPassword, setConfirmPassword] = createSignal("");
  const [authError, setAuthError] = createSignal<string | null>(null);
  const [authNotice, setAuthNotice] = createSignal<string | null>(null);
  const [authSubmitting, setAuthSubmitting] = createSignal(false);
  const showGoogleSignIn = () => auth.supportsGoogleSignIn() && authMode() === "sign-in";
  const isDark = () => theme.resolvedTheme() === "dark";

  const navLinks = [
    { href: "/pricing", label: i18n.t("nav.pricing") },
    { href: "/about", label: i18n.t("nav.about") },
    { href: "/contact", label: i18n.t("nav.contact") },
  ];

  // Demo mode detection
  const isDemoMode = () => {
    const hostname = window.location.hostname;
    return hostname.includes("demo") || hostname === "localhost" || hostname === "127.0.0.1";
  };

  // Listen for custom event to open auth dialog from dashboard
  onMount(() => {
    const handleOpenAuth = (e: Event) => {
      const customEvent = e as CustomEvent;
      setAuthMode(customEvent.detail?.mode || "sign-in");
      setSignInOpen(true);
    };
    window.addEventListener("openAuthDialog", handleOpenAuth);
    onCleanup(() => {
      window.removeEventListener("openAuthDialog", handleOpenAuth);
    });
  });

  const submitSignIn = async () => {
    setAuthSubmitting(true);
    setAuthError(null);
    setAuthNotice(null);
    try {
      if (authMode() === "register") {
        if (password().length < 8) {
          throw new Error(i18n.t("auth.passwordTooShort"));
        }
        if (password() !== confirmPassword()) {
          throw new Error(i18n.t("auth.passwordMismatch"));
        }
        await auth.signUpWithEmail(name().trim(), email().trim(), password());
      } else {
        await auth.signInWithEmail(email().trim(), password());
      }
      setSignInOpen(false);
      setName("");
      setEmail("");
      setPassword("");
      setConfirmPassword("");
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      // Translate common validation errors
      const translatedError = translateAuthError(errorMessage, i18n.locale());
      setAuthError(translatedError);
    } finally {
      setAuthSubmitting(false);
    }
  };

  // Helper to translate validation error messages
  const translateAuthError = (error: string, locale: string): string => {
    // Email required errors
    if (error.includes("'Email'")) {
      if (locale === 'cs') {
        return 'E-mail je povinný';
      }
      return 'Email is required';
    }
    // Password required errors
    if (error.includes("'Password'")) {
      if (locale === 'cs') {
        return 'Heslo je povinné';
      }
      return 'Password is required';
    }
    // Name required errors (for registration)
    if (error.includes("'Name'")) {
      if (locale === 'cs') {
        return 'Jméno je povinné';
      }
      return 'Name is required';
    }
    // Invalid credentials
    if (error.toLowerCase().includes('invalid') || error.toLowerCase().includes('credentials')) {
      if (locale === 'cs') {
        return 'Neplatné přihlašovací údaje';
      }
      return 'Invalid credentials';
    }
    // Return original if no translation
    return error;
  };

  const sendMagicLink = async () => {
    setAuthSubmitting(true);
    setAuthError(null);
    setAuthNotice(null);
    try {
      await auth.sendMagicLink(email().trim());
      setAuthNotice(i18n.t("auth.magicLinkSent"));
      setPassword("");
    } catch (error) {
      setAuthError(error instanceof Error ? error.message : i18n.t("auth.signInFailed"));
    } finally {
      setAuthSubmitting(false);
    }
  };

  const signInWithGoogle = async () => {
    setAuthSubmitting(true);
    setAuthError(null);
    setAuthNotice(null);
    try {
      await auth.signInWithGoogle();
    } catch (error) {
      setAuthError(error instanceof Error ? error.message : i18n.t("auth.signInFailed"));
      setAuthSubmitting(false);
    }
  };

  return (
    <div class="min-h-screen flex flex-col">
      <Show when={!hideHeader()}>
      <header class="sticky top-0 z-50 w-full border-b border-border/60 bg-canvas/75 backdrop-blur-xl">
        <div class="section-container">
          <div class="flex h-16 items-center justify-between">
            {/* Logo */}
            <A
              class="flex items-center gap-2.5 text-lg font-display font-semibold tracking-tight text-ink hover:text-accent transition-all duration-300 group"
              href="/"
              onClick={() => window.scrollTo(0, 0)}
            >
              <div class="relative h-8">
                <img
                  src="/bookra-illustrations/logo_text_horizontal.svg"
                  alt="Bookra"
                  class="h-8 w-auto absolute inset-0 transition-opacity duration-200"
                  classList={{ "opacity-0": isDark(), "opacity-75": !isDark() }}
                />
                <img
                  src="/bookra-illustrations/logo_text_horizontal_white.svg"
                  alt="Bookra"
                  class="h-8 w-auto absolute inset-0 transition-opacity duration-200"
                  classList={{ "opacity-0": !isDark(), "opacity-75": isDark() }}
                />
              </div>
            </A>

            {/* Desktop Navigation */}
            <nav class="hidden md:flex items-center gap-1">
              {navLinks.map((link) => (
                <A
                  class="relative px-4 py-2 text-sm font-display font-medium text-ink-muted hover:text-ink transition-all duration-300 rounded-lg hover:bg-canvas-subtle group"
                  href={link.href}
                  activeClass="text-ink bg-canvas-subtle"
                  onClick={() => window.scrollTo(0, 0)}
                >
                  {link.label}
                  <span class="absolute bottom-1 left-1/2 -translate-x-1/2 w-0 h-0.5 bg-accent rounded-full transition-all duration-300 group-hover:w-4" />
                </A>
              ))}

              <div class="h-5 w-px bg-border mx-1" />

              {/* Theme Toggle */}
              <button
                class="p-2.5 rounded-lg text-ink-muted hover:text-ink hover:bg-canvas-subtle transition-all duration-300 group relative overflow-hidden"
                onClick={() => theme.toggle()}
                type="button"
                aria-label={theme.resolvedTheme() === "dark" ? "Switch to light mode" : "Switch to dark mode"}
              >
                <span class="relative z-10 transition-transform duration-300 group-hover:scale-110">
                  <Show when={theme.resolvedTheme() === "dark"} fallback={<SunIcon />}>
                    <MoonIcon />
                  </Show>
                </span>
                <span class="absolute inset-0 bg-canvas-subtle scale-0 group-hover:scale-100 transition-transform duration-300 rounded-lg" />
              </button>

              {/* Language Toggle */}
              <button
                class="flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-display font-medium text-ink-muted hover:text-ink hover:bg-canvas-subtle transition-all duration-200"
                onClick={() => i18n.toggleLocale()}
                type="button"
              >
                <GlobeIcon />
                <span class="uppercase">{i18n.locale()}</span>
              </button>

              <div class="h-5 w-px bg-border mx-1" />

              {/* Auth */}
              <Show
                when={auth.session()}
                fallback={
                  <Show when={isDemoMode()} fallback={
                    <Button
                      size="sm"
                      onClick={() => {
                        setAuthMode("sign-in");
                        setSignInOpen(true);
                      }}
                    >
                      {i18n.t("auth.signIn")}
                    </Button>
                  }>
                    <Button
                      size="sm"
                      variant="secondary"
                      onClick={async () => {
                        await auth.signInAsDemo();
                        navigate("/dashboard");
                      }}
                    >
                      {i18n.locale() === 'cs' ? 'Demo režim - bez přihlášení' : 'Demo mode - no login'}
                    </Button>
                  </Show>
                }
              >
                <Button
                  variant="secondary"
                  size="sm"
                  onClick={() => void auth.signOut()}
                >
                  {i18n.t("auth.signOut")}
                </Button>
              </Show>
            </nav>

            {/* Mobile Menu Button */}
            <button
              class="md:hidden p-2.5 rounded-lg text-ink-muted hover:text-ink hover:bg-canvas-subtle transition-all duration-200"
              onClick={() => setMobileMenuOpen(!mobileMenuOpen())}
              type="button"
              aria-label={mobileMenuOpen() ? "Close menu" : "Open menu"}
              aria-expanded={mobileMenuOpen()}
            >
              <Show when={mobileMenuOpen()} fallback={<MenuIcon />}>
                <XIcon />
              </Show>
            </button>
          </div>
        </div>

        {/* Mobile Menu */}
        <Show when={mobileMenuOpen()}>
          <div class="md:hidden border-t border-border/60 bg-canvas/95 backdrop-blur-xl animate-slide-down">
            <div class="section-container py-4 space-y-2">
              {navLinks.map((link) => (
                <A
                  class="block px-4 py-3 text-base font-display font-medium text-ink-muted hover:text-ink hover:bg-canvas-subtle rounded-lg transition-all duration-200"
                  href={link.href}
                  onClick={() => {
                    setMobileMenuOpen(false);
                    window.scrollTo(0, 0);
                  }}
                >
                  {link.label}
                </A>
              ))}

              <div class="pt-2 border-t border-border/60 space-y-2">
                <div class="flex items-center gap-4 px-4 py-2">
                  <button
                    class="flex items-center gap-2 p-2 rounded-lg text-ink-muted hover:text-ink hover:bg-canvas-subtle transition-all duration-200"
                    onClick={() => theme.toggle()}
                    type="button"
                  >
                    <Show when={theme.resolvedTheme() === "dark"} fallback={<SunIcon />}>
                      <MoonIcon />
                    </Show>
                    <span class="text-sm font-medium">
                      {theme.resolvedTheme() === "dark" ? "Light mode" : "Dark mode"}
                    </span>
                  </button>

                  <button
                    class="flex items-center gap-2 p-2 rounded-lg text-ink-muted hover:text-ink hover:bg-canvas-subtle transition-all duration-200"
                    onClick={() => i18n.toggleLocale()}
                    type="button"
                  >
                    <GlobeIcon />
                    <span class="text-sm font-medium uppercase">{i18n.locale()}</span>
                  </button>
                </div>

                <Show
                  when={auth.session()}
                  fallback={
                    <Show when={isDemoMode()} fallback={
                      <Button
                        fullWidth
                        onClick={() => {
                          setAuthMode("sign-in");
                          setSignInOpen(true);
                          setMobileMenuOpen(false);
                        }}
                      >
                        {i18n.t("auth.signIn")}
                      </Button>
                    }>
                      <Button
                        fullWidth
                        variant="secondary"
                        onClick={async () => {
                          await auth.signInAsDemo();
                          setMobileMenuOpen(false);
                          navigate("/dashboard");
                        }}
                      >
                        {i18n.locale() === 'cs' ? 'Demo režim - bez přihlášení' : 'Demo mode - no login'}
                      </Button>
                    </Show>
                  }
                >
                  <Button
                    variant="secondary"
                    fullWidth
                    onClick={() => {
                      void auth.signOut();
                      setMobileMenuOpen(false);
                    }}
                  >
                    {i18n.t("auth.signOut")}
                  </Button>
                </Show>
              </div>
            </div>
          </div>
        </Show>
      </header>
      </Show>

      <main class="flex-1">{props.children}</main>

      <Show when={!hideFooter()}>
      {/* Footer */}
      <footer class="border-t border-border/60 py-16 bg-canvas-subtle/40">
        <div class="section-container">
          <div class="grid grid-cols-1 md:grid-cols-4 gap-12 mb-12">
            {/* Logo & Description */}
            <div class="md:col-span-2 space-y-4">
              <A href="/" class="inline-flex items-center gap-4 group" onClick={() => window.scrollTo(0, 0)}>
                <div class="relative h-10">
                  <img
                    src="/bookra-illustrations/logo_text_horizontal.svg"
                    alt="Bookra"
                    class="h-10 w-auto absolute inset-0 transition-opacity duration-200"
                    classList={{ "opacity-0": isDark(), "opacity-90": !isDark() }}
                  />
                  <img
                    src="/bookra-illustrations/logo_text_horizontal_white.svg"
                    alt="Bookra"
                    class="h-10 w-auto absolute inset-0 transition-opacity duration-200"
                    classList={{ "opacity-0": !isDark(), "opacity-90": isDark() }}
                  />
                </div>
              </A>
              <p class="text-ink-muted max-w-sm leading-relaxed">
                {i18n.t("footer.description")}
              </p>
            </div>

            {/* Navigation Links */}
            <div class="space-y-4">
              <h4 class="font-display font-semibold text-ink">{i18n.t("footer.links.title")}</h4>
              <ul class="space-y-2">
                <li>
                  <A href="/about" class="text-ink-muted hover:text-ink transition-colors duration-200" onClick={() => window.scrollTo(0, 0)}>
                    {i18n.t("nav.about")}
                  </A>
                </li>
                <li>
                  <A href="/contact" class="text-ink-muted hover:text-ink transition-colors duration-200" onClick={() => window.scrollTo(0, 0)}>
                    {i18n.t("nav.contact")}
                  </A>
                </li>
                <li>
                  <A href="/#pricing" class="text-ink-muted hover:text-ink transition-colors duration-200" onClick={() => window.scrollTo(0, 0)}>
                    {i18n.t("home.pricing.title")}
                  </A>
                </li>
              </ul>
            </div>

            {/* Legal Links */}
            <div class="space-y-4">
              <h4 class="font-display font-semibold text-ink">{i18n.t("footer.legal.title")}</h4>
              <ul class="space-y-2">
                <li>
                  <A href="/privacy" class="text-ink-muted hover:text-ink transition-colors duration-200" onClick={() => window.scrollTo(0, 0)}>
                    {i18n.t("footer.privacy")}
                  </A>
                </li>
                <li>
                  <A href="/terms" class="text-ink-muted hover:text-ink transition-colors duration-200" onClick={() => window.scrollTo(0, 0)}>
                    {i18n.t("footer.terms")}
                  </A>
                </li>
              </ul>
            </div>
          </div>

          {/* Bottom Bar */}
          <div class="pt-8 border-t border-border/60 flex flex-col md:flex-row items-center justify-between gap-4">
            <p class="text-sm text-ink-subtle font-sans">
              {i18n.t("footer.copyright")}
            </p>
            <div class="flex items-center gap-2 text-sm text-ink-subtle">
              <span>Made with</span>
              <span class="text-accent">♥</span>
              <span>in Czech Republic</span>
            </div>
          </div>
        </div>
      </footer>
      </Show>

      <Dialog open={signInOpen()} onClose={() => setSignInOpen(false)}>
        <DialogHeader>
          <div class="mb-2 flex justify-center">
            <BookraCharacter
              pose={authMode() === "register" ? "announcement" : "hello"}
              size="md"
              animate={true}
            />
          </div>
          <DialogTitle>{authMode() === "register" ? i18n.t("auth.registerTitle") : i18n.t("auth.signInTitle")}</DialogTitle>
          <DialogDescription>{authMode() === "register" ? i18n.t("auth.registerBody") : i18n.t("auth.signInBody")}</DialogDescription>
        </DialogHeader>
        <DialogContent>
          <form
            class="space-y-4"
            onSubmit={(event) => {
              event.preventDefault();
              void submitSignIn();
            }}
          >
            <Show when={authMode() === "register"}>
              <Input
                autocomplete="name"
                label={i18n.t("auth.fullName")}
                onInput={(event) => setName(event.currentTarget.value)}
                required
                value={name()}
              />
            </Show>
            <Input
              autocomplete="email"
              label={i18n.t("auth.email")}
              onInput={(event) => setEmail(event.currentTarget.value)}
              required
              type="email"
              value={email()}
            />
            <Input
              autocomplete="current-password"
              label={i18n.t("auth.password")}
              onInput={(event) => setPassword(event.currentTarget.value)}
              required
              type="password"
              value={password()}
            />
            <Show when={authMode() === "register"}>
              <Input
                autocomplete="new-password"
                label={i18n.t("auth.confirmPassword")}
                onInput={(event) => setConfirmPassword(event.currentTarget.value)}
                required
                type="password"
                value={confirmPassword()}
              />
            </Show>
            <Show when={authError()}>
              <p class="rounded-card border border-error/20 bg-error-subtle px-4 py-3 text-sm text-error">
                {authError()}
              </p>
            </Show>
            <Show when={authNotice()}>
              <p class="rounded-card border border-success/20 bg-success-subtle px-4 py-3 text-sm text-success">
                {authNotice()}
              </p>
            </Show>
            <button class="hidden" type="submit" />
          </form>
        </DialogContent>
        <DialogFooter class="flex-col gap-3">
          <Show when={showGoogleSignIn()}>
            <Button
              variant="secondary"
              onClick={() => void signInWithGoogle()}
              fullWidth
              disabled={authSubmitting()}
            >
              <span class="flex items-center justify-center gap-2">
                <GoogleIcon />
                {i18n.t("auth.continueWithGoogle")}
              </span>
            </Button>
          </Show>
          <Button 
            isLoading={authSubmitting()} 
            onClick={() => void submitSignIn()}
            fullWidth
            class="shadow-lg"
          >
            {authMode() === "register" ? i18n.t("auth.createAccount") : i18n.t("auth.signIn")}
          </Button>
          <Button
            variant="ghost"
            onClick={() => {
              setAuthError(null);
              setAuthNotice(null);
              setAuthMode(authMode() === "register" ? "sign-in" : "register");
            }}
            fullWidth
          >
            {authMode() === "register" ? i18n.t("auth.signIn") : i18n.t("auth.createAccount")}
          </Button>
        </DialogFooter>
      </Dialog>
    </div>
  );
};
