import { Show, createSignal, type JSX, type ParentComponent } from "solid-js";
import { A, useLocation } from "@solidjs/router";
import { useTheme } from "../../providers/theme-provider";
import { BookraCharacter } from "../../components/bookra-character";
import { IntegrationModal } from "../../components/integration-modal";
import { NotificationDropdown } from "../../components/dashboard/notification-dropdown";
import { getInitials, getBookingDuration } from "../../components/dashboard/types";
import {
  LayoutDashboardIcon, CalendarDaysIcon, CreditCardIcon, Settings2Icon,
  LogOutIcon, MenuIcon, XIcon, SparklesIcon, GlobeIcon, SunIcon, MoonIcon,
  UserCircleIcon, MapPinIcon
} from "../../components/dashboard/icons";
import { DashboardContext, useDashboardData, DashboardDataProvider } from "./dashboard-data";

export { useDashboardData };

const navItems = [
  { id: "overview", label: "dashboard.overview", icon: LayoutDashboardIcon, path: "/dashboard" },
  { id: "bookings", label: "dashboard.bookings", icon: CalendarDaysIcon, path: "/dashboard/bookings" },
  { id: "customers", label: "dashboard.customers", icon: UserCircleIcon, path: "/dashboard/customers" },
  { id: "zones", label: "dashboard.zones", icon: MapPinIcon, path: "/dashboard/zones" },
  { id: "billing", label: "dashboard.billing", icon: CreditCardIcon, path: "/dashboard/billing" },
  { id: "settings", label: "dashboard.settings", icon: Settings2Icon, path: "/dashboard/settings" },
];

function DashboardShell(props: { children: JSX.Element }) {
  const data = useDashboardData();
  const theme = useTheme();
  const location = useLocation();
  const [isMobileMenuOpen, setIsMobileMenuOpen] = createSignal(false);

  const activeSection = () => {
    const p = location.pathname;
    if (p === "/dashboard" || p === "/dashboard/") return "overview";
    const match = navItems.find(item => p === item.path || p.startsWith(item.path + "/"));
    return match?.id ?? "overview";
  };

  const isDark = () => theme.resolvedTheme() === "dark";

  const DashboardLogo = (props: { class?: string }) => (
    <div class={`relative h-8 ${props.class ?? ""}`}>
      <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>
  );

  const LanguageToggle = () => (
    <button
      onClick={() => data.i18n.toggleLocale()}
      class="flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium text-ink-muted hover:text-ink hover:bg-canvas-subtle rounded-lg transition-all"
      title={data.i18n.t("dashboard.language")}
    >
      <GlobeIcon />
      {data.i18n.locale() === "cs" ? "CS" : "EN"}
    </button>
  );

  const ThemeToggle = () => (
    <button
      onClick={() => theme.toggle()}
      class="p-2 text-ink-subtle hover:text-ink hover:bg-canvas-subtle rounded-xl transition-all"
      aria-label="Toggle theme"
    >
      {theme.resolvedTheme() === "dark" ? <SunIcon /> : <MoonIcon />}
    </button>
  );

  const DemoBanner = () => (
    <Show when={data.isDemoMode()}>
      <div class="mb-6 p-4 rounded-xl bg-accent-subtle border border-accent/20 flex items-center justify-between animate-fade-in">
        <div class="flex items-center gap-3 min-w-0">
          <SparklesIcon />
          <div class="min-w-0">
            <p class="text-sm font-semibold text-accent">{data.i18n.t("dashboard.demoBanner")}</p>
            <p class="text-xs text-accent/70">{data.i18n.t("dashboard.demoBannerDesc")}</p>
          </div>
        </div>
        <button
          onClick={() => window.dispatchEvent(new CustomEvent("openAuthDialog", { detail: { mode: "register" } }))}
          class="shrink-0 ml-4 px-4 py-2 bg-accent text-canvas text-sm font-medium rounded-lg hover:bg-accent-hover transition-colors"
        >
          {data.i18n.t("dashboard.demoBannerCTA")}
        </button>
      </div>
    </Show>
  );

  const Sidebar = () => (
    <aside class="hidden lg:flex flex-col w-64 h-screen bg-canvas border-r border-border sticky top-0 shrink-0">
      <div class="p-6">
        <A href="/" class="flex items-center gap-2.5 text-lg font-display font-semibold tracking-tight text-ink hover:text-accent transition-colors">
          <DashboardLogo />
        </A>
      </div>
      <nav class="flex-1 px-4 space-y-1 overflow-y-auto">
        {navItems.map((item) => (
          <A
            href={item.path}
            class={`
              w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-medium transition-all duration-200
              ${activeSection() === item.id
                ? "bg-accent text-canvas shadow-sm"
                : "text-ink-muted hover:bg-canvas-subtle hover:text-ink"
              }
            `}
          >
            <item.icon /> {data.i18n.t(item.label)}
          </A>
        ))}
      </nav>
      <div class="p-4 border-t border-border space-y-1">
        <div class="flex items-center gap-2 px-4 py-2">
          <LanguageToggle />
          <ThemeToggle />
        </div>
        <Show when={data.auth.session()?.user}>
          <div class="flex items-center gap-3 px-4 py-3">
            <div class="w-8 h-8 rounded-full bg-accent-subtle flex items-center justify-center text-sm font-bold text-accent shrink-0">
              {getInitials(data.auth.session()?.user?.name)}
            </div>
            <div class="min-w-0">
              <p class="text-sm font-semibold text-ink truncate">{data.auth.session()?.user?.name}</p>
              <p class="text-xs text-ink-muted truncate">{data.auth.session()?.user?.email}</p>
            </div>
          </div>
        </Show>
        <button
          onClick={() => void data.auth.signOut()}
          class="w-full flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium text-ink-muted hover:text-ink hover:bg-canvas-subtle transition-all group"
        >
          <span class="group-hover:translate-x-0.5 transition-transform"><LogOutIcon /></span>
          {data.i18n.t("auth.signOut")}
        </button>
      </div>
    </aside>
  );

  const MobileMenu = () => (
    <Show when={isMobileMenuOpen()}>
      <div class="lg:hidden fixed inset-0 z-50">
        <div class="absolute inset-0 bg-ink/40 backdrop-blur-sm transition-opacity" onClick={() => setIsMobileMenuOpen(false)} />
        <div class="absolute left-0 top-0 h-full w-72 bg-canvas shadow-2xl">
          <div class="p-4 border-b border-border flex items-center justify-between">
            <DashboardLogo />
            <button onClick={() => setIsMobileMenuOpen(false)} class="p-2 hover:bg-canvas-subtle rounded-xl transition-colors" aria-label={data.i18n.t("dashboard.close")}>
              <XIcon />
            </button>
          </div>
          <nav class="p-4 space-y-1">
            {navItems.map((item) => (
              <A
                href={item.path}
                onClick={() => setIsMobileMenuOpen(false)}
                class={`
                  w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-medium transition-all
                  ${activeSection() === item.id ? "bg-accent text-canvas" : "text-ink-muted hover:bg-canvas-subtle"}
                `}
              >
                <item.icon /> {data.i18n.t(item.label)}
              </A>
            ))}
          </nav>
          <div class="p-4 border-t border-border">
            <div class="flex items-center gap-2 mb-2">
              <LanguageToggle />
              <ThemeToggle />
            </div>
            <button onClick={() => void data.auth.signOut()} class="w-full flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium text-ink-muted hover:text-ink hover:bg-canvas-subtle transition-all">
              <LogOutIcon /> {data.i18n.t("auth.signOut")}
            </button>
          </div>
        </div>
      </div>
    </Show>
  );

  const BookingDetailModal = () => (
    <Show when={data.showBookingDetail() && data.selectedBooking()}>
      <div class="fixed inset-0 z-50 flex items-center justify-center p-4">
        <div class="absolute inset-0 bg-ink/50 backdrop-blur-sm" onClick={() => data.setShowBookingDetail(false)} />
        <div class="relative bg-canvas rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto animate-scale-in">
          <div class="p-6 border-b border-border flex items-center justify-between">
            <h3 class="text-xl font-bold text-ink">{data.i18n.t("dashboard.bookingDetails")}</h3>
            <button onClick={() => data.setShowBookingDetail(false)} class="p-2 hover:bg-canvas-subtle rounded-lg transition-colors" aria-label={data.i18n.t("dashboard.close")}>
              <XIcon />
            </button>
          </div>
          <div class="p-6 space-y-5">
            <div class="flex items-center gap-4 p-4 bg-canvas-subtle rounded-xl">
              <div class="w-14 h-14 rounded-full bg-accent-subtle flex items-center justify-center text-lg font-bold text-accent">
                {getInitials(data.selectedBooking()?.customerName)}
              </div>
              <div class="min-w-0">
                <p class="font-semibold text-ink text-lg">{data.selectedBooking()?.customerName}</p>
                <p class="text-ink-muted">{data.selectedBooking()?.customerEmail}</p>
              </div>
            </div>
            <div class="grid grid-cols-2 gap-4">
              <div class="p-4 bg-canvas-subtle rounded-xl">
                <p class="text-xs text-ink-muted uppercase tracking-wider mb-1">{data.i18n.t("dashboard.bookingModal.service")}</p>
                <p class="font-medium text-ink">{data.selectedBooking()?.service}</p>
              </div>
              <div class="p-4 bg-canvas-subtle rounded-xl">
                <p class="text-xs text-ink-muted uppercase tracking-wider mb-1">{data.i18n.t("dashboard.bookingModal.location")}</p>
                <p class="font-medium text-ink">{data.selectedBooking()?.location || "\u2014"}</p>
              </div>
              <div class="p-4 bg-canvas-subtle rounded-xl col-span-2">
                <p class="text-xs text-ink-muted uppercase tracking-wider mb-1">{data.i18n.t("dashboard.bookingModal.assignedTo")}</p>
                <Show when={data.selectedBooking()?.staffName} fallback={<p class="text-ink-subtle">{data.i18n.t("dashboard.bookingModal.noAssign")}</p>}>
                  <div class="flex items-center gap-2">
                    <div class="w-7 h-7 rounded-full bg-accent-subtle flex items-center justify-center text-[10px] font-bold text-accent">
                      {data.selectedBooking()?.staffName?.split(" ").map((n: string) => n[0]).join("")}
                    </div>
                    <p class="font-medium text-ink">{data.selectedBooking()?.staffName}</p>
                  </div>
                </Show>
              </div>
            </div>
            <div class="p-4 bg-canvas-subtle rounded-xl">
              <p class="text-xs text-ink-muted uppercase tracking-wider mb-1">{data.i18n.t("dashboard.bookingModal.dateTime")}</p>
              <p class="font-medium text-ink">
                {new Date(data.selectedBooking()?.startsAt).toLocaleString(undefined, { weekday: "long", year: "numeric", month: "long", day: "numeric", hour: "2-digit", minute: "2-digit" })}
              </p>
              <p class="text-sm text-ink-muted">{data.i18n.t("dashboard.bookingModal.duration")}: {getBookingDuration(data.selectedBooking()?.startsAt, data.selectedBooking()?.endsAt)}</p>
            </div>
            <div class="flex items-center justify-between p-4 bg-canvas-subtle rounded-xl">
              <div>
                <p class="text-xs text-ink-muted uppercase tracking-wider mb-1">{data.i18n.t("dashboard.bookingModal.reference")}</p>
                <p class="font-medium text-ink font-mono text-sm">{data.selectedBooking()?.reference}</p>
              </div>
              <span class={`inline-flex items-center px-3 py-1 rounded-full text-xs font-medium ${
                data.selectedBooking()?.status === "confirmed" ? "bg-accent/10 text-accent"
                : data.selectedBooking()?.status === "pending" ? "bg-canvas-muted text-ink-muted"
                : "bg-canvas-subtle text-ink-subtle"
              }`}>
                {data.i18n.t(`dashboard.${data.selectedBooking()?.status}`)}
              </span>
            </div>
            <Show when={data.selectedBooking()?.notes}>
              <div class="p-4 bg-canvas-subtle rounded-xl">
                <p class="text-xs text-ink-muted uppercase tracking-wider mb-1">{data.i18n.t("dashboard.bookingModal.notes")}</p>
                <p class="text-ink text-sm">{data.selectedBooking()?.notes}</p>
              </div>
            </Show>
          </div>
        </div>
      </div>
    </Show>
  );

  return (
    <div class="min-h-screen flex bg-canvas font-dashboard">
      <Sidebar />
      <div class="flex-1 flex flex-col min-h-screen">
        {/* Mobile Header */}
        <div class="lg:hidden bg-canvas/80 backdrop-blur-xl border-b border-border p-4 flex items-center justify-between sticky top-0 z-40">
          <DashboardLogo />
          <div class="flex items-center gap-2">
            <NotificationDropdown bookings={data.normalizedAllBookings()} billing={data.resolvedBilling()} />
            <button onClick={() => setIsMobileMenuOpen(true)} aria-label={data.i18n.locale() === "cs" ? "Otevrit menu" : "Open menu"} class="p-2 hover:bg-canvas-subtle rounded-xl transition-all">
              <MenuIcon />
            </button>
          </div>
        </div>
        <MobileMenu />

        <main class="flex-1 p-4 lg:p-8 overflow-y-auto">
          <DemoBanner />

          {/* Demo Notice Toast */}
          <Show when={data.demoNotice()}>
            <div class="mb-6 p-4 rounded-xl bg-accent-subtle border border-accent/20 flex items-center justify-between animate-fade-in">
              <div class="flex items-center gap-3">
                <SparklesIcon />
                <p class="text-sm font-medium text-accent">{data.demoNotice()}</p>
              </div>
              <button onClick={() => data.setDemoNotice(null)} class="p-1.5 hover:bg-accent/10 rounded-lg text-accent"><XIcon /></button>
            </div>
          </Show>

          {/* Not logged in */}
          <Show when={!data.token() && data.auth.session() !== undefined}>
            <div class="max-w-lg mx-auto py-12 lg:py-20 px-4 text-center">
              <div class="relative inline-block mb-6">
                <div class="absolute inset-0 bg-accent/20 rounded-full blur-3xl opacity-60" />
                <BookraCharacter pose="hello" size="xl" animate={true} />
              </div>
              <h2 class="text-3xl lg:text-4xl font-bold text-ink tracking-tight font-display">{data.i18n.locale() === "cs" ? "Vas rezervacni system ceka" : "Your booking system awaits"}</h2>
              <p class="text-ink-muted mt-3 text-lg max-w-md mx-auto">{data.i18n.t("dashboard.welcome.body")}</p>
              <div class="mt-10 flex flex-col sm:flex-row items-center justify-center gap-4">
                <button onClick={() => window.dispatchEvent(new CustomEvent("openAuthDialog", { detail: { mode: "sign-in" } }))} class="btn-primary w-full sm:w-auto">
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><polyline points="10 17 15 12 10 7"/><line x1="15" x2="3" y1="12" y2="12"/></svg>
                  {data.i18n.t("auth.signIn")}
                </button>
                <button onClick={async () => { await data.auth.signInAsDemo(); window.location.reload(); }} class="btn-secondary w-full sm:w-auto">
                  <SparklesIcon /> {data.i18n.t("dashboard.tryDemo")}
                </button>
              </div>
              <p class="mt-6 text-sm text-ink-muted">{data.i18n.locale() === "cs" ? "Jeste nemate ucet? " : "No account yet? "}
                <button onClick={() => window.dispatchEvent(new CustomEvent("openAuthDialog", { detail: { mode: "register" } }))} class="text-accent hover:text-accent-hover font-medium underline underline-offset-2">{data.i18n.t("auth.createAccount")}</button>
              </p>
            </div>
          </Show>

          {/* Loading */}
          <Show when={data.token() && !data.isDashboardReady()}>
            <div class="flex flex-col items-center justify-center py-20">
              <BookraCharacter pose="walk" size="lg" animate={true} />
              <p class="mt-6 text-sm text-ink-muted animate-pulse font-medium">{data.i18n.locale() === "cs" ? "Nacitani dashboardu..." : "Loading your dashboard..."}</p>
            </div>
          </Show>

          {/* Dashboard Content */}
          <Show when={data.isDashboardReady()}>
            <div class="max-w-7xl mx-auto">
              {props.children}
            </div>
          </Show>
        </main>
      </div>

      <IntegrationModal
        isOpen={data.showIntegrationModal()}
        onClose={() => data.setShowIntegrationModal(false)}
        tenantSlug={data.resolvedSummary()?.tenantSlug || "demo-studio"}
        publicBookingUrl={data.resolvedSummary()?.publicBookingUrl || "https://bookra.eu/book/demo-studio"}
        tenantName={data.resolvedSummary()?.tenantName || "Demo Studio"}
        primaryColor={data.resolvedBootstrap()?.brand?.primaryColor}
      />

      <BookingDetailModal />
    </div>
  );
}

export const DashboardLayout: ParentComponent = (props) => {
  const value = DashboardDataProvider({ children: undefined } as any);
  return (
    <DashboardContext.Provider value={value}>
      <DashboardShell>{props.children}</DashboardShell>
    </DashboardContext.Provider>
  );
};
