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

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 { useAppSelector } from '../stores/hooks';

type DashboardCount = number | string | null;

type DashboardEntity = {
  key: string;
  label: string;
  description: string;
  href: string;
  permission: string;
  icon: string;
  group: 'commercial' | 'catalog' | 'fulfillment' | 'system';
};

type UserSummary = {
  firstName?: string;
  lastName?: string;
  email?: string;
};

type PriceListSummary = {
  price_list_name?: string;
};

type AccountSummary = {
  id: string;
  account_name: string;
  account_type?: string;
  account_number?: string;
  credit_status?: string;
  credit_limit?: string;
  notes?: string;
  default_price_list?: PriceListSummary;
  assigned_sales_rep?: UserSummary;
};

type LocationSummary = {
  location_name?: string;
  city?: string;
  state?: string;
};

type OrderSummary = {
  id: string;
  order_number: string;
  po_number?: string;
  order_status?: string;
  order_total?: string | number;
  ordered_at?: string;
  requested_delivery_date?: string;
  promised_delivery_date?: string;
  account?: AccountSummary;
  location?: LocationSummary;
  buyer?: UserSummary;
};

type SampleRequestSummary = {
  id: string;
  sample_request_number: string;
  sample_status?: string;
  needed_by?: string;
  account?: AccountSummary;
  product?: ProductSummary;
  requested_by?: UserSummary;
};

type QuoteSummary = {
  id: string;
  quote_number: string;
  quote_status?: string;
  quote_total?: string | number;
  expires_at?: string;
  account?: AccountSummary;
  owner?: UserSummary;
};

type ProductSummary = {
  id: string;
  sku?: string;
  product_name: string;
  brand?: string;
  product_status?: string;
  temperature_zone?: string;
  moq_cases?: number;
  is_sample_eligible?: boolean;
  category?: {
    category_name?: string;
  };
  spec_sheet?: unknown[];
};

type InventoryItemSummary = {
  id: string;
  warehouse_name?: string;
  available_cases?: number;
  allocated_cases?: number;
  product?: ProductSummary;
};

const supplierDashboardPermissions = [
  'READ_ACCOUNTS',
  'READ_PRODUCTS',
  'READ_ORDERS',
  'READ_INVENTORY_ITEMS',
];

const dashboardEntities: DashboardEntity[] = [
  {
    key: 'accounts',
    label: 'Buyer accounts',
    description: 'Restaurant groups, hotels, caterers, and contracted buyers.',
    href: '/accounts/accounts-list',
    permission: 'READ_ACCOUNTS',
    icon: icon.mdiDomain,
    group: 'commercial',
  },
  {
    key: 'locations',
    label: 'Ship-to locations',
    description: 'Receiving docks, restaurants, hotel kitchens, and contacts.',
    href: '/locations/locations-list',
    permission: 'READ_LOCATIONS',
    icon: icon.mdiMapMarker,
    group: 'commercial',
  },
  {
    key: 'contacts',
    label: 'Buyer contacts',
    description: 'Purchasing, receiving, chef, and accounting stakeholders.',
    href: '/contacts/contacts-list',
    permission: 'READ_CONTACTS',
    icon: icon.mdiAccountMultiple,
    group: 'commercial',
  },
  {
    key: 'price_lists',
    label: 'Price lists',
    description: 'Contract price files and customer-specific buying terms.',
    href: '/price_lists/price_lists-list',
    permission: 'READ_PRICE_LISTS',
    icon: icon.mdiCashMultiple,
    group: 'commercial',
  },
  {
    key: 'account_price_lists',
    label: 'Account pricing',
    description: 'Assigned contract lists, effective dates, and exceptions.',
    href: '/account_price_lists/account_price_lists-list',
    permission: 'READ_ACCOUNT_PRICE_LISTS',
    icon: icon.mdiLinkVariant,
    group: 'commercial',
  },
  {
    key: 'quotes',
    label: 'Quotes',
    description: 'Commercial follow-up for negotiated buyer opportunities.',
    href: '/quotes/quotes-list',
    permission: 'READ_QUOTES',
    icon: icon.mdiFileDocumentOutline,
    group: 'commercial',
  },
  {
    key: 'products',
    label: 'Products',
    description: 'SKUs, brands, pack sizes, allergens, and sample flags.',
    href: '/products/products-list',
    permission: 'READ_PRODUCTS',
    icon: icon.mdiPackageVariantClosed,
    group: 'catalog',
  },
  {
    key: 'product_categories',
    label: 'Categories',
    description: 'Chef pantry, dairy, prepared proteins, desserts, and more.',
    href: '/product_categories/product_categories-list',
    permission: 'READ_PRODUCT_CATEGORIES',
    icon: icon.mdiTagMultiple,
    group: 'catalog',
  },
  {
    key: 'inventory_items',
    label: 'Inventory',
    description: 'Warehouse availability, committed stock, and backorders.',
    href: '/inventory_items/inventory_items-list',
    permission: 'READ_INVENTORY_ITEMS',
    icon: icon.mdiWarehouse,
    group: 'catalog',
  },
  {
    key: 'sample_requests',
    label: 'Sample requests',
    description: 'Chef tastings and buyer evaluation workflows.',
    href: '/sample_requests/sample_requests-list',
    permission: 'READ_SAMPLE_REQUESTS',
    icon: icon.mdiPackageVariant,
    group: 'catalog',
  },
  {
    key: 'saved_lists',
    label: 'Saved order guides',
    description: 'Buyer reorder lists and account-specific replenishment sets.',
    href: '/saved_lists/saved_lists-list',
    permission: 'READ_SAVED_LISTS',
    icon: icon.mdiBookmarkMultiple,
    group: 'catalog',
  },
  {
    key: 'orders',
    label: 'Orders',
    description: 'Purchase orders submitted by buyer accounts.',
    href: '/orders/orders-list',
    permission: 'READ_ORDERS',
    icon: icon.mdiClipboardText,
    group: 'fulfillment',
  },
  {
    key: 'order_items',
    label: 'Order lines',
    description: 'SKU-level picking, pricing, and fulfillment state.',
    href: '/order_items/order_items-list',
    permission: 'READ_ORDER_ITEMS',
    icon: icon.mdiClipboardList,
    group: 'fulfillment',
  },
  {
    key: 'shipments',
    label: 'Shipments',
    description: 'Delivery handoff, routes, and shipment status.',
    href: '/shipments/shipments-list',
    permission: 'READ_SHIPMENTS',
    icon: icon.mdiTruckDelivery,
    group: 'fulfillment',
  },
  {
    key: 'carts',
    label: 'Carts',
    description: 'In-progress buyer purchase order drafts.',
    href: '/carts/carts-list',
    permission: 'READ_CARTS',
    icon: icon.mdiCart,
    group: 'fulfillment',
  },
  {
    key: 'users',
    label: 'Users',
    description: 'Internal team members and invited buyer users.',
    href: '/users/users-list',
    permission: 'READ_USERS',
    icon: icon.mdiAccountGroup,
    group: 'system',
  },
  {
    key: 'roles',
    label: 'Roles',
    description: 'Admin, buyer admin, buyer user, and operational access.',
    href: '/roles/roles-list',
    permission: 'READ_ROLES',
    icon: icon.mdiShieldAccountVariantOutline,
    group: 'system',
  },
  {
    key: 'permissions',
    label: 'Permissions',
    description: 'Fine-grained CRUD and buyer portal access controls.',
    href: '/permissions/permissions-list',
    permission: 'READ_PERMISSIONS',
    icon: icon.mdiShieldAccountOutline,
    group: 'system',
  },
];

const groupCopy = {
  commercial: {
    title: 'Commercial control',
    subtitle: 'Accounts, price files, contacts, and quote follow-up.',
  },
  catalog: {
    title: 'Catalog readiness',
    subtitle: 'Foodservice SKUs, samples, stock, and order guides.',
  },
  fulfillment: {
    title: 'Fulfillment floor',
    subtitle: 'Purchase orders, lines, carts, and delivery handoff.',
  },
  system: {
    title: 'Access control',
    subtitle: 'Users, roles, permissions, and operational guardrails.',
  },
};

const currencyFormatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  maximumFractionDigits: 0,
});

const dateFormatter = new Intl.DateTimeFormat('en-US', {
  month: 'short',
  day: 'numeric',
});

const formatCount = (value: DashboardCount | undefined) => {
  if (value === undefined) {
    return 'Loading';
  }

  if (value === null) {
    return 'No access';
  }

  return String(value);
};

const formatCurrency = (value?: string | number) => {
  const numericValue = Number(value || 0);

  if (!Number.isFinite(numericValue)) {
    return '$0';
  }

  return currencyFormatter.format(numericValue);
};

const formatDate = (value?: string) => {
  if (!value) {
    return 'Not set';
  }

  return dateFormatter.format(new Date(value));
};

const formatUserName = (user?: UserSummary) => {
  if (!user) {
    return 'Unassigned';
  }

  const name = [user.firstName, user.lastName].filter(Boolean).join(' ');
  return name || user.email || 'Unassigned';
};

const humanizeStatus = (status?: string) => {
  if (!status) {
    return 'Unassigned';
  }

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

const getStatusClass = (status?: string) => {
  if (['approved', 'accepted', 'delivered', 'active', 'good'].includes(status || '')) {
    return 'border-emerald-200 bg-emerald-50 text-emerald-800';
  }

  if (['submitted', 'sent', 'in_review', 'shipped'].includes(status || '')) {
    return 'border-blue-200 bg-blue-50 text-blue-800';
  }

  if (['requested', 'draft', 'pending'].includes(status || '')) {
    return 'border-amber-200 bg-amber-50 text-amber-800';
  }

  if (['cancelled', 'declined', 'expired', 'exception', 'on_hold'].includes(status || '')) {
    return 'border-rose-200 bg-rose-50 text-rose-800';
  }

  return 'border-slate-200 bg-slate-50 text-slate-700';
};

const isOpenOrder = (order: OrderSummary) =>
  !['delivered', 'cancelled'].includes(order.order_status || '');

const isActiveSample = (sample: SampleRequestSummary) =>
  !['delivered', 'declined', 'cancelled'].includes(sample.sample_status || '');

const isPendingQuote = (quote: QuoteSummary) =>
  !['accepted', 'declined', 'expired'].includes(quote.quote_status || '');

const isDueSoon = (dateValue?: string) => {
  if (!dateValue) {
    return false;
  }

  const dueDate = new Date(dateValue).getTime();

  if (!Number.isFinite(dueDate)) {
    return false;
  }

  const sevenDaysFromNow = Date.now() + 7 * 24 * 60 * 60 * 1000;
  return dueDate <= sevenDaysFromNow;
};

const isDemoRecord = (id: string, prefix: string) => id.startsWith(prefix);

const StatusPill = ({ status }: { status?: string }) => (
  <span
    className={`inline-flex rounded-full border px-2.5 py-1 text-xs font-bold ${getStatusClass(
      status,
    )}`}
  >
    {humanizeStatus(status)}
  </span>
);

const EmptyState = ({ text }: { text: string }) => (
  <div className='rounded-xl border border-dashed border-slate-300 bg-slate-50 p-4 text-sm text-slate-500'>
    {text}
  </div>
);

const Dashboard = () => {
  const [counts, setCounts] = React.useState<Record<string, DashboardCount>>(
    {},
  );
  const [orders, setOrders] = React.useState<OrderSummary[]>([]);
  const [sampleRequests, setSampleRequests] = React.useState<
    SampleRequestSummary[]
  >([]);
  const [quotes, setQuotes] = React.useState<QuoteSummary[]>([]);
  const [accounts, setAccounts] = React.useState<AccountSummary[]>([]);
  const [products, setProducts] = React.useState<ProductSummary[]>([]);
  const [inventoryItems, setInventoryItems] = React.useState<
    InventoryItemSummary[]
  >([]);
  const [isLoading, setIsLoading] = React.useState(false);
  const [dashboardError, setDashboardError] = React.useState('');
  const { currentUser } = useAppSelector((state) => state.auth);

  const visibleEntities = React.useMemo(() => {
    return dashboardEntities.filter((entity) =>
      hasPermission(currentUser, entity.permission),
    );
  }, [currentUser]);

  const openOrders = React.useMemo(
    () => orders.filter(isOpenOrder).slice(0, 5),
    [orders],
  );
  const dueSoonOrders = React.useMemo(
    () =>
      orders
        .filter(isOpenOrder)
        .filter((order) => isDueSoon(order.requested_delivery_date)),
    [orders],
  );
  const activeSamples = React.useMemo(
    () => sampleRequests.filter(isActiveSample).slice(0, 4),
    [sampleRequests],
  );
  const pendingQuotes = React.useMemo(
    () => quotes.filter(isPendingQuote).slice(0, 4),
    [quotes],
  );
  const activeProducts = React.useMemo(
    () =>
      products.filter((product) => product.product_status !== 'discontinued'),
    [products],
  );
  const sampleReadyProducts = React.useMemo(
    () => activeProducts.filter((product) => product.is_sample_eligible),
    [activeProducts],
  );
  const missingSpecProducts = React.useMemo(
    () => activeProducts.filter((product) => !product.spec_sheet?.length),
    [activeProducts],
  );
  const inventoryAlerts = React.useMemo(
    () =>
      inventoryItems
        .filter((item) => Number(item.available_cases || 0) <= 3)
        .slice(0, 4),
    [inventoryItems],
  );
  const accountActivity = React.useMemo(() => {
    const activity = new Map<string, { openOrders: number; total: number }>();

    orders.forEach((order) => {
      if (!order.account?.id) {
        return;
      }

      const current = activity.get(order.account.id) || {
        openOrders: 0,
        total: 0,
      };
      current.total += Number(order.order_total || 0);

      if (isOpenOrder(order)) {
        current.openOrders += 1;
      }

      activity.set(order.account.id, current);
    });

    return activity;
  }, [orders]);

  const loadDashboard = React.useCallback(async () => {
    if (!currentUser) {
      return;
    }

    setIsLoading(true);
    setDashboardError('');

    try {
      const countResults = await Promise.allSettled(
        visibleEntities.map((entity) =>
          axios.get(`/${entity.key.toLowerCase()}/count`),
        ),
      );
      const nextCounts: Record<string, DashboardCount> = {};
      const failures: string[] = [];

      countResults.forEach((result, index) => {
        const entity = visibleEntities[index];

        if (result.status === 'fulfilled') {
          nextCounts[entity.key] = result.value.data.count;
        } else {
          console.error(
            `Failed to load dashboard count for ${entity.key}`,
            result.reason,
          );
          nextCounts[entity.key] = 'Error';
          failures.push(entity.label);
        }
      });

      const [
        ordersResult,
        samplesResult,
        quotesResult,
        accountsResult,
        productsResult,
        inventoryResult,
      ] = await Promise.allSettled([
        hasPermission(currentUser, 'READ_ORDERS')
          ? axios.get('/orders', { params: { page: 0, limit: 12 } })
          : Promise.resolve({ data: { rows: [] } }),
        hasPermission(currentUser, 'READ_SAMPLE_REQUESTS')
          ? axios.get('/sample_requests', { params: { page: 0, limit: 8 } })
          : Promise.resolve({ data: { rows: [] } }),
        hasPermission(currentUser, 'READ_QUOTES')
          ? axios.get('/quotes', { params: { page: 0, limit: 8 } })
          : Promise.resolve({ data: { rows: [] } }),
        hasPermission(currentUser, 'READ_ACCOUNTS')
          ? axios.get('/accounts', { params: { page: 0, limit: 8 } })
          : Promise.resolve({ data: { rows: [] } }),
        hasPermission(currentUser, 'READ_PRODUCTS')
          ? axios.get('/products', { params: { page: 0, limit: 18 } })
          : Promise.resolve({ data: { rows: [] } }),
        hasPermission(currentUser, 'READ_INVENTORY_ITEMS')
          ? axios.get('/inventory_items', { params: { page: 0, limit: 18 } })
          : Promise.resolve({ data: { rows: [] } }),
      ]);
      let loadedOrders: OrderSummary[] = [];
      let loadedSamples: SampleRequestSummary[] = [];
      let loadedQuotes: QuoteSummary[] = [];
      let loadedAccounts: AccountSummary[] = [];
      let loadedProducts: ProductSummary[] = [];
      let loadedInventory: InventoryItemSummary[] = [];

      if (ordersResult.status === 'fulfilled') {
        loadedOrders = (ordersResult.value.data.rows || []).filter(
          (order: OrderSummary) => isDemoRecord(order.id, '79300000'),
        );
        setOrders(loadedOrders);
      } else {
        console.error('Failed to load dashboard orders', ordersResult.reason);
        failures.push('Orders');
      }

      if (samplesResult.status === 'fulfilled') {
        loadedSamples = (samplesResult.value.data.rows || []).filter(
          (sample: SampleRequestSummary) => isDemoRecord(sample.id, '79200000'),
        );
        setSampleRequests(loadedSamples);
      } else {
        console.error(
          'Failed to load dashboard sample requests',
          samplesResult.reason,
        );
        failures.push('Sample requests');
      }

      if (quotesResult.status === 'fulfilled') {
        loadedQuotes = (quotesResult.value.data.rows || []).filter(
          (quote: QuoteSummary) => isDemoRecord(quote.id, '79000000'),
        );
        setQuotes(loadedQuotes);
      } else {
        console.error('Failed to load dashboard quotes', quotesResult.reason);
        failures.push('Quotes');
      }

      if (accountsResult.status === 'fulfilled') {
        loadedAccounts = (accountsResult.value.data.rows || []).filter(
          (account: AccountSummary) => isDemoRecord(account.id, '71000000'),
        );
        setAccounts(loadedAccounts);
      } else {
        console.error('Failed to load dashboard accounts', accountsResult.reason);
        failures.push('Accounts');
      }

      if (productsResult.status === 'fulfilled') {
        loadedProducts = (productsResult.value.data.rows || []).filter(
          (product: ProductSummary) => isDemoRecord(product.id, '75000000'),
        );
        setProducts(loadedProducts);
      } else {
        console.error('Failed to load dashboard products', productsResult.reason);
        failures.push('Products');
      }

      if (inventoryResult.status === 'fulfilled') {
        loadedInventory = inventoryResult.value.data.rows || [];
        setInventoryItems(loadedInventory);
      } else {
        console.error(
          'Failed to load dashboard inventory items',
          inventoryResult.reason,
        );
        failures.push('Inventory');
      }

      setCounts({
        ...nextCounts,
        orders: loadedOrders.length,
        sample_requests: loadedSamples.length,
        quotes: loadedQuotes.length,
        accounts: loadedAccounts.length,
        products: loadedProducts.length,
        inventory_items: loadedInventory.length,
      });

      if (failures.length) {
        setDashboardError(
          `Some dashboard data failed to load: ${failures.join(', ')}.`,
        );
      }
    } catch (error) {
      console.error('Failed to load supplier command center', error);
      setDashboardError('Unable to load the supplier command center.');
    } finally {
      setIsLoading(false);
    }
  }, [currentUser, visibleEntities]);

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

    void loadDashboard();
  }, [currentUser, loadDashboard]);

  const kpiCards = [
    {
      label: 'Open POs',
      value: openOrders.length,
      detail: `${formatCount(counts.orders)} total orders`,
      href: '/orders/orders-list',
      icon: icon.mdiClipboardText,
      tone: 'emerald',
    },
    {
      label: 'Fulfillment due',
      value: dueSoonOrders.length,
      detail: 'Due inside 7 days',
      href: '/orders/orders-list',
      icon: icon.mdiTruckDelivery,
      tone: 'blue',
    },
    {
      label: 'Sample queue',
      value: activeSamples.length,
      detail: `${formatCount(counts.sample_requests)} total requests`,
      href: '/sample_requests/sample_requests-list',
      icon: icon.mdiPackageVariant,
      tone: 'amber',
    },
    {
      label: 'Quote follow-up',
      value: pendingQuotes.length,
      detail: `${formatCount(counts.quotes)} total quotes`,
      href: '/quotes/quotes-list',
      icon: icon.mdiFileDocumentOutline,
      tone: 'violet',
    },
    {
      label: 'Contract SKUs',
      value: formatCount(counts.products),
      detail: `${sampleReadyProducts.length} sample-ready`,
      href: '/products/products-list',
      icon: icon.mdiPackageVariantClosed,
      tone: 'slate',
    },
    {
      label: 'Spec gaps',
      value: missingSpecProducts.length,
      detail: 'Need product spec sheets',
      href: '/products/products-list',
      icon: icon.mdiFileDocumentOutline,
      tone: 'rose',
    },
  ];

  return (
    <>
      <Head>
        <title>{getPageTitle('Supplier command center')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={icon.mdiChartTimelineVariant}
          title='Supplier command center'
          main
        >
          <div className='flex flex-wrap gap-2'>
            <Link
              href='/products/products-list'
              className='inline-flex h-10 items-center rounded-xl border border-emerald-200 bg-emerald-50 px-4 text-sm font-semibold text-emerald-800 hover:bg-emerald-100'
            >
              Contract catalog
            </Link>
            <Link
              href='/orders/orders-list'
              className='inline-flex h-10 items-center rounded-xl bg-slate-950 px-4 text-sm font-semibold text-white hover:bg-slate-800'
            >
              Open orders
            </Link>
          </div>
        </SectionTitleLineWithButton>

        {dashboardError && (
          <div className='mb-5 rounded-2xl border border-rose-200 bg-rose-50 p-4 text-sm font-semibold text-rose-800'>
            {dashboardError}
          </div>
        )}

        <section className='mb-6 overflow-hidden rounded-2xl border border-slate-200 bg-slate-950 text-white shadow-sm'>
          <div className='grid gap-6 p-6 xl:grid-cols-[minmax(0,1fr)_420px] xl:p-8'>
            <div>
              <p className='text-xs font-semibold uppercase tracking-[0.24em] text-emerald-300'>
                Northstar Foodservice operations
              </p>
              <h2 className='mt-4 max-w-4xl text-3xl font-semibold leading-tight lg:text-4xl'>
                Today&apos;s control room for contract buyers, price files,
                samples, and fulfillment handoff.
              </h2>
              <p className='mt-4 max-w-3xl text-sm leading-7 text-slate-300'>
                Monitor restaurant, hotel, and catering accounts without
                replacing POS or accounting. The portal sits between buyer
                demand, catalog readiness, and warehouse execution.
              </p>
              <div className='mt-6 flex flex-wrap gap-2'>
                {[
                  '3 PM order cutoff',
                  'Contract catalog live',
                  'Buyer portal active',
                  isLoading ? 'Refreshing data' : 'Data synced',
                ].map((label) => (
                  <span
                    key={label}
                    className='rounded-full border border-white/10 bg-white/5 px-3 py-1 text-xs font-semibold text-slate-200'
                  >
                    {label}
                  </span>
                ))}
              </div>
            </div>
            <div className='grid gap-3 sm:grid-cols-2 xl:grid-cols-1'>
              <div className='rounded-xl border border-white/10 bg-white/5 p-4'>
                <p className='text-xs uppercase tracking-[0.18em] text-slate-400'>
                  Current role
                </p>
                <p className='mt-2 text-lg font-semibold'>
                  {currentUser?.app_role?.name || 'Loading'}
                </p>
              </div>
              <div className='rounded-xl border border-white/10 bg-white/5 p-4'>
                <p className='text-xs uppercase tracking-[0.18em] text-slate-400'>
                  Active work areas
                </p>
                <p className='mt-2 text-lg font-semibold'>
                  {visibleEntities.length} modules available
                </p>
              </div>
            </div>
          </div>
        </section>

        <section className='mb-6 grid gap-4 sm:grid-cols-2 xl:grid-cols-6'>
          {kpiCards.map((card) => (
            <Link href={card.href} key={card.label}>
              <div className='h-full rounded-2xl border border-slate-200 bg-white p-4 shadow-sm transition hover:-translate-y-0.5 hover:border-emerald-200 hover:shadow-md'>
                <div className='flex items-start justify-between gap-3'>
                  <div>
                    <p className='text-xs font-semibold uppercase tracking-[0.16em] text-slate-400'>
                      {card.label}
                    </p>
                    <p className='mt-3 text-3xl font-semibold text-slate-950'>
                      {card.value}
                    </p>
                  </div>
                  <span className='inline-flex h-10 w-10 items-center justify-center rounded-xl bg-emerald-50 text-emerald-700'>
                    <BaseIcon path={card.icon} size='20' />
                  </span>
                </div>
                <p className='mt-3 text-sm leading-6 text-slate-500'>
                  {card.detail}
                </p>
              </div>
            </Link>
          ))}
        </section>

        <section className='mb-6 grid items-start gap-5 xl:grid-cols-[minmax(0,1.2fr)_minmax(360px,0.8fr)]'>
          <div className='rounded-2xl border border-slate-200 bg-white p-5 shadow-sm'>
            <div className='mb-4 flex items-start justify-between gap-3 border-b border-slate-100 pb-4'>
              <div>
                <p className='text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700'>
                  Fulfillment queue
                </p>
                <h3 className='mt-2 text-2xl font-semibold text-slate-950'>
                  Purchase orders requiring action
                </h3>
              </div>
              <Link
                href='/orders/orders-list'
                className='rounded-xl border border-slate-200 px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50'
              >
                All POs
              </Link>
            </div>
            <div className='space-y-3'>
              {openOrders.map((order) => (
                <Link
                  key={order.id}
                  href={`/orders/orders-view/?id=${order.id}`}
                  className='block rounded-xl border border-slate-200 bg-slate-50 p-4 transition hover:border-emerald-200 hover:bg-emerald-50/70'
                >
                  <div className='flex flex-wrap items-start justify-between gap-3'>
                    <div>
                      <p className='text-sm font-bold text-slate-950'>
                        {order.order_number}
                      </p>
                      <p className='mt-1 text-sm text-slate-600'>
                        {order.account?.account_name || 'Unassigned account'}
                      </p>
                    </div>
                    <StatusPill status={order.order_status} />
                  </div>
                  <div className='mt-4 grid gap-3 text-sm text-slate-600 sm:grid-cols-4'>
                    <div>
                      <p className='text-xs uppercase tracking-[0.14em] text-slate-400'>
                        PO
                      </p>
                      <p className='mt-1 font-semibold text-slate-900'>
                        {order.po_number || 'Pending'}
                      </p>
                    </div>
                    <div>
                      <p className='text-xs uppercase tracking-[0.14em] text-slate-400'>
                        Ship-to
                      </p>
                      <p className='mt-1 font-semibold text-slate-900'>
                        {order.location?.location_name || 'Not selected'}
                      </p>
                    </div>
                    <div>
                      <p className='text-xs uppercase tracking-[0.14em] text-slate-400'>
                        Requested
                      </p>
                      <p className='mt-1 font-semibold text-slate-900'>
                        {formatDate(order.requested_delivery_date)}
                      </p>
                    </div>
                    <div>
                      <p className='text-xs uppercase tracking-[0.14em] text-slate-400'>
                        Total
                      </p>
                      <p className='mt-1 font-semibold text-slate-900'>
                        {formatCurrency(order.order_total)}
                      </p>
                    </div>
                  </div>
                </Link>
              ))}
              {!openOrders.length && (
                <EmptyState text='No open purchase orders in the current view.' />
              )}
            </div>
          </div>

          <div className='grid gap-5'>
            <div className='rounded-2xl border border-slate-200 bg-white p-5 shadow-sm'>
              <div className='mb-4 flex items-start justify-between gap-3 border-b border-slate-100 pb-4'>
                <div>
                  <p className='text-xs font-semibold uppercase tracking-[0.2em] text-amber-700'>
                    Chef samples
                  </p>
                  <h3 className='mt-2 text-xl font-semibold text-slate-950'>
                    Sample requests
                  </h3>
                </div>
                <Link
                  href='/sample_requests/sample_requests-list'
                  className='text-sm font-semibold text-emerald-700'
                >
                  View all
                </Link>
              </div>
              <div className='space-y-3'>
                {activeSamples.map((sample) => (
                  <Link
                    href={`/sample_requests/sample_requests-view/?id=${sample.id}`}
                    key={sample.id}
                    className='block rounded-xl border border-slate-200 bg-slate-50 p-3 hover:border-amber-200 hover:bg-amber-50'
                  >
                    <div className='flex items-start justify-between gap-3'>
                      <div className='min-w-0'>
                        <p className='truncate text-sm font-bold text-slate-950'>
                          {sample.sample_request_number}
                        </p>
                        <p className='mt-1 truncate text-xs text-slate-500'>
                          {sample.product?.product_name || 'Product pending'}
                        </p>
                      </div>
                      <StatusPill status={sample.sample_status} />
                    </div>
                    <p className='mt-2 text-xs text-slate-500'>
                      {sample.account?.account_name || 'Unassigned'} · needed{' '}
                      {formatDate(sample.needed_by)}
                    </p>
                  </Link>
                ))}
                {!activeSamples.length && (
                  <EmptyState text='No active sample requests.' />
                )}
              </div>
            </div>

            <div className='rounded-2xl border border-slate-200 bg-white p-5 shadow-sm'>
              <div className='mb-4 flex items-start justify-between gap-3 border-b border-slate-100 pb-4'>
                <div>
                  <p className='text-xs font-semibold uppercase tracking-[0.2em] text-violet-700'>
                    Sales follow-up
                  </p>
                  <h3 className='mt-2 text-xl font-semibold text-slate-950'>
                    Quotes pending buyer action
                  </h3>
                </div>
                <Link
                  href='/quotes/quotes-list'
                  className='text-sm font-semibold text-emerald-700'
                >
                  View all
                </Link>
              </div>
              <div className='space-y-3'>
                {pendingQuotes.map((quote) => (
                  <Link
                    href={`/quotes/quotes-view/?id=${quote.id}`}
                    key={quote.id}
                    className='block rounded-xl border border-slate-200 bg-slate-50 p-3 hover:border-violet-200 hover:bg-violet-50'
                  >
                    <div className='flex items-start justify-between gap-3'>
                      <div className='min-w-0'>
                        <p className='truncate text-sm font-bold text-slate-950'>
                          {quote.quote_number}
                        </p>
                        <p className='mt-1 truncate text-xs text-slate-500'>
                          {quote.account?.account_name || 'Unassigned account'}
                        </p>
                      </div>
                      <StatusPill status={quote.quote_status} />
                    </div>
                    <p className='mt-2 text-xs text-slate-500'>
                      Expires {formatDate(quote.expires_at)} ·{' '}
                      {formatCurrency(quote.quote_total)} · owner{' '}
                      {formatUserName(quote.owner)}
                    </p>
                  </Link>
                ))}
                {!pendingQuotes.length && (
                  <EmptyState text='No quotes waiting for follow-up.' />
                )}
              </div>
            </div>
          </div>
        </section>

        <section className='mb-6 grid items-start gap-5 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]'>
          <div className='rounded-2xl border border-slate-200 bg-white p-5 shadow-sm'>
            <div className='mb-4 border-b border-slate-100 pb-4'>
              <p className='text-xs font-semibold uppercase tracking-[0.2em] text-blue-700'>
                Buyer accounts
              </p>
              <h3 className='mt-2 text-2xl font-semibold text-slate-950'>
                Priority commercial accounts
              </h3>
            </div>
            <div className='space-y-3'>
              {accounts.slice(0, 4).map((account) => {
                const activity = accountActivity.get(account.id);

                return (
                  <Link
                    href={`/accounts/accounts-view/?id=${account.id}`}
                    key={account.id}
                    className='block rounded-xl border border-slate-200 bg-slate-50 p-4 transition hover:border-blue-200 hover:bg-blue-50'
                  >
                    <div className='flex items-start justify-between gap-3'>
                      <div className='min-w-0'>
                        <p className='truncate font-bold text-slate-950'>
                          {account.account_name}
                        </p>
                        <p className='mt-1 text-xs font-semibold uppercase tracking-[0.14em] text-slate-400'>
                          {account.account_type || 'Buyer'} ·{' '}
                          {account.account_number || 'No number'}
                        </p>
                      </div>
                      <StatusPill status={account.credit_status} />
                    </div>
                    <div className='mt-3 grid gap-3 text-sm text-slate-600 sm:grid-cols-2'>
                      <p>
                        Rep:{' '}
                        <span className='font-semibold text-slate-900'>
                          {formatUserName(account.assigned_sales_rep)}
                        </span>
                      </p>
                      <p>
                        Open POs:{' '}
                        <span className='font-semibold text-slate-900'>
                          {activity?.openOrders || 0}
                        </span>
                      </p>
                      <p className='sm:col-span-2'>
                        Price file:{' '}
                        <span className='font-semibold text-slate-900'>
                          {account.default_price_list?.price_list_name ||
                            'Not assigned'}
                        </span>
                      </p>
                    </div>
                  </Link>
                );
              })}
              {!accounts.length && (
                <EmptyState text='No buyer accounts available for this role.' />
              )}
            </div>
          </div>

          <div className='rounded-2xl border border-slate-200 bg-white p-5 shadow-sm'>
            <div className='mb-4 flex items-start justify-between gap-3 border-b border-slate-100 pb-4'>
              <div>
                <p className='text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700'>
                  Catalog readiness
                </p>
                <h3 className='mt-2 text-2xl font-semibold text-slate-950'>
                  Product and inventory signals
                </h3>
              </div>
              <Link
                href='/products/products-list'
                className='rounded-xl border border-slate-200 px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50'
              >
                Catalog
              </Link>
            </div>
            <div className='grid gap-3 sm:grid-cols-3'>
              <div className='rounded-xl bg-emerald-50 p-4'>
                <p className='text-xs font-semibold uppercase tracking-[0.16em] text-emerald-700'>
                  Active SKUs
                </p>
                <p className='mt-2 text-2xl font-semibold text-slate-950'>
                  {activeProducts.length}
                </p>
              </div>
              <div className='rounded-xl bg-blue-50 p-4'>
                <p className='text-xs font-semibold uppercase tracking-[0.16em] text-blue-700'>
                  Sample-ready
                </p>
                <p className='mt-2 text-2xl font-semibold text-slate-950'>
                  {sampleReadyProducts.length}
                </p>
              </div>
              <div className='rounded-xl bg-amber-50 p-4'>
                <p className='text-xs font-semibold uppercase tracking-[0.16em] text-amber-700'>
                  Missing spec
                </p>
                <p className='mt-2 text-2xl font-semibold text-slate-950'>
                  {missingSpecProducts.length}
                </p>
              </div>
            </div>
            <div className='mt-4 grid gap-3 lg:grid-cols-2'>
              <div className='rounded-xl border border-slate-200 bg-slate-50 p-4'>
                <p className='text-sm font-bold text-slate-950'>
                  Temperature mix
                </p>
                <div className='mt-3 space-y-2 text-sm text-slate-600'>
                  {['ambient', 'refrigerated', 'frozen'].map((zone) => {
                    const value = activeProducts.filter(
                      (product) => product.temperature_zone === zone,
                    ).length;

                    return (
                      <div
                        key={zone}
                        className='flex items-center justify-between gap-3'
                      >
                        <span className='capitalize'>{zone}</span>
                        <span className='font-semibold text-slate-950'>
                          {value} SKU(s)
                        </span>
                      </div>
                    );
                  })}
                </div>
              </div>
              <div className='rounded-xl border border-slate-200 bg-slate-50 p-4'>
                <p className='text-sm font-bold text-slate-950'>
                  Stock watch
                </p>
                <div className='mt-3 space-y-2'>
                  {inventoryAlerts.map((item) => (
                    <div
                      key={item.id}
                      className='flex items-center justify-between gap-3 text-sm'
                    >
                      <span className='truncate text-slate-600'>
                        {item.product?.product_name || item.warehouse_name}
                      </span>
                      <span className='font-semibold text-slate-950'>
                        {item.available_cases || 0} cases
                      </span>
                    </div>
                  ))}
                  {!inventoryAlerts.length && (
                    <p className='text-sm text-slate-500'>
                      No low-stock rows in the current feed.
                    </p>
                  )}
                </div>
              </div>
            </div>
          </div>
        </section>

        <section className='grid gap-5 xl:grid-cols-2'>
          {Object.entries(groupCopy).map(([groupKey, copy]) => {
            const groupEntities = visibleEntities.filter(
              (entity) => entity.group === groupKey,
            );

            if (!groupEntities.length) {
              return null;
            }

            return (
              <div
                key={groupKey}
                className='rounded-2xl border border-slate-200 bg-white p-5 shadow-sm'
              >
                <div className='mb-4 border-b border-slate-100 pb-4'>
                  <p className='text-xs font-semibold uppercase tracking-[0.18em] text-emerald-700'>
                    {copy.title}
                  </p>
                  <p className='mt-2 text-sm leading-6 text-slate-500'>
                    {copy.subtitle}
                  </p>
                </div>
                <div className='grid gap-3 sm:grid-cols-2'>
                  {groupEntities.map((entity) => (
                    <Link href={entity.href} key={entity.key}>
                      <div className='flex h-full items-start gap-3 rounded-xl border border-slate-200 bg-slate-50 p-4 transition hover:border-emerald-200 hover:bg-emerald-50/70'>
                        <span className='mt-0.5 inline-flex h-9 w-9 flex-none items-center justify-center rounded-lg bg-white text-emerald-700 shadow-sm'>
                          <BaseIcon path={entity.icon} size='18' />
                        </span>
                        <div className='min-w-0'>
                          <div className='flex items-center gap-2'>
                            <p className='truncate font-semibold text-slate-950'>
                              {entity.label}
                            </p>
                            <span className='rounded-full bg-white px-2 py-0.5 text-xs font-semibold text-slate-500'>
                              {formatCount(counts[entity.key])}
                            </span>
                          </div>
                          <p className='mt-2 text-sm leading-6 text-slate-500'>
                            {entity.description}
                          </p>
                        </div>
                      </div>
                    </Link>
                  ))}
                </div>
              </div>
            );
          })}
        </section>
      </SectionMain>
    </>
  );
};

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

export default Dashboard;
