import {
  mdiAccountTie,
  mdiArrowTopRight,
  mdiCalendarCheck,
  mdiCheckDecagram,
  mdiClipboardTextOutline,
  mdiClockOutline,
  mdiFileDocument,
  mdiHomeCity,
  mdiRefresh,
  mdiRoomService,
  mdiViewDashboardOutline,
} from '@mdi/js';
import axios from 'axios';
import Head from 'next/head';
import Link from 'next/link';
import React, { ReactElement, useCallback, useEffect, useState } from 'react';

import BaseButton from '../components/BaseButton';
import BaseIcon from '../components/BaseIcon';
import CardBox from '../components/CardBox';
import SectionMain from '../components/SectionMain';
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
import { getPageTitle } from '../config';
import { hasPermission } from '../helpers/userPermissions';
import LayoutAuthenticated from '../layouts/Authenticated';
import { useAppSelector } from '../stores/hooks';

type AccessMap = {
  accounts: boolean;
  bookings: boolean;
  approvals: boolean;
  reservations: boolean;
  serviceRequests: boolean;
  invoices: boolean;
  inventory: boolean;
};

type BookingRequestItem = {
  id: string;
  request_code: string | null;
  status: string;
  check_in_at: string | null;
  check_out_at: string | null;
  guest_count: number | null;
  preferred_bedrooms: number | null;
  updatedAt: string;
  organizationName: string;
  requestedBy: string | null;
  propertyName: string;
  unitTypeName: string;
};

type ReservationItem = {
  id: string;
  reservation_code: string | null;
  status: string;
  check_in_at: string | null;
  check_out_at: string | null;
  guest_count: number | null;
  updatedAt: string;
  organizationName: string;
  propertyName: string;
  unitNumber: string;
  sourceRequestCode: string | null;
};

type ServiceRequestItem = {
  id: string;
  request_type: string;
  status: string;
  priority: string;
  summary: string | null;
  due_at: string | null;
  updatedAt: string;
  reservationCode: string | null;
  assignedTo: string | null;
};

type InvoiceItem = {
  id: string;
  invoice_number: string | null;
  status: string;
  total_amount: number;
  balance_due: number;
  currency: string;
  due_at: string | null;
  updatedAt: string;
  organizationName: string;
  reservationCode: string | null;
};

type OverviewResponse = {
  generatedAt: string;
  access: AccessMap;
  organizations: {
    total: number;
  };
  bookingRequests: {
    statusCounts: Record<string, number>;
    pendingReview: number;
    approvedReady: number;
    recent: BookingRequestItem[];
  };
  approvals: {
    pending: number;
  };
  reservations: {
    statusCounts: Record<string, number>;
    upcomingArrivals: number;
    upcomingDepartures: number;
    inHouse: number;
    recent: ReservationItem[];
  };
  serviceRequests: {
    statusCounts: Record<string, number>;
    open: number;
    urgent: number;
    recent: ServiceRequestItem[];
  };
  invoices: {
    statusCounts: Record<string, number>;
    openBalance: number;
    recent: InvoiceItem[];
  };
  inventory: {
    activeProperties: number;
    unitStatusCounts: Record<string, number>;
  };
};

type MetricCard = {
  title: string;
  value: string;
  detail: string;
  icon: string;
  visible?: boolean;
};

type HeroStat = {
  title: string;
  value: string;
  detail: string;
  visible?: boolean;
};

const emptyOverview: OverviewResponse = {
  generatedAt: '',
  access: {
    accounts: false,
    bookings: false,
    approvals: false,
    reservations: false,
    serviceRequests: false,
    invoices: false,
    inventory: false,
  },
  organizations: {
    total: 0,
  },
  bookingRequests: {
    statusCounts: {},
    pendingReview: 0,
    approvedReady: 0,
    recent: [],
  },
  approvals: {
    pending: 0,
  },
  reservations: {
    statusCounts: {},
    upcomingArrivals: 0,
    upcomingDepartures: 0,
    inHouse: 0,
    recent: [],
  },
  serviceRequests: {
    statusCounts: {},
    open: 0,
    urgent: 0,
    recent: [],
  },
  invoices: {
    statusCounts: {},
    openBalance: 0,
    recent: [],
  },
  inventory: {
    activeProperties: 0,
    unitStatusCounts: {},
  },
};

const statusTone = {
  draft: 'bg-slate-100 text-slate-700',
  submitted: 'bg-amber-100 text-amber-800',
  in_review: 'bg-blue-100 text-blue-800',
  changes_requested: 'bg-orange-100 text-orange-800',
  approved: 'bg-emerald-100 text-emerald-800',
  converted_to_reservation: 'bg-emerald-100 text-emerald-800',
  quoted: 'bg-sky-100 text-sky-800',
  confirmed: 'bg-emerald-100 text-emerald-800',
  checked_in: 'bg-indigo-100 text-indigo-800',
  checked_out: 'bg-slate-100 text-slate-700',
  rejected: 'bg-rose-100 text-rose-800',
  canceled: 'bg-slate-100 text-slate-700',
  new: 'bg-amber-100 text-amber-800',
  triaged: 'bg-blue-100 text-blue-800',
  in_progress: 'bg-blue-100 text-blue-800',
  scheduled: 'bg-indigo-100 text-indigo-800',
  waiting_on_guest: 'bg-fuchsia-100 text-fuchsia-800',
  completed: 'bg-emerald-100 text-emerald-800',
  issued: 'bg-sky-100 text-sky-800',
  overdue: 'bg-rose-100 text-rose-800',
  partially_paid: 'bg-orange-100 text-orange-800',
  paid: 'bg-emerald-100 text-emerald-800',
  maintenance: 'bg-rose-100 text-rose-800',
  reserved: 'bg-amber-100 text-amber-800',
  occupied: 'bg-indigo-100 text-indigo-800',
  available: 'bg-emerald-100 text-emerald-800',
  cleaning_hold: 'bg-cyan-100 text-cyan-800',
  urgent: 'bg-rose-100 text-rose-800',
  high: 'bg-orange-100 text-orange-800',
  normal: 'bg-slate-100 text-slate-700',
  low: 'bg-slate-100 text-slate-700',
} as const;

const formatDate = (value?: string | null) => {
  if (!value) {
    return 'TBD';
  }

  return new Intl.DateTimeFormat('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  }).format(new Date(value));
};

const formatDateTime = (value?: string | null) => {
  if (!value) {
    return 'No timestamp';
  }

  return new Intl.DateTimeFormat('en-US', {
    month: 'short',
    day: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
  }).format(new Date(value));
};

const formatMoney = (amount: number, currency = 'USD') => {
  try {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency,
      maximumFractionDigits: 0,
    }).format(amount || 0);
  } catch (_error) {
    return `$${amount || 0}`;
  }
};

const humanizeToken = (value?: string | null) => {
  if (!value) {
    return 'Unspecified';
  }

  return value
    .split('_')
    .map((token) => token.charAt(0).toUpperCase() + token.slice(1))
    .join(' ');
};

const getBadgeClassName = (value?: string | null) => {
  if (!value) {
    return 'bg-slate-100 text-slate-700';
  }

  return statusTone[value as keyof typeof statusTone] || 'bg-slate-100 text-slate-700';
};

type ActionItem = {
  title: string;
  description: string;
  href: string;
  icon: string;
  visible: boolean;
  priority?: number;
};

type FocusItem = {
  label: string;
  value: string;
  detail: string;
  visible?: boolean;
};

type ActivitySection = {
  title: string;
  href: string;
  emptyState: string;
  items: Array<{
    id: string;
    title: string;
    subtitle: string;
    meta: string;
    badge: string | null;
    extra?: string;
  }>;
};

const MetricSummaryCard = ({ title, value, detail, icon }: MetricCard) => (
  <CardBox className="h-full">
    <div className="flex items-start justify-between gap-4">
      <div>
        <p className="text-xs uppercase tracking-[0.2em] text-slate-400">{title}</p>
        <p className="mt-3 text-3xl font-semibold text-white">{value}</p>
        <p className="mt-2 text-sm leading-6 text-slate-400">{detail}</p>
      </div>
      <div className="rounded-xl border border-white/10 bg-white/5 p-3 text-slate-200">
        <BaseIcon path={icon} size={22} />
      </div>
    </div>
  </CardBox>
);

const FocusListItem = ({ label, value, detail }: FocusItem) => (
  <div className="flex items-start justify-between gap-4 rounded-xl border border-white/10 bg-white/5 px-4 py-3">
    <div>
      <div className="text-sm font-medium text-white">{label}</div>
      <div className="mt-1 text-sm text-slate-400">{detail}</div>
    </div>
    <div className="text-lg font-semibold text-white">{value}</div>
  </div>
);

const ROLE_LANES = {
  superAdmin: new Set(['Super Administrator']),
  admin: new Set(['Administrator', 'Platform Owner', 'Operations Director', 'Reservations Lead', 'Finance Controller']),
  concierge: new Set(['Concierge Coordinator']),
  customer: new Set(['Customer']),
};

const getRoleLane = (roleName: string, hasGlobalAccess: boolean) => {
  if (hasGlobalAccess || ROLE_LANES.superAdmin.has(roleName)) {
    return 'super_admin';
  }

  if (ROLE_LANES.admin.has(roleName)) {
    return 'admin';
  }

  if (ROLE_LANES.customer.has(roleName)) {
    return 'customer';
  }

  return 'concierge';
};

const ActivityCard = ({ title, href, emptyState, items }: ActivitySection) => (
  <CardBox className="h-full">
    <div className="mb-4 flex items-center justify-between gap-3">
      <div>
        <h3 className="text-lg font-semibold text-white">{title}</h3>
        <p className="text-sm text-slate-400">Latest operational items.</p>
      </div>
      <Link href={href} className="text-sm font-medium text-sky-300 hover:text-sky-200">
        View all
      </Link>
    </div>

    <div className="space-y-3">
      {items.length === 0 ? (
        <div className="rounded-xl border border-dashed border-white/10 px-4 py-5 text-sm text-slate-400">
          {emptyState}
        </div>
      ) : (
        items.map((item) => (
          <div key={item.id} className="rounded-xl border border-white/10 bg-white/5 px-4 py-3">
            <div className="flex items-start justify-between gap-3">
              <div>
                <div className="text-sm font-medium text-white">{item.title}</div>
                <div className="mt-1 text-sm text-slate-400">{item.subtitle}</div>
              </div>
              <span className={`rounded-full px-2.5 py-1 text-xs font-medium ${getBadgeClassName(item.badge)}`}>
                {humanizeToken(item.badge)}
              </span>
            </div>
            <div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-2 text-xs text-slate-400">
              <span>{item.meta}</span>
              {item.extra ? <span>{item.extra}</span> : null}
            </div>
          </div>
        ))
      )}
    </div>
  </CardBox>
);

const CommandCenterPage = () => {
  const { currentUser } = useAppSelector((state) => state.auth);
  const [overview, setOverview] = useState<OverviewResponse>(emptyOverview);
  const [isLoading, setIsLoading] = useState(true);
  const [errorMessage, setErrorMessage] = useState('');

  const organizationName =
    currentUser?.organizations?.name || currentUser?.organization?.name || 'your corporate workspace';
  const firstName = currentUser?.firstName || currentUser?.email || 'team';
  const roleName = currentUser?.app_role?.name || 'Team member';
  const roleLane = getRoleLane(roleName, Boolean(currentUser?.app_role?.globalAccess));
  const isSuperAdmin = roleLane === 'super_admin';
  const isAdmin = roleLane === 'admin';
  const isCustomer = roleLane === 'customer';
  const dashboardLens = isSuperAdmin
    ? 'Network oversight'
    : isAdmin
      ? 'Approval and portfolio operations'
      : isCustomer
        ? 'Customer stay visibility'
        : 'Concierge delivery';
  const dashboardHeadline = isSuperAdmin
    ? 'See every handoff across accounts, inventory, service, and revenue.'
    : isAdmin
      ? 'Approve faster, place stays cleanly, and keep billing exposure visible.'
      : isCustomer
        ? 'Request stays, follow reservation status, and stay connected during the trip.'
        : 'Move travelers from request to arrival without losing operational detail.';
  const dashboardDescription = isSuperAdmin
    ? `You share the same command center as every operating role, but your lens spans organizations, portfolio health, and revenue risk across ${organizationName}.`
    : isAdmin
      ? `You work from the same live records as customers, coordinators, and leadership, with a sharper focus on approvals, reservations, and financial follow-through for ${organizationName}.`
      : isCustomer
        ? `You work from the same live records as concierge and administrators, focused on request status, confirmed stays, documents, and active support for ${organizationName}.`
        : `You operate from the same live workspace as customers, administrators, and leadership, focused on intake, guest movement, and service execution for ${organizationName}.`;

  const loadOverview = useCallback(async () => {
    try {
      setIsLoading(true);
      setErrorMessage('');
      const response = await axios.get('/corporate-stay-portal/overview');
      setOverview(response.data);
    } catch (error) {
      console.error('Failed to load command center overview:', error);
      setErrorMessage('The command center could not load live operational data. Please try again.');
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    loadOverview();
  }, [loadOverview]);

  const canCreateBookingRequest = Boolean(currentUser && hasPermission(currentUser, 'CREATE_BOOKING_REQUESTS'));
  const canReadApprovals = Boolean(currentUser && hasPermission(currentUser, 'READ_APPROVAL_STEPS'));
  const canReadReservations = Boolean(currentUser && hasPermission(currentUser, 'READ_RESERVATIONS'));
  const canReadServiceRequests = Boolean(currentUser && hasPermission(currentUser, 'READ_SERVICE_REQUESTS'));
  const canReadInvoices = Boolean(currentUser && hasPermission(currentUser, 'READ_INVOICES'));
  const canReadBookings = Boolean(currentUser && hasPermission(currentUser, 'READ_BOOKING_REQUESTS'));

  const metricCards: MetricCard[] = [
    {
      title: 'Pending review',
      value: `${overview.bookingRequests.pendingReview}`,
      detail: `${overview.approvals.pending} approvals are waiting on sign-off.`,
      icon: mdiClipboardTextOutline,
      visible: overview.access.bookings || overview.access.approvals,
    },
    {
      title: 'Upcoming arrivals',
      value: `${overview.reservations.upcomingArrivals}`,
      detail: `${overview.reservations.inHouse} travelers are currently in house.`,
      icon: mdiCalendarCheck,
      visible: overview.access.reservations,
    },
    {
      title: 'Open service queue',
      value: `${overview.serviceRequests.open}`,
      detail: `${overview.serviceRequests.urgent} urgent requests need attention.`,
      icon: mdiRoomService,
      visible: overview.access.serviceRequests,
    },
    {
      title: 'Open balance',
      value: formatMoney(overview.invoices.openBalance, overview.invoices.recent[0]?.currency || 'USD'),
      detail: `${overview.invoices.statusCounts.overdue || 0} invoices are overdue.`,
      icon: mdiFileDocument,
      visible: overview.access.invoices,
    },
  ].filter((card) => card.visible);

  const heroStats: HeroStat[] = [
    {
      title: 'Corporate accounts',
      value: `${overview.organizations.total}`,
      detail: 'Organizations in the current operating scope.',
      visible: overview.access.accounts,
    },
    {
      title: 'Live properties',
      value: `${overview.inventory.activeProperties}`,
      detail: 'Properties open for negotiated corporate stays.',
      visible: overview.access.inventory,
    },
    {
      title: 'Last refresh',
      value: formatDateTime(overview.generatedAt),
      detail: 'Live snapshot across operations and billing.',
      visible: true,
    },
  ].filter((stat) => stat.visible);

  const quickActions: ActionItem[] = [
    {
      title: 'Create booking request',
      description: 'Start a new corporate stay request.',
      href: '/booking_requests/booking_requests-new',
      icon: mdiArrowTopRight,
      visible: canCreateBookingRequest,
      priority: isSuperAdmin ? 5 : isAdmin ? 4 : isCustomer ? 1 : 2,
    },
    {
      title: 'Review approvals',
      description: 'Process pending client sign-off.',
      href: '/approval_steps/approval_steps-list',
      icon: mdiCheckDecagram,
      visible: canReadApprovals,
      priority: isSuperAdmin ? 3 : isAdmin ? 1 : isCustomer ? 6 : 4,
    },
    {
      title: 'Open reservations',
      description: 'Confirm stays and monitor arrivals.',
      href: '/reservations/reservations-list',
      icon: mdiCalendarCheck,
      visible: canReadReservations,
      priority: isSuperAdmin ? 4 : isAdmin ? 2 : isCustomer ? 2 : 1,
    },
    {
      title: 'Service queue',
      description: 'Stay on top of open guest and property requests.',
      href: '/service_requests/service_requests-list',
      icon: mdiRoomService,
      visible: canReadServiceRequests,
      priority: isSuperAdmin ? 6 : isAdmin ? 5 : isCustomer ? 3 : 3,
    },
    {
      title: 'Finance view',
      description: 'Track invoice exposure and overdue items.',
      href: '/invoices/invoices-list',
      icon: mdiFileDocument,
      visible: canReadInvoices,
      priority: isSuperAdmin ? 1 : isAdmin ? 3 : isCustomer ? 6 : 6,
    },
    {
      title: 'Portfolio view',
      description: 'Monitor active properties and operating capacity.',
      href: '/properties/properties-list',
      icon: mdiHomeCity,
      visible: overview.access.inventory,
      priority: isSuperAdmin ? 2 : isAdmin ? 6 : isCustomer ? 6 : 5,
    },
  ]
    .filter((item) => item.visible)
    .sort((left, right) => (left.priority || 99) - (right.priority || 99));

  const laneTitle = isSuperAdmin
    ? 'Leadership lane'
    : isAdmin
      ? 'Approval and portfolio lane'
      : isCustomer
        ? 'Customer request lane'
        : 'Concierge execution lane';

  const laneDescription = isSuperAdmin
    ? 'The same shared records, viewed through account health, supply, and revenue exposure.'
    : isAdmin
      ? 'The same shared records, centered on approvals, placement quality, and billing follow-through.'
      : isCustomer
        ? 'The same shared records, centered on stay requests, reservation status, and live service support.'
        : 'The same shared records, centered on intake speed, arrivals, and service coordination.';

  const focusItems: FocusItem[] = (isSuperAdmin
    ? [
        {
          label: 'Organizations in scope',
          value: `${overview.organizations.total}`,
          detail: 'Corporate accounts currently visible in your network view.',
          visible: overview.access.accounts,
        },
        {
          label: 'Active properties',
          value: `${overview.inventory.activeProperties}`,
          detail: 'Supply currently available for corporate allocation.',
          visible: overview.access.inventory,
        },
        {
          label: 'Open balance',
          value: formatMoney(overview.invoices.openBalance, overview.invoices.recent[0]?.currency || 'USD'),
          detail: 'Outstanding invoice exposure across the current operating scope.',
          visible: overview.access.invoices,
        },
        {
          label: 'Urgent service items',
          value: `${overview.serviceRequests.urgent}`,
          detail: 'High-risk stays or property issues that may affect service quality.',
          visible: overview.access.serviceRequests,
        },
      ]
    : isAdmin
      ? [
          {
            label: 'Approvals waiting',
            value: `${overview.approvals.pending}`,
            detail: 'Requests that still need client or internal sign-off.',
            visible: overview.access.approvals,
          },
          {
            label: 'Approved and ready',
            value: `${overview.bookingRequests.approvedReady}`,
            detail: 'Demand ready to quote or convert into reservations.',
            visible: overview.access.bookings,
          },
          {
            label: 'Arrivals ahead',
            value: `${overview.reservations.upcomingArrivals}`,
            detail: 'Upcoming arrivals that may need final placement review.',
            visible: overview.access.reservations,
          },
          {
            label: 'Open balance',
            value: formatMoney(overview.invoices.openBalance, overview.invoices.recent[0]?.currency || 'USD'),
            detail: 'Outstanding billing that may need follow-up before closeout.',
            visible: overview.access.invoices,
          },
        ]
      : isCustomer
        ? [
            {
              label: 'Requests in motion',
              value: `${overview.bookingRequests.pendingReview}`,
              detail: 'Stay requests that are still moving through review or confirmation.',
              visible: overview.access.bookings,
            },
            {
              label: 'Upcoming stays',
              value: `${overview.reservations.upcomingArrivals}`,
              detail: 'Confirmed arrivals coming up soon in your current scope.',
              visible: overview.access.reservations,
            },
            {
              label: 'Guests in house',
              value: `${overview.reservations.inHouse}`,
              detail: 'Active stays that may still need service coordination.',
              visible: overview.access.reservations,
            },
            {
              label: 'Support queue',
              value: `${overview.serviceRequests.open}`,
              detail: 'Open service requests tied to live reservations or traveler needs.',
              visible: overview.access.serviceRequests,
            },
          ]
        : [
            {
              label: 'New demand',
              value: `${overview.bookingRequests.pendingReview}`,
              detail: 'Requests currently entering review or awaiting next action.',
              visible: overview.access.bookings,
            },
            {
              label: 'Guests in house',
              value: `${overview.reservations.inHouse}`,
              detail: 'Travelers currently active across your operating scope.',
              visible: overview.access.reservations,
            },
            {
              label: 'Service queue',
              value: `${overview.serviceRequests.open}`,
              detail: 'Open guest or property requests needing execution.',
              visible: overview.access.serviceRequests,
            },
            {
              label: 'Departures ahead',
              value: `${overview.reservations.upcomingDepartures}`,
              detail: 'Upcoming departures that may require extensions or billing checks.',
              visible: overview.access.reservations,
            },
          ])
    .filter((item) => item.visible);

  const connectedWorkflow = [
    {
      title: 'Request submission',
      owner: 'Customer',
      value: `${overview.bookingRequests.pendingReview}`,
      detail: 'Customers initiate stay demand once, keeping dates, traveler context, and special requirements attached to the same shared record.',
      href: '/booking_requests/booking_requests-list',
      visible: canReadBookings || canCreateBookingRequest,
    },
    {
      title: 'Approval and placement',
      owner: 'Administrator',
      value: `${overview.bookingRequests.approvedReady}`,
      detail: 'Approved demand becomes placement-ready work, so administrators can quote, confirm, and convert stays without rekeying data.',
      href: '/approval_steps/approval_steps-list',
      visible: canReadApprovals || canReadReservations,
    },
    {
      title: 'Stay execution',
      owner: 'Concierge Coordinator',
      value: `${overview.serviceRequests.open}`,
      detail: 'Confirmed reservations carry forward into arrivals, in-house service, and operational follow-through.',
      href: '/service_requests/service_requests-list',
      visible: canReadReservations || canReadServiceRequests,
    },
    {
      title: 'Oversight and finance',
      owner: 'Super Administrator',
      value: formatMoney(overview.invoices.openBalance, overview.invoices.recent[0]?.currency || 'USD'),
      detail: 'Leadership sees the same records aggregated across accounts, portfolio capacity, and invoice exposure.',
      href: '/invoices/invoices-list',
      visible: canReadInvoices || overview.access.inventory || overview.access.accounts,
    },
  ].filter((step) => step.visible);

  const activitySections: ActivitySection[] = [
    {
      title: 'Booking requests',
      href: '/booking_requests/booking_requests-list',
      emptyState: 'No recent booking requests in scope.',
      items: canReadBookings
        ? overview.bookingRequests.recent.slice(0, 3).map((item) => ({
            id: item.id,
            title: item.request_code || 'Booking request',
            subtitle: `${item.organizationName} · ${item.propertyName || item.unitTypeName || 'Pending property'}`,
            meta: `${formatDate(item.check_in_at)} → ${formatDate(item.check_out_at)}`,
            extra: `${item.guest_count || 0} guests`,
            badge: item.status,
          }))
        : [],
    },
    {
      title: 'Reservations',
      href: '/reservations/reservations-list',
      emptyState: 'No recent reservations in scope.',
      items: canReadReservations
        ? overview.reservations.recent.slice(0, 3).map((item) => ({
            id: item.id,
            title: item.reservation_code || 'Reservation',
            subtitle: `${item.organizationName} · ${item.propertyName || item.unitNumber || 'Pending unit'}`,
            meta: `${formatDate(item.check_in_at)} → ${formatDate(item.check_out_at)}`,
            extra: item.sourceRequestCode ? `From ${item.sourceRequestCode}` : undefined,
            badge: item.status,
          }))
        : [],
    },
    {
      title: 'Service requests',
      href: '/service_requests/service_requests-list',
      emptyState: 'No recent service requests in scope.',
      items: canReadServiceRequests
        ? overview.serviceRequests.recent.slice(0, 3).map((item) => ({
            id: item.id,
            title: humanizeToken(item.request_type),
            subtitle: item.summary || item.assignedTo || 'Awaiting assignment',
            meta: item.due_at ? `Due ${formatDate(item.due_at)}` : `Updated ${formatDateTime(item.updatedAt)}`,
            extra: item.reservationCode ? `Reservation ${item.reservationCode}` : undefined,
            badge: item.priority === 'urgent' ? item.priority : item.status,
          }))
        : [],
    },
    {
      title: 'Invoices',
      href: '/invoices/invoices-list',
      emptyState: 'No recent invoices in scope.',
      items: canReadInvoices
        ? overview.invoices.recent.slice(0, 3).map((item) => ({
            id: item.id,
            title: item.invoice_number || 'Invoice draft',
            subtitle: item.organizationName,
            meta: `Balance ${formatMoney(item.balance_due, item.currency)}`,
            extra: item.due_at ? `Due ${formatDate(item.due_at)}` : undefined,
            badge: item.status,
          }))
        : [],
    },
  ].filter((section) => section.items.length > 0);

  const hasModuleAccess = Object.values(overview.access).some(Boolean);

  return (
    <>
      <Head>
        <title>{getPageTitle('Command Center')}</title>
      </Head>

      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiViewDashboardOutline}
          title="Command Center"
          subtitle="One shared operating dashboard with role-specific modules and visibility."
          main
        >
          <BaseButton color="whiteDark" icon={mdiRefresh} label="Refresh" onClick={loadOverview} />
        </SectionTitleLineWithButton>

        {errorMessage ? (
          <CardBox className="mb-6 border border-rose-200 bg-rose-50">
            <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
              <div>
                <div className="text-sm font-semibold uppercase tracking-[0.18em] text-rose-700">
                  Operational feed unavailable
                </div>
                <p className="mt-2 text-sm text-rose-900">{errorMessage}</p>
              </div>
              <BaseButton color="danger" label="Retry" onClick={loadOverview} />
            </div>
          </CardBox>
        ) : null}

        {isLoading ? (
          <CardBox className="mb-6">
            <div className="flex items-center gap-3 text-sm text-slate-300">
              <BaseIcon path={mdiClockOutline} className="animate-pulse text-slate-400" />
              Building the latest corporate operations snapshot...
            </div>
          </CardBox>
        ) : null}

        {!isLoading && !hasModuleAccess ? (
          <CardBox>
            <div className="max-w-2xl">
              <div className="text-xs uppercase tracking-[0.22em] text-slate-400">Limited role access</div>
              <h2 className="mt-2 text-2xl font-semibold text-white">
                Your account is authenticated, but it does not currently expose operational modules.
              </h2>
              <p className="mt-3 text-sm leading-7 text-slate-400">
                Ask a super admin to grant booking, reservation, concierge, or finance permissions. Once those are
                enabled, this workspace will populate automatically with live data.
              </p>
            </div>
          </CardBox>
        ) : null}

        {!isLoading && hasModuleAccess ? (
          <>
            <section className="mb-8 overflow-hidden rounded-2xl border border-white/10 bg-slate-950 shadow-lg">
              <div className="grid gap-6 px-6 py-7 lg:grid-cols-[1.35fr_0.85fr] lg:px-8">
                <div>
                  <div className="inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-3 py-1 text-xs uppercase tracking-[0.24em] text-slate-300">
                    <BaseIcon path={mdiAccountTie} className="text-slate-200" />
                    Shared dashboard · {dashboardLens}
                  </div>
                  <div className="mt-4 inline-flex items-center rounded-full border border-cyan-300/20 bg-cyan-400/10 px-3 py-1 text-xs font-medium text-cyan-100">
                    Role: {roleName}
                  </div>
                  <h2 className="mt-4 max-w-3xl text-3xl font-semibold leading-tight text-white md:text-4xl">
                    {dashboardHeadline}
                  </h2>
                  <p className="mt-4 max-w-2xl text-sm leading-7 text-slate-300 md:text-base">
                    Welcome back, {firstName}. {dashboardDescription}
                  </p>

                  <div className="mt-6 flex flex-wrap gap-3">
                    {quickActions.map((action, index) => (
                      <BaseButton
                        key={action.title}
                        href={action.href}
                        color={index === 0 ? 'info' : 'whiteDark'}
                        icon={action.icon}
                        label={action.title}
                      />
                    ))}
                  </div>
                </div>

                <div className="grid gap-3 sm:grid-cols-3 lg:grid-cols-1">
                  {heroStats.map((stat) => (
                    <div key={stat.title} className="rounded-2xl border border-white/10 bg-white/5 p-4">
                      <div className="text-xs uppercase tracking-[0.2em] text-slate-400">{stat.title}</div>
                      <div className="mt-2 text-3xl font-semibold text-white">{stat.value}</div>
                      <div className="mt-2 text-sm text-slate-400">{stat.detail}</div>
                    </div>
                  ))}
                </div>
              </div>
            </section>

            {metricCards.length ? (
              <div className="mb-8 grid gap-4 md:grid-cols-2 xl:grid-cols-4">
                {metricCards.map((card) => (
                  <MetricSummaryCard key={card.title} {...card} />
                ))}
              </div>
            ) : null}

            <div className="mb-8 grid gap-6 xl:grid-cols-[1.1fr_0.9fr]">
              <CardBox>
                <div className="mb-5 flex items-start justify-between gap-3">
                  <div>
                    <h3 className="text-lg font-semibold text-white">Core workflows</h3>
                    <p className="text-sm text-slate-400">Use the main operational flows without opening the full menu.</p>
                  </div>
                </div>

                <div className="grid gap-3 md:grid-cols-2">
                  {quickActions.length ? (
                    quickActions.map((action) => (
                      <Link
                        key={action.title}
                        href={action.href}
                        className="rounded-xl border border-white/10 bg-white/5 px-4 py-4 transition hover:bg-white/10"
                      >
                        <div className="flex items-start gap-3">
                          <div className="rounded-xl border border-white/10 bg-white/5 p-2 text-slate-200">
                            <BaseIcon path={action.icon} size={20} />
                          </div>
                          <div>
                            <div className="text-sm font-medium text-white">{action.title}</div>
                            <div className="mt-1 text-sm text-slate-400">{action.description}</div>
                          </div>
                        </div>
                      </Link>
                    ))
                  ) : (
                    <div className="rounded-xl border border-dashed border-white/10 px-4 py-5 text-sm text-slate-400">
                      No primary workflows are available for your current role.
                    </div>
                  )}
                </div>
              </CardBox>

              <CardBox>
                <div className="mb-5 flex items-start justify-between gap-3">
                  <div>
                    <h3 className="text-lg font-semibold text-white">{laneTitle}</h3>
                    <p className="text-sm text-slate-400">{laneDescription}</p>
                  </div>
                </div>

                <div className="space-y-3">
                  {focusItems.length ? (
                    focusItems.map((item) => <FocusListItem key={item.label} {...item} />)
                  ) : (
                    <div className="rounded-xl border border-dashed border-white/10 px-4 py-5 text-sm text-slate-400">
                      This lane will populate as more role permissions are enabled.
                    </div>
                  )}
                </div>
              </CardBox>
            </div>

            {connectedWorkflow.length ? (
              <CardBox className="mb-8">
                <div className="mb-5 flex items-start justify-between gap-3">
                  <div>
                    <h3 className="text-lg font-semibold text-white">Interconnected operating model</h3>
                    <p className="text-sm text-slate-400">
                      Customers, concierge, administrators, and super admins share the same command center, but each role acts on a different part of the same live workflow.
                    </p>
                  </div>
                </div>

                <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
                  {connectedWorkflow.map((step) => (
                    <Link
                      key={step.title}
                      href={step.href}
                      className="rounded-xl border border-white/10 bg-white/5 px-4 py-4 transition hover:bg-white/10"
                    >
                      <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">{step.owner}</div>
                      <div className="mt-2 text-lg font-semibold text-white">{step.title}</div>
                      <div className="mt-3 text-2xl font-semibold text-white">{step.value}</div>
                      <p className="mt-2 text-sm leading-6 text-slate-400">{step.detail}</p>
                    </Link>
                  ))}
                </div>
              </CardBox>
            ) : null}

            <div className="grid gap-6 xl:grid-cols-2 2xl:grid-cols-4">
              {activitySections.map((section) => (
                <ActivityCard key={section.title} {...section} />
              ))}
            </div>
          </>
        ) : null}
      </SectionMain>
    </>
  );
};

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

export default CommandCenterPage;
