import * as icon from '@mdi/js';
import Head from 'next/head';
import React from 'react';
import axios from 'axios';
import type { ReactElement, ReactNode } from 'react';
import Link from 'next/link';

import LayoutAuthenticated from '../layouts/Authenticated';
import SectionMain from '../components/SectionMain';
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
import BaseIcon from '../components/BaseIcon';
import { getPageTitle } from '../config';
import { hasPermission } from '../helpers/userPermissions';
import { fetchWidgets } from '../stores/roles/rolesSlice';
import { WidgetCreator } from '../components/WidgetCreator/WidgetCreator';
import { SmartWidget } from '../components/SmartWidget/SmartWidget';
import { useAppDispatch, useAppSelector } from '../stores/hooks';

type CountValue = number | string | null;

const entityCards = [
  {
    key: 'users',
    permission: 'READ_USERS',
    label: 'Pengguna',
    description: 'Akun admin dan anggota',
    href: '/users/users-list',
    iconPath: icon.mdiAccountGroup,
    accentClass: 'text-blue-500 bg-blue-50 dark:bg-blue-900/20',
  },
  {
    key: 'roles',
    permission: 'READ_ROLES',
    label: 'Roles',
    description: 'Hak akses aplikasi',
    href: '/roles/roles-list',
    iconPath: icon.mdiShieldAccountVariantOutline,
    accentClass: 'text-indigo-500 bg-indigo-50 dark:bg-indigo-900/20',
  },
  {
    key: 'permissions',
    permission: 'READ_PERMISSIONS',
    label: 'Permissions',
    description: 'Kontrol izin detail',
    href: '/permissions/permissions-list',
    iconPath: icon.mdiShieldAccountOutline,
    accentClass: 'text-slate-500 bg-slate-100 dark:bg-slate-800',
  },
  {
    key: 'place_categories',
    permission: 'READ_PLACE_CATEGORIES',
    label: 'Kategori Tempat',
    description: 'Kelompok data lokasi',
    href: '/place_categories/place_categories-list',
    iconPath: icon.mdiShape,
    accentClass: 'text-violet-500 bg-violet-50 dark:bg-violet-900/20',
  },
  {
    key: 'places',
    permission: 'READ_PLACES',
    label: 'Tempat',
    description: 'Direktori lokasi GeoSeek',
    href: '/places/places-list',
    iconPath: icon.mdiMapMarker,
    accentClass: 'text-emerald-500 bg-emerald-50 dark:bg-emerald-900/20',
  },
  {
    key: 'place_opening_hours',
    permission: 'READ_PLACE_OPENING_HOURS',
    label: 'Jam Buka',
    description: 'Jadwal operasional tempat',
    href: '/place_opening_hours/place_opening_hours-list',
    iconPath: icon.mdiClockOutline,
    accentClass: 'text-cyan-500 bg-cyan-50 dark:bg-cyan-900/20',
  },
  {
    key: 'place_features',
    permission: 'READ_PLACE_FEATURES',
    label: 'Fitur Tempat',
    description: 'Fasilitas dan atribut',
    href: '/place_features/place_features-list',
    iconPath: icon.mdiTagMultiple,
    accentClass: 'text-teal-500 bg-teal-50 dark:bg-teal-900/20',
  },
  {
    key: 'place_feature_links',
    permission: 'READ_PLACE_FEATURE_LINKS',
    label: 'Relasi Fitur',
    description: 'Koneksi tempat dan fitur',
    href: '/place_feature_links/place_feature_links-list',
    iconPath: icon.mdiLinkVariant,
    accentClass: 'text-sky-500 bg-sky-50 dark:bg-sky-900/20',
  },
  {
    key: 'reviews',
    permission: 'READ_REVIEWS',
    label: 'Ulasan',
    description: 'Komentar dan rating warga',
    href: '/reviews/reviews-list',
    iconPath: icon.mdiStarOutline,
    accentClass: 'text-amber-500 bg-amber-50 dark:bg-amber-900/20',
  },
  {
    key: 'favorites',
    permission: 'READ_FAVORITES',
    label: 'Favorit',
    description: 'Tempat tersimpan anggota',
    href: '/favorites/favorites-list',
    iconPath: icon.mdiHeartOutline,
    accentClass: 'text-rose-500 bg-rose-50 dark:bg-rose-900/20',
  },
  {
    key: 'search_logs',
    permission: 'READ_SEARCH_LOGS',
    label: 'Riwayat Cari',
    description: 'Aktivitas pencarian',
    href: '/search_logs/search_logs-list',
    iconPath: icon.mdiMagnify,
    accentClass: 'text-blue-500 bg-blue-50 dark:bg-blue-900/20',
  },
  {
    key: 'reports',
    permission: 'READ_REPORTS',
    label: 'Laporan',
    description: 'Masukan dan aduan warga',
    href: '/reports/reports-list',
    iconPath: icon.mdiAlertCircleOutline,
    accentClass: 'text-red-500 bg-red-50 dark:bg-red-900/20',
  },
] as const;

type EntityKey = (typeof entityCards)[number]['key'];

const initialCounts = entityCards.reduce(
  (accumulator, item) => ({ ...accumulator, [item.key]: 'Loading...' }),
  {} as Record<EntityKey, CountValue>,
);

const adminShortcuts = [
  {
    label: 'Tambah Tempat',
    description: 'Buat data lokasi baru untuk GeoSeek.',
    href: '/places/places-new',
    iconPath: icon.mdiPlusCircleOutline,
  },
  {
    label: 'Kelola Review',
    description: 'Moderasi ulasan dan rating anggota.',
    href: '/reviews/reviews-list',
    iconPath: icon.mdiCommentTextOutline,
  },
  {
    label: 'Pantau Laporan',
    description: 'Tindak lanjuti laporan dari anggota.',
    href: '/reports/reports-list',
    iconPath: icon.mdiClipboardAlertOutline,
  },
  {
    label: 'Manajemen User',
    description: 'Atur akun admin dan anggota.',
    href: '/users/users-list',
    iconPath: icon.mdiAccountGroup,
  },
  {
    label: 'Atur Role',
    description: 'Kelola akses Admin dan Anggota.',
    href: '/roles/roles-list',
    iconPath: icon.mdiShieldAccountVariantOutline,
  },
  {
    label: 'Swagger API',
    description: 'Buka dokumentasi endpoint backend.',
    href: '/api-docs',
    iconPath: icon.mdiFileCode,
  },
];

const memberActions = [
  {
    label: 'Cari Tempat',
    description: 'Temukan tempat, layanan, UMKM, dan promo sekitar.',
    href: '/geoseek/search',
    iconPath: icon.mdiMagnify,
    colorClass: 'text-blue-600 bg-blue-50 border-blue-100 dark:bg-blue-900/20 dark:border-blue-800',
  },
  {
    label: 'Lihat Peta',
    description: 'Jelajahi lokasi dari tampilan peta GeoSeek.',
    href: '/geoseek/map',
    iconPath: icon.mdiMapMarkerRadiusOutline,
    colorClass: 'text-emerald-600 bg-emerald-50 border-emerald-100 dark:bg-emerald-900/20 dark:border-emerald-800',
  },
  {
    label: 'Favorit Saya',
    description: 'Buka tempat yang sudah kamu simpan.',
    href: '/favorites/favorites-list',
    iconPath: icon.mdiHeartOutline,
    colorClass: 'text-rose-600 bg-rose-50 border-rose-100 dark:bg-rose-900/20 dark:border-rose-800',
  },
  {
    label: 'Buat Review',
    description: 'Bagikan pengalaman untuk membantu warga lain.',
    href: '/reviews/reviews-new',
    iconPath: icon.mdiStarOutline,
    colorClass: 'text-amber-600 bg-amber-50 border-amber-100 dark:bg-amber-900/20 dark:border-amber-800',
  },
  {
    label: 'Kirim Laporan',
    description: 'Laporkan info tempat yang kurang tepat.',
    href: '/reports/reports-new',
    iconPath: icon.mdiAlertCircleOutline,
    colorClass: 'text-red-600 bg-red-50 border-red-100 dark:bg-red-900/20 dark:border-red-800',
  },
  {
    label: 'Promo Terdekat',
    description: 'Cek kabar promo dan penawaran menarik.',
    href: '/geoseek/promos',
    iconPath: icon.mdiTicketPercentOutline,
    colorClass: 'text-orange-600 bg-orange-50 border-orange-100 dark:bg-orange-900/20 dark:border-orange-800',
  },
];

const feedItems = [
  {
    username: 'Admin GeoSeek',
    initials: 'AG',
    timestamp: 'Baru saja',
    badge: 'Laporan',
    badgeClass: 'bg-red-500',
    avatarClass: 'from-red-400 to-rose-500',
    text: 'Ada laporan baru tentang jam buka tempat yang perlu diverifikasi oleh tim.',
    mediaTitle: 'Update data lokasi',
    mediaDescription: 'Prioritas tinggi untuk menjaga akurasi informasi warga.',
    mediaClass: 'from-red-50 via-rose-50 to-orange-50 text-red-600 dark:from-red-950/40 dark:via-rose-950/30 dark:to-orange-950/30',
  },
  {
    username: 'Warga Lokal',
    initials: 'WL',
    timestamp: '12 menit lalu',
    badge: 'Warga',
    badgeClass: 'bg-emerald-500',
    avatarClass: 'from-emerald-400 to-teal-500',
    text: 'Rekomendasi kuliner baru sudah ditambahkan. Jangan lupa simpan tempat favoritmu.',
    mediaTitle: 'Rekomendasi komunitas',
    mediaDescription: 'Bantu warga lain menemukan tempat terbaik di sekitar.',
    mediaClass: 'from-emerald-50 via-teal-50 to-cyan-50 text-emerald-600 dark:from-emerald-950/40 dark:via-teal-950/30 dark:to-cyan-950/30',
  },
  {
    username: 'Mitra Promo',
    initials: 'MP',
    timestamp: '1 jam lalu',
    badge: 'Promo',
    badgeClass: 'bg-amber-500',
    avatarClass: 'from-amber-400 to-orange-500',
    text: 'Promo akhir pekan tersedia untuk beberapa kategori UMKM dan kuliner.',
    mediaTitle: 'Promo pilihan',
    mediaDescription: 'Cek halaman promo untuk melihat penawaran terbaru.',
    mediaClass: 'from-amber-50 via-orange-50 to-yellow-50 text-amber-700 dark:from-amber-950/40 dark:via-orange-950/30 dark:to-yellow-950/30',
  },
];

type StatCardProps = {
  label: string;
  description: string;
  value: CountValue;
  href: string;
  iconPath: string;
  accentClass: string;
  cardClass: string;
};

const StatCard = ({ label, description, value, href, iconPath, accentClass, cardClass }: StatCardProps) => (
  <Link href={href}>
    <div className={`${cardClass} p-5 transition hover:-translate-y-0.5 hover:shadow-md`}>
      <div className="flex items-start justify-between gap-4">
        <div>
          <div className="text-sm font-medium text-gray-500 dark:text-gray-400">{label}</div>
          <div className="mt-2 text-3xl font-semibold leading-tight text-slate-800 dark:text-slate-100">{value}</div>
          <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">{description}</p>
        </div>
        <div className={`rounded-2xl p-3 ${accentClass}`}>
          <BaseIcon path={iconPath} w="w-8" h="h-8" size={30} />
        </div>
      </div>
    </div>
  </Link>
);

type ShortcutCardProps = {
  label: string;
  description: string;
  href: string;
  iconPath: string;
  cardClass: string;
};

const ShortcutCard = ({ label, description, href, iconPath, cardClass }: ShortcutCardProps) => (
  <Link href={href}>
    <div className={`${cardClass} group p-5 transition hover:-translate-y-0.5 hover:shadow-md`}>
      <div className="mb-4 inline-flex h-11 w-11 items-center justify-center rounded-2xl bg-blue-50 text-blue-600 group-hover:bg-blue-600 group-hover:text-white dark:bg-blue-900/20">
        <BaseIcon path={iconPath} w="w-6" h="h-6" size={24} />
      </div>
      <h3 className="text-base font-semibold text-slate-800 dark:text-slate-100">{label}</h3>
      <p className="mt-1 text-sm text-slate-500 dark:text-slate-400">{description}</p>
    </div>
  </Link>
);

type MemberActionCardProps = {
  label: string;
  description: string;
  href: string;
  iconPath: string;
  colorClass: string;
};

const MemberActionCard = ({ label, description, href, iconPath, colorClass }: MemberActionCardProps) => (
  <Link href={href}>
    <div className={`rounded-xl border p-4 transition hover:-translate-y-0.5 hover:shadow-sm ${colorClass}`}>
      <BaseIcon path={iconPath} w="w-9" h="h-9" size={32} />
      <h3 className="mt-3 text-sm font-semibold text-slate-800 dark:text-slate-100">{label}</h3>
      <p className="mt-1 text-xs leading-5 text-slate-500 dark:text-slate-400">{description}</p>
    </div>
  </Link>
);

type FeedItemProps = {
  username: string;
  initials: string;
  timestamp: string;
  badge: string;
  badgeClass: string;
  avatarClass: string;
  text: string;
  mediaTitle: string;
  mediaDescription: string;
  mediaClass: string;
};

const ActionButton = ({ iconPath, children }: { iconPath: string; children: ReactNode }) => (
  <button
    type="button"
    className="inline-flex items-center gap-1.5 border-0 bg-transparent p-0 text-sm text-slate-500 transition hover:text-blue-500 dark:text-slate-400"
  >
    <BaseIcon path={iconPath} w="w-4" h="h-4" size={16} />
    {children}
  </button>
);

const FeedItemCard = ({
  username,
  initials,
  timestamp,
  badge,
  badgeClass,
  avatarClass,
  text,
  mediaTitle,
  mediaDescription,
  mediaClass,
}: FeedItemProps) => (
  <article className="mb-3 rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-dark-700 dark:bg-dark-900">
    <header className="mb-3 flex items-center gap-3">
      <div className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-gradient-to-br text-sm font-bold text-white ${avatarClass}`}>
        {initials}
      </div>
      <div className="flex flex-col gap-0.5">
        <div className="text-[0.95rem] font-semibold text-slate-800 dark:text-slate-100">{username}</div>
        <div className="text-xs text-slate-500 dark:text-slate-400">{timestamp}</div>
        <span className={`my-0.5 w-max rounded-full px-2 py-0.5 text-[0.7rem] font-medium text-white ${badgeClass}`}>{badge}</span>
      </div>
    </header>

    <div>
      <p className="mb-3 text-[0.95rem] leading-6 text-slate-700 dark:text-slate-200">{text}</p>
      <div className={`mb-3 max-h-[300px] overflow-hidden rounded-lg border border-slate-200 bg-gradient-to-br p-4 dark:border-dark-700 ${mediaClass}`}>
        <div className="flex min-h-[120px] items-center justify-center rounded-md border border-white/70 bg-white/50 p-4 text-center dark:border-white/10 dark:bg-white/5">
          <div>
            <BaseIcon path={icon.mdiImageOutline} w="mx-auto mb-2 w-10" h="h-10" size={38} />
            <div className="text-sm font-semibold">{mediaTitle}</div>
            <div className="mt-1 text-xs opacity-80">{mediaDescription}</div>
          </div>
        </div>
      </div>
    </div>

    <footer className="flex gap-[15px] border-t border-slate-100 pt-2.5 dark:border-dark-700">
      <ActionButton iconPath={icon.mdiThumbUpOutline}>Suka</ActionButton>
      <ActionButton iconPath={icon.mdiMessageReplyTextOutline}>Komentar</ActionButton>
      <ActionButton iconPath={icon.mdiShareVariantOutline}>Bagikan</ActionButton>
    </footer>
  </article>
);

const formatRoleLabel = (roleName?: string) => {
  if (!roleName || roleName === 'Registered User') {
    return 'Anggota';
  }

  return roleName;
};

const Dashboard = () => {
  const dispatch = useAppDispatch();
  const corners = useAppSelector((state) => state.style.corners);
  const cardsStyle = useAppSelector((state) => state.style.cardsStyle);
  const { currentUser } = useAppSelector((state) => state.auth);
  const { isFetchingQuery } = useAppSelector((state) => state.openAi);
  const { rolesWidgets, loading } = useAppSelector((state) => state.roles);

  const [counts, setCounts] = React.useState<Record<EntityKey, CountValue>>(initialCounts);
  const [widgetsRole, setWidgetsRole] = React.useState({
    role: { value: '', label: '' },
  });

  const cardClass = `${corners !== 'rounded-full' ? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700`;
  const isAdminDashboard = hasPermission(currentUser, 'CREATE_ROLES');
  const displayName = [currentUser?.firstName, currentUser?.lastName].filter(Boolean).join(' ') || currentUser?.email || 'Anggota';
  const roleLabel = formatRoleLabel(currentUser?.app_role?.name);

  async function loadData() {
    if (!currentUser) return;

    const requests = entityCards.map((item) => {
      if (hasPermission(currentUser, item.permission)) {
        return axios.get(`/${item.key}/count`);
      }

      return Promise.resolve({ data: { count: null } });
    });

    const results = await Promise.allSettled(requests);

    setCounts((currentCounts) => {
      const nextCounts = { ...currentCounts };

      results.forEach((result, index) => {
        const entityKey = entityCards[index].key;

        if (result.status === 'fulfilled') {
          nextCounts[entityKey] = result.value.data.count;
        } else {
          console.error(`Failed to load dashboard count for ${entityKey}:`, result.reason);
          nextCounts[entityKey] = result.reason?.message || 'Error';
        }
      });

      return nextCounts;
    });
  }

  async function getWidgets(roleId: string) {
    await dispatch(fetchWidgets(roleId));
  }

  React.useEffect(() => {
    if (!currentUser) return;

    loadData().catch((error) => {
      console.error('Failed to load dashboard data:', error);
    });
    setWidgetsRole({ role: { value: currentUser?.app_role?.id, label: formatRoleLabel(currentUser?.app_role?.name) } });
  }, [currentUser]);

  React.useEffect(() => {
    if (!isAdminDashboard || !currentUser || !widgetsRole?.role?.value) return;

    getWidgets(widgetsRole?.role?.value || '').catch((error) => {
      console.error('Failed to load dashboard widgets:', error);
    });
  }, [isAdminDashboard, widgetsRole?.role?.value]);

  const visibleAdminCards = entityCards.filter((item) => hasPermission(currentUser, item.permission));
  const adminHighlights = entityCards.filter((item) => ['users', 'places', 'reviews', 'reports'].includes(item.key));
  const memberSummary = entityCards.filter((item) => ['favorites', 'reviews', 'reports'].includes(item.key));

  if (!currentUser) {
    return (
      <>
        <Head>
          <title>{getPageTitle('Dashboard')}</title>
        </Head>
        <SectionMain>
          <SectionTitleLineWithButton icon={icon.mdiChartTimelineVariant} title="Dashboard" main>
            {''}
          </SectionTitleLineWithButton>
          <div className={`${cardClass} p-6 text-slate-500 dark:text-slate-400`}>Memuat dashboard...</div>
        </SectionMain>
      </>
    );
  }

  return (
    <>
      <Head>
        <title>{getPageTitle(isAdminDashboard ? 'Dashboard Admin' : 'Dashboard Anggota')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={isAdminDashboard ? icon.mdiViewDashboardOutline : icon.mdiAccountHeartOutline}
          title={isAdminDashboard ? 'Dashboard Admin' : 'Dashboard Anggota'}
          main
        >
          {''}
        </SectionTitleLineWithButton>

        {isAdminDashboard ? (
          <>
            <section className="mb-6 overflow-hidden rounded-3xl bg-gradient-to-br from-slate-900 via-blue-900 to-slate-800 p-6 text-white shadow-sm">
              <div className="flex flex-col gap-6 lg:flex-row lg:items-end lg:justify-between">
                <div>
                  <p className="text-sm uppercase tracking-[0.3em] text-blue-200">GeoSeek Control Center</p>
                  <h2 className="mt-3 text-2xl font-semibold md:text-3xl">Selamat datang, {displayName}</h2>
                  <p className="mt-2 max-w-2xl text-sm leading-6 text-blue-100">
                    Pantau data utama, moderasi laporan warga, dan kelola akses Admin/Anggota dari satu dashboard.
                  </p>
                </div>
                <div className="rounded-2xl border border-white/20 bg-white/10 px-4 py-3 text-sm backdrop-blur">
                  <div className="text-blue-100">Role aktif</div>
                  <div className="mt-1 text-lg font-semibold">{roleLabel}</div>
                </div>
              </div>
            </section>

            <div className="mb-6 grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">
              {adminHighlights.map((item) => (
                <StatCard
                  key={item.key}
                  label={item.label}
                  description={item.description}
                  value={counts[item.key]}
                  href={item.href}
                  iconPath={item.iconPath}
                  accentClass={item.accentClass}
                  cardClass={cardClass}
                />
              ))}
            </div>

            {hasPermission(currentUser, 'CREATE_ROLES') && (
              <WidgetCreator
                currentUser={currentUser}
                isFetchingQuery={isFetchingQuery}
                setWidgetsRole={setWidgetsRole}
                widgetsRole={widgetsRole}
              />
            )}

            {!!rolesWidgets.length && hasPermission(currentUser, 'CREATE_ROLES') && (
              <p className="mb-4 text-gray-500 dark:text-gray-400">{`${widgetsRole?.role?.label || 'Users'} widgets`}</p>
            )}

            <div className="mb-6 grid grid-cols-1 gap-6 lg:grid-cols-4 lg:grid-flow-dense">
              {(isFetchingQuery || loading) && (
                <div className={`${cardClass} flex items-center p-6 text-lg leading-tight text-gray-500`}>
                  <BaseIcon className="mr-5 animate-spin text-blue-500" w="w-16" h="h-16" size={48} path={icon.mdiLoading} /> Loading widgets...
                </div>
              )}

              {rolesWidgets?.map((widget) => (
                <SmartWidget
                  key={widget.id}
                  userId={currentUser?.id}
                  widget={widget}
                  roleId={widgetsRole?.role?.value || ''}
                  admin={hasPermission(currentUser, 'CREATE_ROLES')}
                />
              ))}
            </div>

            {!!rolesWidgets.length && <hr className="my-6" />}

            <section className="mb-6">
              <div className="mb-4 flex items-center gap-2 text-slate-800 dark:text-slate-100">
                <BaseIcon path={icon.mdiTrendingUp} w="w-6" h="h-6" size={24} className="text-blue-500" />
                <h2 className="text-xl font-semibold">Ringkasan Semua Data</h2>
              </div>
              <div id="dashboard" className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3">
                {visibleAdminCards.map((item) => (
                  <StatCard
                    key={item.key}
                    label={item.label}
                    description={item.description}
                    value={counts[item.key]}
                    href={item.href}
                    iconPath={item.iconPath}
                    accentClass={item.accentClass}
                    cardClass={cardClass}
                  />
                ))}
              </div>
            </section>

            <section>
              <div className="mb-4 flex items-center gap-2 text-slate-800 dark:text-slate-100">
                <BaseIcon path={icon.mdiCompassOutline} w="w-6" h="h-6" size={24} className="text-blue-500" />
                <h2 className="text-xl font-semibold">Aksi Cepat Admin</h2>
              </div>
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3">
                {adminShortcuts.map((item) => (
                  <ShortcutCard key={item.href} {...item} cardClass={cardClass} />
                ))}
              </div>
            </section>
          </>
        ) : (
          <div className="bg-slate-50 text-slate-800 dark:bg-transparent dark:text-slate-100">
            <section className="mb-6 overflow-hidden rounded-3xl border border-slate-200 bg-white p-6 shadow-sm dark:border-dark-700 dark:bg-dark-900">
              <div className="flex flex-col gap-5 lg:flex-row lg:items-center lg:justify-between">
                <div>
                  <p className="text-sm font-medium uppercase tracking-[0.28em] text-blue-500">GeoSeek Anggota</p>
                  <h2 className="mt-3 text-2xl font-semibold md:text-3xl">Halo, {displayName}</h2>
                  <p className="mt-2 max-w-2xl text-sm leading-6 text-slate-500 dark:text-slate-400">
                    Temukan tempat terbaik, simpan favorit, tulis review, dan kirim laporan untuk membantu warga lain.
                  </p>
                </div>
                <div className="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3 text-sm dark:border-dark-700 dark:bg-dark-800">
                  <div className="text-slate-500 dark:text-slate-400">Status akun</div>
                  <div className="mt-1 text-lg font-semibold text-emerald-600">{roleLabel}</div>
                </div>
              </div>
            </section>

            <section className="mb-6 grid grid-cols-1 gap-4 sm:grid-cols-3">
              {memberSummary.map((item) => (
                <Link key={item.key} href={item.href}>
                  <div className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm transition hover:-translate-y-0.5 hover:shadow-md dark:border-dark-700 dark:bg-dark-900">
                    <div className="flex items-center justify-between">
                      <div>
                        <div className="text-xs font-medium text-slate-500 dark:text-slate-400">{item.label}</div>
                        <div className="mt-1 text-2xl font-semibold text-slate-800 dark:text-slate-100">{counts[item.key]}</div>
                      </div>
                      <BaseIcon path={item.iconPath} w="w-9" h="h-9" size={32} className="text-blue-500" />
                    </div>
                  </div>
                </Link>
              ))}
            </section>

            <section className="mb-6">
              <div className="mb-5 flex items-center gap-2 text-slate-800 dark:text-slate-100">
                <BaseIcon path={icon.mdiCompassOutline} w="w-6" h="h-6" size={24} className="text-blue-500" />
                <h2 className="text-xl font-semibold">Mulai Jelajah</h2>
              </div>
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3">
                {memberActions.map((item) => (
                  <MemberActionCard key={item.href} {...item} />
                ))}
              </div>
            </section>

            <section className="mx-auto max-w-[680px]">
              <div className="mb-5 flex items-center gap-2 text-slate-800 dark:text-slate-100">
                <BaseIcon path={icon.mdiCommentTextOutline} w="w-6" h="h-6" size={24} className="text-blue-500" />
                <h2 className="text-xl font-semibold">Feed Aktivitas</h2>
              </div>

              {feedItems.map((item) => (
                <FeedItemCard key={`${item.username}-${item.timestamp}`} {...item} />
              ))}
            </section>
          </div>
        )}
      </SectionMain>
    </>
  );
};

Dashboard.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};

export default Dashboard;
