/* eslint-disable react-hooks/exhaustive-deps */
import styles from './admin-layout.module.scss'
import AdminSidebar from '@/components/admin/Admin-Sidebar'
import AdminNavbar from '@/components/admin/AdminNavbar'
import RightSideBar from '@/components/dashboard/RightSideBar'
import { Head, usePage, router } from '@inertiajs/react'
import { useState, useEffect } from 'react'

// --- Flash types
interface FlashProps {
  success?: string | null
  error?: string | null
  warning?: string | null
  info?: string | null
}

interface FlashMessageState {
  type: 'success' | 'error' | 'warning' | 'info'
  message: string
}

// --- Props for the layout
interface AdminDashboardLayoutProps {
  children: React.ReactNode
  title: string
}

const AdminDashboardLayout: React.FC<AdminDashboardLayoutProps> = ({ children, title }) => {
  const { props } = usePage<{ flash?: FlashProps }>()
  const flash = props.flash || {}

  const [flashMessage, setFlashMessage] = useState<FlashMessageState | null>(null)

  // Initialize flashMessage once when props.flash changes
  useEffect(() => {
    const types: (keyof FlashProps)[] = ['success', 'error', 'warning', 'info']
    for (const type of types) {
      const message = flash[type]
      if (message) {
        setFlashMessage({ type, message })
        break
      }
    }
  }, [flash])

  useEffect(() => {
    const handleNavigation = () => {
      // disable inertia restoring scroll
      window.history.scrollRestoration = "manual";

      // wait for render
      requestAnimationFrame(() => {
        const layout = document.querySelector(
          `.${styles.layout}`
        ) as HTMLElement;

        if (layout) {
          layout.scrollTo({
            top: 0,
            behavior: "smooth", // 🔥 smooth animation
          });
        }

        // fallback
        window.scrollTo({
          top: 0,
          behavior: "smooth",
        });
      });
    };

    const removeListener = router.on("navigate", handleNavigation);

    return () => removeListener();
  }, []);

  // Auto-clear flashMessage after 4 seconds
  useEffect(() => {
    if (!flashMessage) return
    const timer = setTimeout(() => setFlashMessage(null), 4000)
    return () => clearTimeout(timer)
  }, [flashMessage])

  return (
    <>
      <Head title={title} />

      {/* Flash message */}
       {flashMessage && (
      <div
        className={`${styles.flash} ${
          flashMessage.type === "success"
            ? styles.flashSuccess
            : flashMessage.type === "error"
            ? styles.flashError
            : flashMessage.type === "warning"
            ? styles.flashWarning
            : styles.flashInfo
        }`}
      >
        <div className={styles.flashIndicator}>
          <span className={styles.flashDot} />
        </div>

        <div className={styles.flashContent}>
          <h5>
            {flashMessage.type === "success" &&
              "Success"}

            {flashMessage.type === "error" &&
              "Error"}

            {flashMessage.type === "warning" &&
              "Warning"}

            {flashMessage.type === "info" &&
              "Information"}
          </h5>

          <p>{flashMessage.message}</p>
        </div>
      </div>
    )}
      <div className={styles['admin__layout']}>
        <div className={styles['admin__layout__sidebar']}>
          <AdminSidebar />
        </div>

        <div className={styles['admin__layout__content']}>
          <div className={styles['admin__layout__content__navbar']}>
            <AdminNavbar />
          </div>

          <div className={styles['admin__layout__content--children']}>
            {children}
            <div className={styles['admin__layout__content--children--rightbar']}>
              <RightSideBar />
            </div>
          </div>
        </div>
      </div>
    </>
  )
}

export default AdminDashboardLayout
