"use client";

import { useState, useEffect } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import Sidebar from "./Sidebar";
import Topbar from "./Topbar";
import MobileAppShell from "./MobileAppShell";
import { Smartphone, Monitor, ShieldCheck, User, Sparkles, LogOut, Info } from "lucide-react";
import { createClient } from "@/lib/supabase/client";

type Profile = {
  full_name: string;
  email: string;
  role: "admin" | "volunteer";
  avatar_url: string | null;
};

type Props = {
  profile: Profile;
  children: React.ReactNode;
};

function useIsMobileViewport() {
  const [isMobile, setIsMobile] = useState(false);
  useEffect(() => {
    const check = () => setIsMobile(window.innerWidth < 768);
    check();
    window.addEventListener("resize", check);
    return () => window.removeEventListener("resize", check);
  }, []);
  return isMobile;
}

export default function DashboardLayoutClient({ profile, children }: Props) {
  const pathname = usePathname();
  const router = useRouter();
  const searchParams = useSearchParams();
  const isViewportMobile = useIsMobileViewport();
  const supabase = createClient();

  const isPreviewMobile = searchParams.get("preview") === "mobile";
  const isMobile = isViewportMobile || isPreviewMobile;

  // Sync simulator preview state
  function togglePreview() {
    const params = new URLSearchParams(window.location.search);
    if (isPreviewMobile) {
      params.delete("preview");
    } else {
      params.set("preview", "mobile");
    }
    router.push(`${pathname}?${params.toString()}`);
  }

  async function handleSignOut() {
    await supabase.auth.signOut();
    router.push("/login");
    router.refresh();
  }

  // If actually on a mobile device, render the mobile shell directly.
  if (isViewportMobile) {
    return (
      <MobileAppShell
        role={profile.role}
        profileName={profile.full_name}
        profileEmail={profile.email}
      >
        {children}
      </MobileAppShell>
    );
  }

  // If in desktop simulator preview mode:
  if (isPreviewMobile) {
    return (
      <div className="flex h-screen w-screen bg-[#11161B] text-zinc-100 overflow-hidden font-sans">
        {/* Left Control Panel */}
        <div className="hidden md:flex w-80 shrink-0 flex-col border-r border-zinc-800 bg-[#151C24] p-6 justify-between">
          <div className="space-y-6">
            <div className="flex items-center gap-2">
              <div className="flex h-9 w-9 items-center justify-center rounded-card bg-emerald text-sm font-extrabold text-white">
                PI
              </div>
              <div>
                <h2 className="text-sm font-bold text-white uppercase tracking-wider">Pusat Islam</h2>
                <p className="text-[10px] text-emerald font-semibold uppercase tracking-wider">App Simulator</p>
              </div>
            </div>

            <div className="rounded-card bg-zinc-800/40 p-4 border border-zinc-700/30 text-xs space-y-2 text-zinc-300">
              <p className="flex items-center gap-1.5 font-bold text-white mb-2">
                <Info size={14} className="text-emerald" /> Simulator Guide
              </p>
              <p>You are viewing the **Mobile App Interface**.</p>
              <p>
                Logged in as: <span className="font-semibold text-emerald">{profile.full_name}</span>
              </p>
              <p>
                Account Role: <span className="font-semibold capitalize text-emerald">{profile.role}</span>
              </p>
              <p className="text-[10px] text-zinc-400 italic">
                Scroll within the phone screen or click navigation tabs to inspect.
              </p>
            </div>

            <div className="space-y-2">
              <button
                onClick={togglePreview}
                className="flex w-full items-center justify-center gap-2 rounded-card bg-emerald px-4 py-2.5 text-xs font-bold text-white hover:bg-emerald-dark transition-colors"
              >
                <Monitor size={14} /> Switch to Web View
              </button>
            </div>
          </div>

          <div className="space-y-4">
            <div className="flex items-center gap-2.5 rounded-card bg-zinc-900/60 p-3 text-xs border border-zinc-800">
              <div className="flex h-8 w-8 items-center justify-center rounded-full bg-emerald font-bold text-white text-[10px]">
                {profile.full_name.split(" ").map(n => n[0]).slice(0,2).join("").toUpperCase()}
              </div>
              <div className="truncate flex-1">
                <p className="font-semibold text-white truncate">{profile.full_name}</p>
                <p className="text-[10px] text-zinc-400 truncate">{profile.email}</p>
              </div>
            </div>
            <button
              onClick={handleSignOut}
              className="flex w-full items-center justify-center gap-2 rounded-card border border-zinc-800 bg-transparent px-4 py-2 text-xs font-bold text-zinc-400 hover:text-error hover:border-error/20 hover:bg-error/5 transition-all"
            >
              <LogOut size={14} /> Log Out
            </button>
          </div>
        </div>

        {/* Smartphone Simulator Viewport */}
        <div className="flex-1 flex items-center justify-center p-6 relative bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-zinc-900 via-[#11161B] to-black">
          {/* Back button link floating */}
          <button
            onClick={togglePreview}
            className="absolute top-6 right-6 flex items-center gap-1.5 rounded-full bg-zinc-800/80 px-4 py-2 text-xs font-bold text-white hover:bg-zinc-700 backdrop-blur-sm transition-all"
          >
            <Monitor size={14} /> Back to Web Portal
          </button>

          {/* Smartphone device frame container */}
          <div className="relative mx-auto h-[780px] w-[370px] rounded-[50px] border-[12px] border-zinc-800 bg-black shadow-[0_25px_60px_-15px_rgba(0,0,0,0.9)] ring-1 ring-zinc-700/50 flex flex-col overflow-hidden">
            {/* Notch / Speaker bar */}
            <div className="absolute top-0 left-1/2 z-40 h-[22px] w-[140px] -translate-x-1/2 rounded-b-[18px] bg-zinc-800 flex items-center justify-center">
              <div className="h-1 w-12 rounded-full bg-zinc-900 mb-0.5" />
            </div>

            {/* Status bar */}
            <div className="absolute top-[2px] left-0 right-0 z-30 flex justify-between px-6 text-[10px] font-semibold text-black/70 mix-blend-difference">
              <span>9:41</span>
              <div className="flex items-center gap-1">
                <span>5G</span>
                <div className="h-2.5 w-4 rounded-sm border border-current p-0.5 flex items-center">
                  <div className="h-full w-full bg-current rounded-2xs" />
                </div>
              </div>
            </div>

            {/* Inner frame contents */}
            <div className="h-full w-full rounded-[38px] overflow-hidden bg-sand pt-4">
              <MobileAppShell
                role={profile.role}
                profileName={profile.full_name}
                profileEmail={profile.email}
              >
                {children}
              </MobileAppShell>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Regular Web Portal Layout
  return (
    <div className="flex min-h-screen bg-sand font-sans">
      <Sidebar role={profile.role} />
      <div className="flex min-w-0 flex-1 flex-col">
        {/* Custom top bar featuring the Islamic background and overlay */}
        <header
          className="relative z-30 flex items-center justify-between gap-4 border-b border-sand-dark/60 px-6 py-4 bg-cover bg-center bg-no-repeat"
          style={{ backgroundImage: "url('/islamic_banner.png')" }}
        >
          {/* Overlay for perfect readability */}
          <div className="absolute inset-0 bg-gradient-to-r from-[#05291F]/90 via-[#0B5945]/85 to-[#0F6E56]/75 z-0" />

          <div className="relative flex items-center gap-2 z-10">
            <span className="text-xs font-bold uppercase bg-white/10 border border-white/20 px-2.5 py-1 rounded-full flex items-center gap-1 text-white shadow-sm">
              <Sparkles size={11} />
              {profile.role === "admin" ? "Admin Web Portal" : "Student Web Portal"}
            </span>
          </div>

          <div className="relative flex items-center gap-4 z-30">
            <Topbar
            name={profile.full_name}
            email={profile.email}
            role={profile.role}
            avatarUrl={profile.avatar_url}
          />
          </div>
        </header>

        <main className="flex-1 overflow-y-auto p-6">{children}</main>
      </div>
    </div>
  );
}
