import {
  mdiAlertCircle,
  mdiBasketOutline,
  mdiClose,
  mdiFileDocumentOutline,
  mdiFilterVariant,
  mdiMagnify,
  mdiMinus,
  mdiPackageVariantClosed,
  mdiPlus,
  mdiTruckDelivery,
} from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement, useEffect, useMemo, useState } from 'react';
import axios from 'axios';

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

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

type Contact = {
  id: string;
  accountId: string;
  locationId?: string | null;
  contact_name: string;
  email?: string | null;
  phone?: string | null;
  role_title?: string | null;
  is_primary?: boolean;
  can_place_orders?: boolean;
  can_see_invoices?: boolean;
};

type Location = {
  id: string;
  accountId: string;
  location_name: string;
  location_type?: string | null;
  address_line_1?: string | null;
  address_line_2?: string | null;
  city?: string | null;
  state?: string | null;
  postal_code?: string | null;
  country?: string | null;
  delivery_instructions?: string | null;
  default_contact?: Contact | null;
};

type Account = {
  id: string;
  account_name: string;
  account_type?: string | null;
  account_number?: string | null;
  credit_status?: string | null;
  credit_limit?: number | null;
  notes?: string | null;
  default_price_list?: {
    id: string;
    price_list_name: string;
  } | null;
  assigned_sales_rep?: UserSummary | null;
  locations: Location[];
  contacts: Contact[];
};

type CatalogItem = {
  id: string;
  sku: string;
  product_name: string;
  brand?: string | null;
  short_description?: string | null;
  long_description?: string | null;
  pack_size?: string | null;
  units_per_case?: number | null;
  uom?: string | null;
  moq_cases?: number | null;
  temperature_zone?: string | null;
  product_status?: string | null;
  allergens?: string | null;
  certifications?: string | null;
  is_sample_eligible?: boolean;
  category?: {
    id: string;
    category_name: string;
  } | null;
  contract_case_price?: number | null;
  contract_min_case_qty?: number | null;
  contract_price_list?: string | null;
};

type LineProduct = {
  id: string;
  sku: string;
  product_name: string;
  brand?: string | null;
  pack_size?: string | null;
};

type OrderLine = {
  id: string;
  quantity_cases: number;
  case_price?: number | null;
  line_total?: number | null;
  fulfillment_status?: string | null;
  line_notes?: string | null;
  product?: LineProduct | null;
};

type OrderSummary = {
  id: string;
  order_number: string;
  po_number?: string | null;
  ordered_at?: string | null;
  requested_delivery_date?: string | null;
  promised_delivery_date?: string | null;
  order_status?: string | null;
  payment_terms?: string | null;
  order_total?: number | null;
  subtotal?: number | null;
  buyer_notes?: string | null;
  location?: Location | null;
  buyer?: UserSummary | null;
  items: OrderLine[];
};

type QuoteSummary = {
  id: string;
  quote_number: string;
  requested_at?: string | null;
  expires_at?: string | null;
  quote_status?: string | null;
  quote_total?: number | null;
  notes?: string | null;
  owner?: UserSummary | null;
  items: OrderLine[];
};

type SampleRequestSummary = {
  id: string;
  sample_request_number: string;
  sample_quantity?: number | null;
  requested_at?: string | null;
  needed_by?: string | null;
  sample_status?: string | null;
  notes?: string | null;
  product?: LineProduct | null;
  location?: Location | null;
  requested_by?: UserSummary | null;
};

type SavedListItem = {
  id: string;
  default_quantity_cases?: number | null;
  notes?: string | null;
  product?: LineProduct | null;
};

type SavedListSummary = {
  id: string;
  list_name: string;
  list_type?: string | null;
  notes?: string | null;
  createdAt?: string | null;
  updatedAt?: string | null;
  owner?: UserSummary | null;
  items: SavedListItem[];
};

type PortalData = {
  accounts: Account[];
  selectedAccountId: string;
  selectedLocationId: string;
  catalog: CatalogItem[];
  recentOrders: OrderSummary[];
  recentQuotes: QuoteSummary[];
  recentSamples: SampleRequestSummary[];
  savedLists: SavedListSummary[];
  roleContext?: {
    isBuyerAdmin?: boolean;
    isBuyerUser?: boolean;
  };
};

type DetailPanelState =
  | {
      type: 'order';
      item: OrderSummary;
    }
  | {
      type: 'quote';
      item: QuoteSummary;
    }
  | {
      type: 'sample';
      item: SampleRequestSummary;
    }
  | {
      type: 'savedList';
      item: SavedListSummary;
    };

type CartItem = {
  productId: string;
  sku: string;
  productName: string;
  packSize: string;
  quantityCases: number;
  casePrice: number;
  lineTotal: number;
  moqCases: number;
  temperatureZone?: string | null;
};

type BannerState = {
  tone: 'success' | 'danger';
  message: string;
};

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

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

const makeDateInput = (offsetDays = 0) => {
  const date = new Date();
  date.setDate(date.getDate() + offsetDays);
  return date.toISOString().slice(0, 10);
};

const splitTags = (value?: string | null) =>
  (value || '')
    .split(',')
    .map((item) => item.trim())
    .filter(Boolean);

const formatCurrency = (value?: number | null) => {
  if (value === null || value === undefined) {
    return 'Quote required';
  }

  return currencyFormatter.format(value);
};

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

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

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

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

const toTitle = (value?: string | null) =>
  (value || '')
    .replace(/_/g, ' ')
    .replace(/\b\w/g, (char) => char.toUpperCase()) || 'Unknown';

const statusClasses: Record<string, string> = {
  submitted: 'bg-blue-50 text-blue-700 border-blue-200',
  delivered: 'bg-emerald-50 text-emerald-700 border-emerald-200',
  approved: 'bg-emerald-50 text-emerald-700 border-emerald-200',
  shipped: 'bg-sky-50 text-sky-700 border-sky-200',
  picking: 'bg-violet-50 text-violet-700 border-violet-200',
  requested: 'bg-amber-50 text-amber-700 border-amber-200',
  sent: 'bg-blue-50 text-blue-700 border-blue-200',
  accepted: 'bg-emerald-50 text-emerald-700 border-emerald-200',
  in_review: 'bg-violet-50 text-violet-700 border-violet-200',
  approved_sample: 'bg-emerald-50 text-emerald-700 border-emerald-200',
  declined: 'bg-rose-50 text-rose-700 border-rose-200',
  cancelled: 'bg-rose-50 text-rose-700 border-rose-200',
  pending: 'bg-slate-100 text-slate-700 border-slate-200',
  allocated: 'bg-sky-50 text-sky-700 border-sky-200',
  backordered: 'bg-amber-50 text-amber-700 border-amber-200',
};

const fallbackProductImages = [
  'https://images.unsplash.com/photo-1452195100486-9cc805987862?auto=format&fit=crop&w=900&q=80',
  'https://images.unsplash.com/photo-1501443762994-82bd5dace89a?auto=format&fit=crop&w=900&q=80',
  'https://images.unsplash.com/photo-1544025162-d76694265947?auto=format&fit=crop&w=900&q=80',
  'https://images.unsplash.com/photo-1486297678162-eb2a19b0a32d?auto=format&fit=crop&w=900&q=80',
  'https://images.unsplash.com/photo-1512621776951-a57141f2eefd?auto=format&fit=crop&w=900&q=80',
  'https://images.unsplash.com/photo-1542838132-92c53300491e?auto=format&fit=crop&w=900&q=80',
];

const StatusPill = ({ label }: { label?: string | null }) => {
  const normalized = label || 'unknown';
  const colorClass =
    statusClasses[normalized] || 'bg-slate-100 text-slate-700 border-slate-200';

  return (
    <span
      className={`inline-flex rounded-full border px-2.5 py-1 text-xs font-semibold ${colorClass}`}
    >
      {toTitle(normalized)}
    </span>
  );
};

const DetailField = ({
  label,
  value,
}: {
  label: string;
  value?: React.ReactNode;
}) => {
  const displayValue =
    value === null || value === undefined || value === '' ? '—' : value;

  return (
    <div className='rounded-xl border border-slate-200 bg-slate-50 px-4 py-3'>
      <p className='text-xs font-semibold uppercase tracking-[0.14em] text-slate-400'>
        {label}
      </p>
      <div className='mt-1 text-sm font-semibold text-slate-900'>
        {displayValue}
      </div>
    </div>
  );
};

const DetailPanel = ({
  detail,
  onClose,
  onLoadOrder,
  onLoadSavedList,
}: {
  detail: DetailPanelState | null;
  onClose: () => void;
  onLoadOrder: (order: OrderSummary) => void;
  onLoadSavedList: (savedList: SavedListSummary) => void;
}) => {
  if (!detail) {
    return null;
  }

  const title =
    detail.type === 'order'
      ? detail.item.order_number
      : detail.type === 'quote'
        ? detail.item.quote_number
        : detail.type === 'sample'
          ? detail.item.sample_request_number
          : detail.item.list_name;

  const subtitle =
    detail.type === 'order'
      ? 'Purchase order detail'
      : detail.type === 'quote'
        ? 'Quote detail'
        : detail.type === 'sample'
          ? 'Sample request detail'
          : 'Saved order guide';

  return (
    <div className='fixed inset-0 z-50 bg-slate-950/40' onClick={onClose}>
      <div
        className='ml-auto flex h-full w-full max-w-2xl flex-col bg-white shadow-2xl'
        onClick={(event) => event.stopPropagation()}
      >
        <div className='flex items-start justify-between gap-4 border-b border-slate-200 px-6 py-5'>
          <div>
            <p className='text-xs font-semibold uppercase tracking-[0.18em] text-blue-600'>
              {subtitle}
            </p>
            <h2 className='mt-2 text-2xl font-semibold text-slate-950'>
              {title}
            </h2>
          </div>
          <BaseButton
            color='white'
            icon={mdiClose}
            label='Close'
            outline
            onClick={onClose}
          />
        </div>

        <div className='flex-1 overflow-y-auto px-6 py-6'>
          {detail.type === 'order' && (
            <div className='space-y-6'>
              <div className='grid gap-3 sm:grid-cols-2'>
                <DetailField
                  label='Status'
                  value={<StatusPill label={detail.item.order_status} />}
                />
                <DetailField
                  label='Total'
                  value={formatCurrency(detail.item.order_total)}
                />
                <DetailField label='PO number' value={detail.item.po_number} />
                <DetailField
                  label='Buyer'
                  value={formatUserName(detail.item.buyer)}
                />
                <DetailField
                  label='Ship-to'
                  value={detail.item.location?.location_name}
                />
                <DetailField
                  label='Requested delivery'
                  value={formatDate(detail.item.requested_delivery_date)}
                />
                <DetailField
                  label='Promised delivery'
                  value={formatDate(detail.item.promised_delivery_date)}
                />
                <DetailField
                  label='Payment terms'
                  value={toTitle(detail.item.payment_terms)}
                />
              </div>

              <div>
                <p className='text-sm font-semibold text-slate-900'>
                  Order notes
                </p>
                <p className='mt-2 rounded-xl border border-slate-200 bg-slate-50 p-4 text-sm leading-6 text-slate-600'>
                  {detail.item.buyer_notes || 'No buyer notes on this order.'}
                </p>
              </div>

              <div>
                <div className='mb-3 flex items-center justify-between'>
                  <p className='text-sm font-semibold text-slate-900'>
                    Line items
                  </p>
                  <BaseButton
                    color='info'
                    small
                    outline
                    label='Load into draft'
                    onClick={() => onLoadOrder(detail.item)}
                  />
                </div>
                <div className='space-y-3'>
                  {detail.item.items.map((line) => (
                    <div
                      key={line.id}
                      className='rounded-xl border border-slate-200 p-4'
                    >
                      <div className='flex items-start justify-between gap-3'>
                        <div>
                          <p className='font-semibold text-slate-900'>
                            {line.product?.product_name || 'Unknown product'}
                          </p>
                          <p className='mt-1 text-xs uppercase tracking-[0.14em] text-slate-400'>
                            {line.product?.sku}
                          </p>
                        </div>
                        <StatusPill label={line.fulfillment_status} />
                      </div>
                      <div className='mt-3 grid gap-2 text-sm text-slate-600 sm:grid-cols-3'>
                        <span>{line.quantity_cases} case(s)</span>
                        <span>{formatCurrency(line.case_price)} / case</span>
                        <span className='font-semibold text-slate-900'>
                          {formatCurrency(line.line_total)}
                        </span>
                      </div>
                      {line.line_notes && (
                        <p className='mt-3 text-sm text-slate-500'>
                          {line.line_notes}
                        </p>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}

          {detail.type === 'quote' && (
            <div className='space-y-6'>
              <div className='grid gap-3 sm:grid-cols-2'>
                <DetailField
                  label='Status'
                  value={<StatusPill label={detail.item.quote_status} />}
                />
                <DetailField
                  label='Quote total'
                  value={formatCurrency(detail.item.quote_total)}
                />
                <DetailField
                  label='Requested'
                  value={formatDate(detail.item.requested_at)}
                />
                <DetailField
                  label='Expires'
                  value={formatDate(detail.item.expires_at)}
                />
                <DetailField
                  label='Owner'
                  value={formatUserName(detail.item.owner)}
                />
              </div>

              <div>
                <p className='text-sm font-semibold text-slate-900'>
                  Commercial notes
                </p>
                <p className='mt-2 rounded-xl border border-slate-200 bg-slate-50 p-4 text-sm leading-6 text-slate-600'>
                  {detail.item.notes || 'No notes on this quote.'}
                </p>
              </div>

              <div className='space-y-3'>
                {detail.item.items.map((line) => (
                  <div
                    key={line.id}
                    className='rounded-xl border border-slate-200 p-4'
                  >
                    <p className='font-semibold text-slate-900'>
                      {line.product?.product_name || 'Unknown product'}
                    </p>
                    <p className='mt-1 text-xs uppercase tracking-[0.14em] text-slate-400'>
                      {line.product?.sku}
                    </p>
                    <div className='mt-3 grid gap-2 text-sm text-slate-600 sm:grid-cols-3'>
                      <span>{line.quantity_cases} case(s)</span>
                      <span>{formatCurrency(line.case_price)} / case</span>
                      <span className='font-semibold text-slate-900'>
                        {formatCurrency(line.line_total)}
                      </span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {detail.type === 'sample' && (
            <div className='space-y-6'>
              <div className='grid gap-3 sm:grid-cols-2'>
                <DetailField
                  label='Status'
                  value={<StatusPill label={detail.item.sample_status} />}
                />
                <DetailField
                  label='Requested by'
                  value={formatUserName(detail.item.requested_by)}
                />
                <DetailField
                  label='Product'
                  value={detail.item.product?.product_name}
                />
                <DetailField
                  label='Ship-to'
                  value={detail.item.location?.location_name}
                />
                <DetailField
                  label='Needed by'
                  value={formatDate(detail.item.needed_by)}
                />
                <DetailField
                  label='Quantity'
                  value={`${detail.item.sample_quantity || 0} sample case(s)`}
                />
              </div>

              <div>
                <p className='text-sm font-semibold text-slate-900'>
                  Sample notes
                </p>
                <p className='mt-2 rounded-xl border border-slate-200 bg-slate-50 p-4 text-sm leading-6 text-slate-600'>
                  {detail.item.notes || 'No notes on this sample request.'}
                </p>
              </div>
            </div>
          )}

          {detail.type === 'savedList' && (
            <div className='space-y-6'>
              <div className='grid gap-3 sm:grid-cols-2'>
                <DetailField
                  label='Owner'
                  value={formatUserName(detail.item.owner)}
                />
                <DetailField
                  label='List type'
                  value={toTitle(detail.item.list_type)}
                />
                <DetailField
                  label='Updated'
                  value={formatDate(detail.item.updatedAt)}
                />
                <DetailField label='Items' value={detail.item.items.length} />
              </div>

              <BaseButton
                color='info'
                label='Load guide into draft'
                onClick={() => onLoadSavedList(detail.item)}
              />

              <div>
                <p className='text-sm font-semibold text-slate-900'>
                  Order guide notes
                </p>
                <p className='mt-2 rounded-xl border border-slate-200 bg-slate-50 p-4 text-sm leading-6 text-slate-600'>
                  {detail.item.notes || 'No notes on this saved list.'}
                </p>
              </div>

              <div className='space-y-3'>
                {detail.item.items.map((line) => (
                  <div
                    key={line.id}
                    className='rounded-xl border border-slate-200 p-4'
                  >
                    <p className='font-semibold text-slate-900'>
                      {line.product?.product_name || 'Unknown product'}
                    </p>
                    <p className='mt-1 text-xs uppercase tracking-[0.14em] text-slate-400'>
                      {line.product?.sku}
                    </p>
                    <div className='mt-3 flex flex-wrap gap-3 text-sm text-slate-600'>
                      <span>
                        Default qty: {line.default_quantity_cases || 0} case(s)
                      </span>
                      {line.product?.pack_size && (
                        <span>Pack: {line.product.pack_size}</span>
                      )}
                    </div>
                    {line.notes && (
                      <p className='mt-3 text-sm text-slate-500'>
                        {line.notes}
                      </p>
                    )}
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

const BuyerPortalPage = () => {
  const { currentUser } = useAppSelector((state) => state.auth);
  const [workspace, setWorkspace] = useState<PortalData | null>(null);
  const [selectedAccountId, setSelectedAccountId] = useState('');
  const [selectedLocationId, setSelectedLocationId] = useState('');
  const [searchQuery, setSearchQuery] = useState('');
  const [catalogMode, setCatalogMode] = useState('order_guide');
  const [categoryFilter, setCategoryFilter] = useState('all');
  const [temperatureFilter, setTemperatureFilter] = useState('all');
  const [stockFilter, setStockFilter] = useState('orderable');
  const [catalogQuantities, setCatalogQuantities] = useState<
    Record<string, string>
  >({});
  const [cartItems, setCartItems] = useState<CartItem[]>([]);
  const [poNumber, setPoNumber] = useState('');
  const [requestedDeliveryDate, setRequestedDeliveryDate] = useState(
    makeDateInput(4),
  );
  const [paymentTerms, setPaymentTerms] = useState('net_30');
  const [buyerNotes, setBuyerNotes] = useState('');
  const [sampleProductId, setSampleProductId] = useState('');
  const [sampleQuantity, setSampleQuantity] = useState('1');
  const [sampleNeededBy, setSampleNeededBy] = useState(makeDateInput(7));
  const [sampleNotes, setSampleNotes] = useState('');
  const [banner, setBanner] = useState<BannerState | null>(null);
  const [errorMessage, setErrorMessage] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isSubmittingOrder, setIsSubmittingOrder] = useState(false);
  const [isSubmittingSample, setIsSubmittingSample] = useState(false);
  const [createdOrder, setCreatedOrder] = useState<OrderSummary | null>(null);
  const [detailPanel, setDetailPanel] = useState<DetailPanelState | null>(null);

  const canCreateOrders =
    !!currentUser &&
    hasPermission(currentUser, 'CREATE_ORDERS') &&
    hasPermission(currentUser, 'CREATE_ORDER_ITEMS');
  const canCreateSamples =
    !!currentUser && hasPermission(currentUser, 'CREATE_SAMPLE_REQUESTS');
  const canReadBuyerTeamQueue =
    !!currentUser && hasPermission(currentUser, 'READ_BUYER_TEAM_QUEUE');

  const loadWorkspace = async (accountId?: string, locationId?: string) => {
    try {
      setIsLoading(true);
      setErrorMessage('');

      const { data } = await axios.get('/buyer_portal/workspace', {
        params: {
          accountId: accountId || undefined,
          locationId: locationId || undefined,
        },
      });

      const nextAccountId =
        data.selectedAccountId || accountId || data.accounts?.[0]?.id || '';
      const nextAccount =
        data.accounts?.find((account: Account) => account.id === nextAccountId) ||
        data.accounts?.[0];
      const nextLocationId =
        data.selectedLocationId ||
        locationId ||
        nextAccount?.locations?.[0]?.id ||
        '';

      setWorkspace(data);
      setSelectedAccountId(nextAccountId);
      setSelectedLocationId(nextLocationId);
    } catch (error: any) {
      console.error('Failed to load buyer portal workspace', error);
      setErrorMessage(
        error?.response?.data || 'Unable to load the buyer portal right now.',
      );
    } finally {
      setIsLoading(false);
    }
  };

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

    loadWorkspace();
  }, [currentUser]);

  const scrollToSection = (sectionId: string) => {
    if (typeof window !== 'undefined') {
      document.getElementById(sectionId)?.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
      });
    }
  };

  const currentAccount = useMemo(
    () =>
      workspace?.accounts.find((account) => account.id === selectedAccountId) ||
      null,
    [workspace, selectedAccountId],
  );

  const currentLocation = useMemo(
    () =>
      currentAccount?.locations.find(
        (location) => location.id === selectedLocationId,
      ) || null,
    [currentAccount, selectedLocationId],
  );

  const categoryOptions = useMemo(() => {
    const categories = new Set<string>();
    (workspace?.catalog || []).forEach((product) => {
      if (product.category?.category_name) {
        categories.add(product.category.category_name);
      }
    });

    return Array.from(categories).sort();
  }, [workspace]);

  const temperatureOptions = useMemo(() => {
    const zones = new Set<string>();
    (workspace?.catalog || []).forEach((product) => {
      if (product.temperature_zone) {
        zones.add(product.temperature_zone);
      }
    });

    return Array.from(zones).sort();
  }, [workspace]);

  const previouslyPurchasedProductIds = useMemo(() => {
    const ids = new Set<string>();
    (workspace?.recentOrders || []).forEach((order) => {
      order.items.forEach((line) => {
        if (line.product?.id) {
          ids.add(line.product.id);
        }
      });
    });

    return ids;
  }, [workspace]);

  const filteredCatalog = useMemo(() => {
    const source = workspace?.catalog || [];
    const normalizedQuery = searchQuery.trim().toLowerCase();

    return source.filter((product) => {
      if (
        catalogMode === 'previously_purchased' &&
        !previouslyPurchasedProductIds.has(product.id)
      ) {
        return false;
      }

      if (
        categoryFilter !== 'all' &&
        product.category?.category_name !== categoryFilter
      ) {
        return false;
      }

      if (
        temperatureFilter !== 'all' &&
        product.temperature_zone !== temperatureFilter
      ) {
        return false;
      }

      if (
        stockFilter === 'orderable' &&
        product.product_status === 'out_of_stock'
      ) {
        return false;
      }

      if (stockFilter === 'sample_eligible' && !product.is_sample_eligible) {
        return false;
      }

      if (!normalizedQuery) {
        return true;
      }

      const haystack = [
        product.product_name,
        product.sku,
        product.brand,
        product.short_description,
        product.category?.category_name,
        product.allergens,
        product.certifications,
      ]
        .filter(Boolean)
        .join(' ')
        .toLowerCase();

      return haystack.includes(normalizedQuery);
    });
  }, [
    catalogMode,
    categoryFilter,
    previouslyPurchasedProductIds,
    searchQuery,
    stockFilter,
    temperatureFilter,
    workspace,
  ]);

  const selectedSampleProduct = useMemo(
    () =>
      workspace?.catalog.find((product) => product.id === sampleProductId) ||
      null,
    [sampleProductId, workspace],
  );

  const draftTotal = useMemo(
    () => cartItems.reduce((sum, item) => sum + item.lineTotal, 0),
    [cartItems],
  );

  const totalDraftCases = useMemo(
    () => cartItems.reduce((sum, item) => sum + item.quantityCases, 0),
    [cartItems],
  );

  const draftWarnings = useMemo(() => {
    const warnings: string[] = [];

    if (!selectedLocationId) {
      warnings.push('Choose a delivery location.');
    }

    if (!poNumber.trim()) {
      warnings.push('PO number is required before checkout.');
    }

    if (!cartItems.length) {
      warnings.push('Add at least one product to the draft.');
    }

    cartItems.forEach((item) => {
      if (item.quantityCases < item.moqCases) {
        warnings.push(
          `${item.productName} is below its ${item.moqCases}-case MOQ.`,
        );
      }
    });

    return warnings;
  }, [cartItems, poNumber, selectedLocationId]);

  const suggestedItems = useMemo(() => {
    const inDraft = new Set(cartItems.map((item) => item.productId));
    return (workspace?.catalog || [])
      .filter(
        (product) =>
          product.contract_case_price &&
          product.product_status !== 'out_of_stock',
      )
      .filter((product) => !inDraft.has(product.id))
      .slice(0, 3);
  }, [cartItems, workspace]);

  const orderQueue = useMemo(
    () =>
      (workspace?.recentOrders || []).filter(
        (order) =>
          !['delivered', 'cancelled'].includes(order.order_status || ''),
      ),
    [workspace],
  );

  const quoteQueue = useMemo(
    () =>
      (workspace?.recentQuotes || []).filter(
        (quote) =>
          !['accepted', 'declined', 'expired'].includes(
            quote.quote_status || '',
          ),
      ),
    [workspace],
  );

  const sampleQueue = useMemo(
    () =>
      (workspace?.recentSamples || []).filter(
        (sample) =>
          !['declined', 'cancelled'].includes(sample.sample_status || ''),
      ),
    [workspace],
  );

  const getLastOrderedLabel = (productId: string) => {
    const matchingOrder = (workspace?.recentOrders || []).find((order) =>
      order.items.some((line) => line.product?.id === productId),
    );

    if (!matchingOrder) {
      return 'Not ordered yet';
    }

    return `Last ordered ${formatDate(matchingOrder.ordered_at)}`;
  };

  const handleAccountChange = async (accountId: string) => {
    setSelectedAccountId(accountId);
    setSelectedLocationId('');
    setCartItems([]);
    setCreatedOrder(null);
    setSampleProductId('');
    setBanner({
      tone: 'success',
      message:
        'Buyer context updated. Draft order reset for the selected account.',
    });
    await loadWorkspace(accountId, '');
  };

  const handleLocationChange = async (locationId: string) => {
    setSelectedLocationId(locationId);
    await loadWorkspace(selectedAccountId, locationId);
  };

  const addProductToDraft = (product: CatalogItem) => {
    const minQty = product.contract_min_case_qty || product.moq_cases || 1;
    const requestedQty = Number.parseInt(
      catalogQuantities[product.id] || String(minQty),
      10,
    );

    if (!Number.isInteger(requestedQty) || requestedQty < minQty) {
      setBanner({
        tone: 'danger',
        message: `${product.product_name} requires at least ${minQty} case(s).`,
      });
      return;
    }

    if (product.product_status === 'out_of_stock') {
      setBanner({
        tone: 'danger',
        message: `${product.product_name} is currently out of stock and cannot be added to the order.`,
      });
      return;
    }

    if (!product.contract_case_price) {
      setBanner({
        tone: 'danger',
        message: `${product.product_name} does not have active contract pricing.`,
      });
      return;
    }

    setCartItems((currentItems) => {
      const existingItem = currentItems.find(
        (item) => item.productId === product.id,
      );
      if (existingItem) {
        return currentItems.map((item) =>
          item.productId === product.id
            ? {
                ...item,
                quantityCases: item.quantityCases + requestedQty,
                lineTotal: (item.quantityCases + requestedQty) * item.casePrice,
              }
            : item,
        );
      }

      return [
        ...currentItems,
        {
          productId: product.id,
          sku: product.sku,
          productName: product.product_name,
          packSize: product.pack_size || 'Case pack',
          quantityCases: requestedQty,
          casePrice: product.contract_case_price,
          lineTotal: product.contract_case_price * requestedQty,
          moqCases: minQty,
          temperatureZone: product.temperature_zone,
        },
      ];
    });

    setCreatedOrder(null);
    setBanner({
      tone: 'success',
      message: `${product.product_name} added to the draft PO at contract pricing.`,
    });
  };

  const updateDraftQuantity = (productId: string, nextValue: string) => {
    const parsed = Number.parseInt(nextValue, 10);

    if (!Number.isInteger(parsed) || parsed <= 0) {
      return;
    }

    setCartItems((currentItems) =>
      currentItems.map((item) =>
        item.productId === productId
          ? {
              ...item,
              quantityCases: parsed,
              lineTotal: parsed * item.casePrice,
            }
          : item,
      ),
    );
  };

  const removeDraftItem = (productId: string) => {
    setCartItems((currentItems) =>
      currentItems.filter((item) => item.productId !== productId),
    );
  };

  const loadOrderIntoDraft = (order: OrderSummary) => {
    const catalogById = new Map(
      (workspace?.catalog || []).map((item) => [item.id, item]),
    );
    const nextDraft: CartItem[] = [];
    let skippedItems = 0;

    order.items.forEach((line) => {
      if (!line.product?.id) {
        skippedItems += 1;
        return;
      }

      const currentCatalogItem = catalogById.get(line.product.id);
      if (!currentCatalogItem?.contract_case_price) {
        skippedItems += 1;
        return;
      }

      nextDraft.push({
        productId: line.product.id,
        sku: line.product.sku,
        productName: line.product.product_name,
        packSize: line.product.pack_size || 'Case pack',
        quantityCases: line.quantity_cases,
        casePrice: currentCatalogItem.contract_case_price,
        lineTotal: currentCatalogItem.contract_case_price * line.quantity_cases,
        moqCases:
          currentCatalogItem.contract_min_case_qty ||
          currentCatalogItem.moq_cases ||
          1,
        temperatureZone: currentCatalogItem.temperature_zone,
      });
    });

    setCartItems(nextDraft);
    setPoNumber('');
    setBuyerNotes(`Reorder based on ${order.order_number}`);
    setRequestedDeliveryDate(makeDateInput(4));
    setCreatedOrder(null);
    setBanner({
      tone: skippedItems ? 'danger' : 'success',
      message: skippedItems
        ? `${order.order_number} loaded with ${skippedItems} unavailable item(s) skipped.`
        : `${order.order_number} loaded into the draft PO with current contract pricing.`,
    });

    scrollToSection('purchase-order');
  };

  const loadSavedListIntoDraft = (savedList: SavedListSummary) => {
    const catalogById = new Map(
      (workspace?.catalog || []).map((item) => [item.id, item]),
    );
    const nextDraft: CartItem[] = [];
    let skippedItems = 0;

    savedList.items.forEach((line) => {
      if (!line.product?.id) {
        skippedItems += 1;
        return;
      }

      const currentCatalogItem = catalogById.get(line.product.id);
      if (!currentCatalogItem?.contract_case_price) {
        skippedItems += 1;
        return;
      }

      const minQty =
        currentCatalogItem.contract_min_case_qty ||
        currentCatalogItem.moq_cases ||
        1;
      const quantityCases = line.default_quantity_cases || minQty;

      nextDraft.push({
        productId: line.product.id,
        sku: line.product.sku,
        productName: line.product.product_name,
        packSize:
          line.product.pack_size ||
          currentCatalogItem.pack_size ||
          'Case pack',
        quantityCases,
        casePrice: currentCatalogItem.contract_case_price,
        lineTotal: currentCatalogItem.contract_case_price * quantityCases,
        moqCases: minQty,
        temperatureZone: currentCatalogItem.temperature_zone,
      });
    });

    setCartItems(nextDraft);
    setPoNumber('');
    setBuyerNotes(`Draft based on saved order guide: ${savedList.list_name}`);
    setRequestedDeliveryDate(makeDateInput(4));
    setCreatedOrder(null);
    setBanner({
      tone: skippedItems ? 'danger' : 'success',
      message: skippedItems
        ? `${savedList.list_name} loaded with ${skippedItems} unavailable item(s) skipped.`
        : `${savedList.list_name} loaded into the draft PO at current contract pricing.`,
    });
    scrollToSection('purchase-order');
  };

  const submitDraftOrder = async () => {
    if (!selectedAccountId || !selectedLocationId) {
      setBanner({
        tone: 'danger',
        message: 'Choose both an account and a delivery location first.',
      });
      return;
    }

    if (!cartItems.length) {
      setBanner({
        tone: 'danger',
        message: 'Add at least one product before submitting the PO.',
      });
      return;
    }

    if (!poNumber.trim()) {
      setBanner({
        tone: 'danger',
        message: 'Enter a PO number before submitting the order.',
      });
      return;
    }

    try {
      setIsSubmittingOrder(true);
      const { data } = await axios.post('/buyer_portal/orders', {
        accountId: selectedAccountId,
        locationId: selectedLocationId,
        poNumber,
        requestedDeliveryDate,
        paymentTerms,
        buyerNotes,
        items: cartItems.map((item) => ({
          productId: item.productId,
          quantityCases: item.quantityCases,
        })),
      });

      setCreatedOrder(data.order);
      setCartItems([]);
      setPoNumber('');
      setBuyerNotes('');
      setRequestedDeliveryDate(makeDateInput(4));
      setBanner({
        tone: 'success',
        message: `PO ${data.order.po_number} has been submitted and added to order history.`,
      });

      await loadWorkspace(selectedAccountId, selectedLocationId);
    } catch (error: any) {
      console.error('Failed to submit draft order', error);
      setBanner({
        tone: 'danger',
        message:
          error?.response?.data ||
          'Unable to place the purchase order right now.',
      });
    } finally {
      setIsSubmittingOrder(false);
    }
  };

  const submitSampleRequest = async () => {
    const quantity = Number.parseInt(sampleQuantity, 10);

    if (!selectedAccountId || !selectedLocationId || !selectedSampleProduct) {
      setBanner({
        tone: 'danger',
        message:
          'Choose an account, location, and sample-eligible product before sending the request.',
      });
      return;
    }

    if (!Number.isInteger(quantity) || quantity <= 0) {
      setBanner({ tone: 'danger', message: 'Enter a valid sample quantity.' });
      return;
    }

    try {
      setIsSubmittingSample(true);
      await axios.post('/buyer_portal/sample-requests', {
        accountId: selectedAccountId,
        locationId: selectedLocationId,
        productId: selectedSampleProduct.id,
        sampleQuantity: quantity,
        neededBy: sampleNeededBy,
        notes: sampleNotes,
      });

      setSampleQuantity('1');
      setSampleNeededBy(makeDateInput(7));
      setSampleNotes('');
      setSampleProductId('');
      setBanner({
        tone: 'success',
        message: `${selectedSampleProduct.product_name} sample request has been sent to your distributor team.`,
      });

      await loadWorkspace(selectedAccountId, selectedLocationId);
    } catch (error: any) {
      console.error('Failed to create sample request', error);
      setBanner({
        tone: 'danger',
        message:
          error?.response?.data ||
          'Unable to create the sample request right now.',
      });
    } finally {
      setIsSubmittingSample(false);
    }
  };

  const sampleEligibleCount = useMemo(
    () =>
      (workspace?.catalog || []).filter((item) => item.is_sample_eligible)
        .length,
    [workspace],
  );

  const draftReady = cartItems.length > 0 && draftWarnings.length === 0;
  const procurementSteps = [
    {
      label: 'Account + ship-to',
      value:
        currentAccount && currentLocation
          ? `${currentAccount.account_name} / ${currentLocation.location_name}`
          : 'Choose account and location',
      ready: Boolean(selectedAccountId && selectedLocationId),
      sectionId: 'buyer-context',
    },
    {
      label: 'Contract catalog',
      value: `${filteredCatalog.length} SKU(s) visible`,
      ready: filteredCatalog.length > 0,
      sectionId: 'catalog',
    },
    {
      label: 'Draft PO',
      value: `${cartItems.length} line(s) / ${totalDraftCases} case(s)`,
      ready: draftReady,
      sectionId: 'purchase-order',
    },
    {
      label: 'Submit order',
      value: createdOrder
        ? createdOrder.order_number
        : canCreateOrders
          ? 'Ready after review'
          : 'Buyer admin submits',
      ready: Boolean(createdOrder),
      sectionId: 'purchase-order',
    },
    {
      label: 'Reorder history',
      value: `${workspace?.recentOrders.length || 0} order(s) on file`,
      ready: Boolean(workspace?.recentOrders.length),
      sectionId: 'orders',
    },
  ];

  if (!currentUser) {
    return (
      <>
        <Head>
          <title>{getPageTitle('Buyer workspace')}</title>
        </Head>
        <SectionMain>
          <CardBox className='border border-slate-200 bg-white p-8 text-center shadow-sm'>
            <p className='text-xs font-semibold uppercase tracking-[0.22em] text-emerald-700'>
              Buyer workspace
            </p>
            <h1 className='mt-3 text-3xl font-semibold text-slate-950'>
              Loading account permissions
            </h1>
            <p className='mx-auto mt-3 max-w-xl text-sm leading-7 text-slate-600'>
              The standard SaaS admin shell is checking your role before opening
              contract pricing, purchase orders, and sample requests.
            </p>
          </CardBox>
        </SectionMain>
      </>
    );
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('Buyer portal')}</title>
      </Head>
      <SectionMain>
        <CardBox
          id='buyer-context'
          className='mb-6 scroll-mt-24 border border-slate-200 bg-white shadow-sm'
        >
          <div className='mb-5 flex flex-col gap-3 border-b border-slate-100 pb-5 lg:flex-row lg:items-center lg:justify-between'>
            <div>
              <p className='text-xs font-semibold uppercase tracking-[0.2em] text-blue-600'>
                Order guide workspace
              </p>
              <h1 className='mt-2 text-3xl font-semibold text-slate-950'>
                Contract-priced replenishment for foodservice buyers
              </h1>
              <p className='mt-2 max-w-3xl text-sm text-slate-500'>
                Pick the account, ship-to, delivery date, and PO once. Then work
                the order guide like a procurement screen.
              </p>
            </div>
            <div className='grid gap-2 rounded-2xl border border-slate-200 bg-slate-50 p-3 text-sm text-slate-600 sm:grid-cols-3'>
              <div>
                <p className='text-xs uppercase tracking-[0.14em] text-slate-400'>
                  Price file
                </p>
                <p className='mt-1 font-semibold text-slate-900'>
                  {currentAccount?.default_price_list?.price_list_name ||
                    'Loading pricing'}
                </p>
              </div>
              <div>
                <p className='text-xs uppercase tracking-[0.14em] text-slate-400'>
                  Sales rep
                </p>
                <p className='mt-1 font-semibold text-slate-900'>
                  {formatUserName(currentAccount?.assigned_sales_rep)}
                </p>
              </div>
              <div>
                <p className='text-xs uppercase tracking-[0.14em] text-slate-400'>
                  Cutoff
                </p>
                <p className='mt-1 font-semibold text-slate-900'>
                  Today 3:00 PM
                </p>
              </div>
            </div>
          </div>

          <div className='grid gap-4 xl:grid-cols-[1fr_1fr_170px_150px]'>
            <FormField label='Account'>
              <select
                value={selectedAccountId}
                onChange={(event) => handleAccountChange(event.target.value)}
              >
                {(workspace?.accounts || []).map((account) => (
                  <option key={account.id} value={account.id}>
                    {account.account_name}
                  </option>
                ))}
              </select>
            </FormField>
            <FormField label='Delivery location'>
              <select
                value={selectedLocationId}
                onChange={(event) => handleLocationChange(event.target.value)}
              >
                {(currentAccount?.locations || []).map((location) => (
                  <option key={location.id} value={location.id}>
                    {location.location_name}
                  </option>
                ))}
              </select>
            </FormField>
            <FormField label='Delivery date'>
              <input
                type='date'
                value={requestedDeliveryDate}
                onChange={(event) =>
                  setRequestedDeliveryDate(event.target.value)
                }
              />
            </FormField>
            <FormField label='PO number'>
              <input
                value={poNumber}
                onChange={(event) => setPoNumber(event.target.value)}
                placeholder='HT-PO-4901'
              />
            </FormField>
          </div>

          <div className='mt-5 grid gap-3 lg:grid-cols-5'>
            {procurementSteps.map((step, index) => (
              <button
                type='button'
                key={step.label}
                onClick={() => scrollToSection(step.sectionId)}
                className={`rounded-2xl border p-4 text-left transition hover:-translate-y-0.5 hover:shadow-sm ${
                  step.ready
                    ? 'border-emerald-200 bg-emerald-50'
                    : 'border-slate-200 bg-slate-50'
                }`}
              >
                <div className='flex items-center gap-3'>
                  <span
                    className={`flex h-8 w-8 items-center justify-center rounded-full text-sm font-bold ${
                      step.ready
                        ? 'bg-emerald-600 text-white'
                        : 'bg-slate-300 text-slate-700'
                    }`}
                  >
                    {index + 1}
                  </span>
                  <div className='min-w-0'>
                    <p className='text-xs font-semibold uppercase tracking-[0.16em] text-slate-500'>
                      {step.label}
                    </p>
                    <p className='mt-1 text-sm font-semibold leading-5 text-slate-950'>
                      {step.value}
                    </p>
                  </div>
                </div>
              </button>
            ))}
          </div>

          <div className='mt-4 flex flex-wrap gap-2'>
            <button
              type='button'
              onClick={() => scrollToSection('catalog')}
              className='rounded-full border border-blue-200 bg-blue-50 px-4 py-2 text-sm font-semibold text-blue-700 transition hover:border-blue-400 hover:bg-blue-100'
            >
              Browse contract catalog
            </button>
            {canReadBuyerTeamQueue && Boolean(workspace?.savedLists.length) && (
              <button
                type='button'
                onClick={() => scrollToSection('saved-guides')}
                className='rounded-full border border-emerald-200 bg-emerald-50 px-4 py-2 text-sm font-semibold text-emerald-700 transition hover:border-emerald-400 hover:bg-emerald-100'
              >
                Use saved order guide
              </button>
            )}
            <button
              type='button'
              onClick={() => scrollToSection('purchase-order')}
              className='rounded-full border border-slate-200 bg-white px-4 py-2 text-sm font-semibold text-slate-700 transition hover:border-slate-400 hover:bg-slate-50'
            >
              Review draft PO
            </button>
            <button
              type='button'
              onClick={() => scrollToSection('orders')}
              className='rounded-full border border-amber-200 bg-amber-50 px-4 py-2 text-sm font-semibold text-amber-800 transition hover:border-amber-400 hover:bg-amber-100'
            >
              Reorder from history
            </button>
          </div>

          <div className='mt-5 grid gap-3 text-sm sm:grid-cols-2 lg:grid-cols-4'>
            <div className='rounded-2xl bg-blue-50 p-4'>
              <p className='text-xs uppercase tracking-[0.16em] text-blue-700'>
                Contract SKUs
              </p>
              <p className='mt-2 text-2xl font-semibold text-slate-950'>
                {workspace?.catalog.length || 0}
              </p>
            </div>
            <div className='rounded-2xl bg-emerald-50 p-4'>
              <p className='text-xs uppercase tracking-[0.16em] text-emerald-700'>
                Sample-ready
              </p>
              <p className='mt-2 text-2xl font-semibold text-slate-950'>
                {sampleEligibleCount}
              </p>
            </div>
            <div className='rounded-2xl bg-amber-50 p-4'>
              <p className='text-xs uppercase tracking-[0.16em] text-amber-700'>
                Recent orders
              </p>
              <p className='mt-2 text-2xl font-semibold text-slate-950'>
                {workspace?.recentOrders.length || 0}
              </p>
            </div>
            <div className='rounded-2xl bg-violet-50 p-4'>
              <p className='text-xs uppercase tracking-[0.16em] text-violet-700'>
                Active quotes
              </p>
              <p className='mt-2 text-2xl font-semibold text-slate-950'>
                {
                  (workspace?.recentQuotes || []).filter(
                    (quote) => quote.quote_status !== 'expired',
                  ).length
                }
              </p>
            </div>
          </div>
        </CardBox>

        {banner && (
          <NotificationBar
            color={banner.tone === 'success' ? 'success' : 'danger'}
            icon={mdiAlertCircle}
          >
            {banner.message}
          </NotificationBar>
        )}

        {errorMessage && (
          <NotificationBar color='danger' icon={mdiAlertCircle}>
            {errorMessage}
          </NotificationBar>
        )}

        {canReadBuyerTeamQueue && (
          <div
            id='team-queue'
            className='mb-6 grid gap-4 scroll-mt-24 xl:grid-cols-4'
          >
            <CardBox className='border border-slate-200 bg-white shadow-sm'>
              <div className='flex items-start justify-between gap-3'>
                <div>
                  <p className='text-xs font-semibold uppercase tracking-[0.18em] text-blue-600'>
                    Team PO queue
                  </p>
                  <h3 className='mt-2 text-xl font-semibold text-slate-950'>
                    {orderQueue.length} open order(s)
                  </h3>
                </div>
                <div className='rounded-xl bg-blue-50 p-3 text-blue-600'>
                  <BaseIcon path={mdiBasketOutline} size={20} />
                </div>
              </div>
              <div className='mt-4 max-h-72 space-y-3 overflow-y-auto pr-1'>
                {orderQueue.map((order) => (
                  <button
                    key={order.id}
                    type='button'
                    onClick={() =>
                      setDetailPanel({ type: 'order', item: order })
                    }
                    className='w-full rounded-xl border border-slate-200 bg-slate-50 p-3 text-left hover:border-blue-200 hover:bg-blue-50'
                  >
                    <div className='flex items-center justify-between gap-3'>
                      <span className='text-sm font-semibold text-slate-900'>
                        {order.order_number}
                      </span>
                      <StatusPill label={order.order_status} />
                    </div>
                    <p className='mt-2 text-xs text-slate-500'>
                      {formatUserName(order.buyer)} ·{' '}
                      {formatCurrency(order.order_total)}
                    </p>
                  </button>
                ))}
                {!orderQueue.length && (
                  <p className='rounded-xl border border-dashed border-slate-300 p-4 text-sm text-slate-500'>
                    No open purchase orders for this account.
                  </p>
                )}
              </div>
            </CardBox>

            <CardBox className='border border-slate-200 bg-white shadow-sm'>
              <div className='flex items-start justify-between gap-3'>
                <div>
                  <p className='text-xs font-semibold uppercase tracking-[0.18em] text-amber-600'>
                    Sample queue
                  </p>
                  <h3 className='mt-2 text-xl font-semibold text-slate-950'>
                    {sampleQueue.length} active request(s)
                  </h3>
                </div>
                <div className='rounded-xl bg-amber-50 p-3 text-amber-600'>
                  <BaseIcon path={mdiPackageVariantClosed} size={20} />
                </div>
              </div>
              <div className='mt-4 max-h-72 space-y-3 overflow-y-auto pr-1'>
                {sampleQueue.map((sample) => (
                  <button
                    key={sample.id}
                    type='button'
                    onClick={() =>
                      setDetailPanel({ type: 'sample', item: sample })
                    }
                    className='w-full rounded-xl border border-slate-200 bg-slate-50 p-3 text-left hover:border-amber-200 hover:bg-amber-50'
                  >
                    <div className='flex items-center justify-between gap-3'>
                      <span className='text-sm font-semibold text-slate-900'>
                        {sample.sample_request_number}
                      </span>
                      <StatusPill label={sample.sample_status} />
                    </div>
                    <p className='mt-2 text-xs text-slate-500'>
                      {sample.product?.product_name} · needed{' '}
                      {formatDate(sample.needed_by)}
                    </p>
                  </button>
                ))}
                {!sampleQueue.length && (
                  <p className='rounded-xl border border-dashed border-slate-300 p-4 text-sm text-slate-500'>
                    No active sample requests for this account.
                  </p>
                )}
              </div>
            </CardBox>

            <CardBox
              id='buyer-quotes'
              className='border border-slate-200 bg-white shadow-sm'
            >
              <div className='flex items-start justify-between gap-3'>
                <div>
                  <p className='text-xs font-semibold uppercase tracking-[0.18em] text-violet-600'>
                    Quote follow-up
                  </p>
                  <h3 className='mt-2 text-xl font-semibold text-slate-950'>
                    {quoteQueue.length} quote(s)
                  </h3>
                </div>
                <div className='rounded-xl bg-violet-50 p-3 text-violet-600'>
                  <BaseIcon path={mdiFileDocumentOutline} size={20} />
                </div>
              </div>
              <div className='mt-4 max-h-72 space-y-3 overflow-y-auto pr-1'>
                {quoteQueue.map((quote) => (
                  <button
                    key={quote.id}
                    type='button'
                    onClick={() =>
                      setDetailPanel({ type: 'quote', item: quote })
                    }
                    className='w-full rounded-xl border border-slate-200 bg-slate-50 p-3 text-left hover:border-violet-200 hover:bg-violet-50'
                  >
                    <div className='flex items-center justify-between gap-3'>
                      <span className='text-sm font-semibold text-slate-900'>
                        {quote.quote_number}
                      </span>
                      <StatusPill label={quote.quote_status} />
                    </div>
                    <p className='mt-2 text-xs text-slate-500'>
                      Expires {formatDate(quote.expires_at)} ·{' '}
                      {formatCurrency(quote.quote_total)}
                    </p>
                  </button>
                ))}
                {!quoteQueue.length && (
                  <p className='rounded-xl border border-dashed border-slate-300 p-4 text-sm text-slate-500'>
                    No quotes waiting on buyer follow-up.
                  </p>
                )}
              </div>
            </CardBox>

            <CardBox
              id='saved-guides'
              className='scroll-mt-24 border border-slate-200 bg-white shadow-sm'
            >
              <div className='flex items-start justify-between gap-3'>
                <div>
                  <p className='text-xs font-semibold uppercase tracking-[0.18em] text-emerald-600'>
                    Saved order guides
                  </p>
                  <h3 className='mt-2 text-xl font-semibold text-slate-950'>
                    {workspace?.savedLists.length || 0} list(s)
                  </h3>
                </div>
                <div className='rounded-xl bg-emerald-50 p-3 text-emerald-600'>
                  <BaseIcon path={mdiTruckDelivery} size={20} />
                </div>
              </div>
              <div className='mt-4 max-h-72 space-y-3 overflow-y-auto pr-1'>
                {(workspace?.savedLists || []).map((savedList) => (
                  <div
                    key={savedList.id}
                    className='rounded-xl border border-slate-200 bg-slate-50 p-3'
                  >
                    <span className='text-sm font-semibold text-slate-900'>
                      {savedList.list_name}
                    </span>
                    <p className='mt-2 text-xs text-slate-500'>
                      {savedList.items.length} SKU(s) · owner{' '}
                      {formatUserName(savedList.owner)}
                    </p>
                    <BaseButtons
                      className='mt-3 gap-2'
                      mb='mb-0'
                      type='justify-start'
                    >
                      <BaseButton
                        color='info'
                        small
                        label='Load guide'
                        onClick={() => loadSavedListIntoDraft(savedList)}
                      />
                      <BaseButton
                        color='info'
                        small
                        outline
                        label='View'
                        onClick={() =>
                          setDetailPanel({
                            type: 'savedList',
                            item: savedList,
                          })
                        }
                      />
                    </BaseButtons>
                  </div>
                ))}
                {!workspace?.savedLists.length && (
                  <p className='rounded-xl border border-dashed border-slate-300 p-4 text-sm text-slate-500'>
                    No saved lists for this account yet.
                  </p>
                )}
              </div>
            </CardBox>
          </div>
        )}

        <div className='mb-6 grid gap-6 xl:grid-cols-[minmax(0,1fr)_420px]'>
          <CardBox
            id='catalog'
            className='scroll-mt-24 border border-slate-200 bg-white shadow-sm'
          >
            <div className='mb-5 flex flex-col gap-4 border-b border-slate-100 pb-5 lg:flex-row lg:items-center lg:justify-between'>
              <div>
                <p className='text-sm font-semibold uppercase tracking-[0.18em] text-blue-600'>
                  Contract catalog
                </p>
                <h2 className='mt-2 text-2xl font-semibold text-slate-950'>
                  Order guide
                </h2>
                <p className='mt-2 max-w-2xl text-sm text-slate-500'>
                  Work from familiar SKUs, contracted pricing, MOQs, pack sizes,
                  and past purchases.
                </p>
              </div>
              <div className='flex flex-wrap gap-2'>
                {[
                  ['order_guide', 'Order guide'],
                  ['full_catalog', 'Full catalog'],
                  ['previously_purchased', 'Previously purchased'],
                ].map(([mode, label]) => (
                  <button
                    key={mode}
                    type='button'
                    onClick={() => setCatalogMode(mode)}
                    className={`rounded-full border px-4 py-2 text-sm font-semibold transition ${
                      catalogMode === mode
                        ? 'border-blue-600 bg-blue-600 text-white'
                        : 'border-slate-200 bg-white text-slate-600 hover:border-blue-200 hover:text-blue-700'
                    }`}
                  >
                    {label}
                  </button>
                ))}
              </div>
            </div>

            <div className='grid gap-3 md:grid-cols-2'>
              <FormField label='Search products' icons={[mdiMagnify]}>
                <input
                  value={searchQuery}
                  onChange={(event) => setSearchQuery(event.target.value)}
                  placeholder='Search SKU, ingredient, allergen, certification'
                />
              </FormField>
              <FormField label='Category'>
                <select
                  value={categoryFilter}
                  onChange={(event) => setCategoryFilter(event.target.value)}
                >
                  <option value='all'>All categories</option>
                  {categoryOptions.map((category) => (
                    <option key={category} value={category}>
                      {category}
                    </option>
                  ))}
                </select>
              </FormField>
              <FormField label='Temperature'>
                <select
                  value={temperatureFilter}
                  onChange={(event) => setTemperatureFilter(event.target.value)}
                >
                  <option value='all'>All zones</option>
                  {temperatureOptions.map((zone) => (
                    <option key={zone} value={zone}>
                      {toTitle(zone)}
                    </option>
                  ))}
                </select>
              </FormField>
              <FormField label='Availability'>
                <select
                  value={stockFilter}
                  onChange={(event) => setStockFilter(event.target.value)}
                >
                  <option value='orderable'>Orderable</option>
                  <option value='all'>Show all</option>
                  <option value='sample_eligible'>Sample eligible</option>
                </select>
              </FormField>
            </div>

            <div className='mt-6'>
              <div>
                <div className='mb-4 flex items-center justify-between gap-4'>
                  <div>
                    <h3 className='text-lg font-semibold text-slate-900'>
                      {filteredCatalog.length} SKU
                      {filteredCatalog.length === 1 ? '' : 's'} ready to review
                    </h3>
                    <p className='text-sm text-slate-500'>
                      Account pricing, last-order hints, MOQs, allergens, and
                      pack details stay visible in each row.
                    </p>
                  </div>
                  {isLoading && (
                    <p className='text-sm font-medium text-blue-600'>
                      Refreshing…
                    </p>
                  )}
                </div>

                <div className='space-y-3'>
                  {filteredCatalog.map((product, index) => {
                    const minQty =
                      product.contract_min_case_qty || product.moq_cases || 1;
                    const qtyValue =
                      catalogQuantities[product.id] || String(minQty);
                    const currentQty = Number.parseInt(qtyValue, 10) || minQty;
                    const fallbackImage =
                      fallbackProductImages[index % fallbackProductImages.length];
                    return (
                      <div
                        key={product.id}
                        className='rounded-2xl border border-slate-200 bg-white p-4 shadow-sm transition hover:border-blue-200 hover:shadow-md'
                      >
                        <div
                          role='img'
                          aria-label={product.product_name}
                          className='mb-4 h-40 rounded-2xl bg-slate-100 bg-cover bg-center'
                          style={{ backgroundImage: `url(${fallbackImage})` }}
                        />
                        <div className='grid gap-4'>
                          <div className='min-w-0'>
                            <div className='flex flex-wrap items-center gap-2'>
                              <span className='rounded-full bg-slate-950 px-2.5 py-1 text-xs font-semibold text-white'>
                                {product.sku}
                              </span>
                              <span className='rounded-full bg-blue-50 px-2.5 py-1 text-xs font-semibold text-blue-700'>
                                {product.category?.category_name ||
                                  'Specialty product'}
                              </span>
                              <StatusPill label={product.product_status} />
                              {product.is_sample_eligible && (
                                <span className='rounded-full bg-emerald-50 px-2.5 py-1 text-xs font-semibold text-emerald-700'>
                                  Sample-ready
                                </span>
                              )}
                            </div>
                            <h4 className='mt-3 text-lg font-semibold text-slate-950'>
                              {product.product_name}
                            </h4>
                            <p className='mt-1 text-sm text-slate-500'>
                              {[
                                product.brand,
                                product.pack_size,
                                toTitle(product.temperature_zone),
                              ]
                                .filter(Boolean)
                                .join(' · ')}
                            </p>
                            <p className='mt-2 line-clamp-2 text-sm leading-6 text-slate-600'>
                              {product.short_description}
                            </p>
                            <div className='mt-3 flex flex-wrap gap-2'>
                              {splitTags(product.allergens)
                                .slice(0, 3)
                                .map((tag) => (
                                  <span
                                    key={tag}
                                    className='rounded-full bg-rose-50 px-2.5 py-1 text-xs font-medium text-rose-700'
                                  >
                                    {tag}
                                  </span>
                                ))}
                              {splitTags(product.certifications)
                                .slice(0, 3)
                                .map((tag) => (
                                  <span
                                    key={tag}
                                    className='rounded-full bg-emerald-50 px-2.5 py-1 text-xs font-medium text-emerald-700'
                                  >
                                    {tag}
                                  </span>
                                ))}
                            </div>
                          </div>
                          <div className='grid gap-3 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_190px]'>
                            <div className='rounded-2xl bg-slate-50 px-4 py-3'>
                              <p className='text-xs uppercase tracking-[0.14em] text-slate-400'>
                                Contract case
                              </p>
                              <p className='mt-1 text-xl font-semibold text-slate-950'>
                                {formatCurrency(product.contract_case_price)}
                              </p>
                              <p className='mt-1 text-xs text-slate-500'>
                                MOQ {minQty} case(s)
                              </p>
                            </div>
                            <div className='rounded-2xl bg-slate-50 px-4 py-3'>
                              <p className='text-xs uppercase tracking-[0.14em] text-slate-400'>
                                Buying signal
                              </p>
                              <p className='mt-1 text-sm font-semibold text-slate-900'>
                                {getLastOrderedLabel(product.id)}
                              </p>
                              <p className='mt-1 text-xs text-slate-500'>
                                {product.contract_price_list}
                              </p>
                            </div>
                            <div className='flex flex-col gap-3'>
                              <div className='flex items-center rounded-2xl border border-slate-200 bg-slate-50 px-2 py-2'>
                                <button
                                  type='button'
                                  onClick={() =>
                                    setCatalogQuantities((current) => ({
                                      ...current,
                                      [product.id]: String(
                                        Math.max(minQty, currentQty - 1),
                                      ),
                                    }))
                                  }
                                  className='flex h-9 w-9 items-center justify-center rounded-xl bg-white text-slate-600 shadow-sm'
                                >
                                  <BaseIcon path={mdiMinus} size={16} />
                                </button>
                                <input
                                  type='number'
                                  min={minQty}
                                  value={qtyValue}
                                  onChange={(event) =>
                                    setCatalogQuantities((current) => ({
                                      ...current,
                                      [product.id]: event.target.value,
                                    }))
                                  }
                                  className='mx-2 w-full border-0 bg-transparent p-0 text-center text-lg font-semibold text-slate-950 focus:outline-none focus:ring-0'
                                />
                                <button
                                  type='button'
                                  onClick={() =>
                                    setCatalogQuantities((current) => ({
                                      ...current,
                                      [product.id]: String(currentQty + 1),
                                    }))
                                  }
                                  className='flex h-9 w-9 items-center justify-center rounded-xl bg-white text-slate-600 shadow-sm'
                                >
                                  <BaseIcon path={mdiPlus} size={16} />
                                </button>
                              </div>
                              <BaseButtons mb='mb-0' className='gap-2'>
                                <BaseButton
                                  color='info'
                                  label='Add'
                                  onClick={() => addProductToDraft(product)}
                                  disabled={
                                    !product.contract_case_price ||
                                    product.product_status === 'out_of_stock'
                                  }
                                />
                                {product.is_sample_eligible &&
                                  canCreateSamples && (
                                    <BaseButton
                                      color='whiteDark'
                                      outline
                                      label='Sample'
                                      onClick={() => {
                                        setSampleProductId(product.id);
                                        setSampleQuantity('1');
                                        setSampleNotes(
                                          `Sample requested for ${product.product_name}.`,
                                        );
                                        scrollToSection('samples');
                                      }}
                                    />
                                  )}
                              </BaseButtons>
                            </div>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>

                {!filteredCatalog.length && !isLoading && (
                  <div className='rounded-3xl border border-dashed border-slate-300 bg-slate-50 px-6 py-10 text-center text-slate-500'>
                    No products matched that search. Try a broader keyword or
                    switch accounts.
                  </div>
                )}
              </div>

              <div className='space-y-6'>
                <CardBox className='border border-slate-200 bg-white shadow-sm'>
                  <div className='flex items-start justify-between gap-4'>
                    <div>
                      <p className='text-sm font-semibold uppercase tracking-[0.22em] text-blue-600'>
                        Delivery profile
                      </p>
                      <h3 className='mt-2 text-xl font-semibold text-slate-900'>
                        {currentLocation?.location_name || 'Select a location'}
                      </h3>
                    </div>
                    <div className='rounded-2xl bg-blue-50 p-3 text-blue-600'>
                      <BaseIcon path={mdiTruckDelivery} size={20} />
                    </div>
                  </div>
                  <div className='mt-4 space-y-4 text-sm text-slate-600'>
                    <div>
                      <p className='font-semibold text-slate-900'>
                        Ship-to address
                      </p>
                      <p className='mt-1'>
                        {[
                          currentLocation?.address_line_1,
                          currentLocation?.address_line_2,
                        ]
                          .filter(Boolean)
                          .join(', ')}
                      </p>
                      <p>
                        {[
                          currentLocation?.city,
                          currentLocation?.state,
                          currentLocation?.postal_code,
                        ]
                          .filter(Boolean)
                          .join(', ')}
                      </p>
                    </div>
                    <div>
                      <p className='font-semibold text-slate-900'>
                        Primary contact
                      </p>
                      <p className='mt-1'>
                        {currentLocation?.default_contact?.contact_name ||
                          'No default contact'}
                      </p>
                      <p>{currentLocation?.default_contact?.role_title}</p>
                      <p>{currentLocation?.default_contact?.email}</p>
                    </div>
                    <div>
                      <p className='font-semibold text-slate-900'>
                        Receiving notes
                      </p>
                      <p className='mt-1'>
                        {currentLocation?.delivery_instructions ||
                          'No location instructions on file.'}
                      </p>
                    </div>
                  </div>
                </CardBox>

                <CardBox className='border border-slate-200 bg-white shadow-sm'>
                  <div className='flex items-start justify-between gap-4'>
                    <div>
                      <p className='text-sm font-semibold uppercase tracking-[0.22em] text-blue-600'>
                        Account operations
                      </p>
                      <h3 className='mt-2 text-xl font-semibold text-slate-900'>
                        Contacts and locations
                      </h3>
                    </div>
                    <div className='rounded-2xl bg-slate-100 p-3 text-slate-700'>
                      <BaseIcon path={mdiFileDocumentOutline} size={20} />
                    </div>
                  </div>
                  <div className='mt-4 space-y-3 text-sm text-slate-600'>
                    <p>
                      <span className='font-semibold text-slate-900'>
                        {currentAccount?.contacts.length || 0}
                      </span>{' '}
                      account contacts and{' '}
                      <span className='font-semibold text-slate-900'>
                        {currentAccount?.locations.length || 0}
                      </span>{' '}
                      active ship-to locations are ready to support the buyer
                      workflow.
                    </p>
                    <p>{currentAccount?.notes}</p>
                  </div>
                  <BaseButtons
                    className='mt-4 gap-3'
                    mb='mb-0'
                    type='justify-start'
                  >
                    <BaseButton
                      color='info'
                      outline
                      label='Request contact update'
                      onClick={() =>
                        setBanner({
                          tone: 'success',
                          message:
                            'Contact changes are routed to the supplier team from the buyer portal.',
                        })
                      }
                    />
                    <BaseButton
                      color='info'
                      outline
                      label='Request location update'
                      onClick={() =>
                        setBanner({
                          tone: 'success',
                          message:
                            'Ship-to location changes are handled as buyer account requests.',
                        })
                      }
                    />
                    <BaseButton
                      color='info'
                      outline
                      label='Contact sales rep'
                      onClick={() =>
                        setBanner({
                          tone: 'success',
                          message:
                            'Your supplier rep will receive the account support request.',
                        })
                      }
                    />
                  </BaseButtons>
                </CardBox>
              </div>
            </div>
          </CardBox>

          <div className='space-y-6 xl:sticky xl:top-6 xl:self-start'>
            <CardBox
              id='purchase-order'
              className='scroll-mt-24 border border-slate-200 bg-white shadow-sm'
            >
              <div className='mb-4 flex items-start justify-between gap-4'>
                <div>
                  <p className='text-sm font-semibold uppercase tracking-[0.18em] text-blue-600'>
                    Draft purchase order
                  </p>
                  <h3 className='mt-2 text-xl font-semibold text-slate-900'>
                    Review cart and checkout
                  </h3>
                  <p className='mt-1 text-sm text-slate-500'>
                    {cartItems.length} line(s) · {totalDraftCases} case(s)
                  </p>
                </div>
                <div className='rounded-2xl bg-blue-50 p-3 text-blue-600'>
                  <BaseIcon path={mdiBasketOutline} size={20} />
                </div>
              </div>

              <div className='grid gap-4'>
                <div className='grid gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-4 text-sm sm:grid-cols-2'>
                  <div>
                    <p className='text-xs uppercase tracking-[0.14em] text-slate-400'>
                      PO
                    </p>
                    <p className='mt-1 font-semibold text-slate-900'>
                      {poNumber || 'Required'}
                    </p>
                  </div>
                  <div>
                    <p className='text-xs uppercase tracking-[0.14em] text-slate-400'>
                      Delivery
                    </p>
                    <p className='mt-1 font-semibold text-slate-900'>
                      {formatDate(requestedDeliveryDate)}
                    </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'>
                      {currentLocation?.location_name || 'Select location'}
                    </p>
                  </div>
                  <div>
                    <p className='text-xs uppercase tracking-[0.14em] text-slate-400'>
                      Payment
                    </p>
                    <select
                      value={paymentTerms}
                      onChange={(event) => setPaymentTerms(event.target.value)}
                    >
                      <option value='net_15'>Net 15</option>
                      <option value='net_30'>Net 30</option>
                      <option value='net_45'>Net 45</option>
                      <option value='prepaid'>Prepaid</option>
                    </select>
                  </div>
                </div>
                <FormField label='Buyer notes' hasTextareaHeight>
                  <textarea
                    value={buyerNotes}
                    onChange={(event) => setBuyerNotes(event.target.value)}
                  />
                </FormField>
              </div>

              <div className='mt-5 rounded-3xl border border-slate-200 bg-slate-50 p-4'>
                <div className='flex items-center justify-between'>
                  <p className='text-sm font-semibold text-slate-900'>
                    Draft lines
                  </p>
                  <p className='text-sm text-slate-500'>
                    {totalDraftCases} total case(s)
                  </p>
                </div>
                <div className='mt-4 space-y-3'>
                  {cartItems.map((item) => (
                    <div
                      key={item.productId}
                      className='rounded-2xl border border-slate-200 bg-white p-4'
                    >
                      <div className='flex items-start justify-between gap-3'>
                        <div>
                          <p className='text-sm font-semibold text-slate-900'>
                            {item.productName}
                          </p>
                          <p className='mt-1 text-xs uppercase tracking-[0.16em] text-slate-400'>
                            {item.sku}
                          </p>
                          <p className='mt-1 text-sm text-slate-500'>
                            {item.packSize}
                          </p>
                        </div>
                        <StatusPill label={item.temperatureZone} />
                      </div>
                      <div className='mt-3 grid items-end gap-3 sm:grid-cols-[96px_1fr_auto]'>
                        <div>
                          <p className='mb-1 text-xs uppercase tracking-[0.16em] text-slate-400'>
                            Cases
                          </p>
                          <input
                            type='number'
                            min={item.moqCases}
                            value={item.quantityCases}
                            onChange={(event) =>
                              updateDraftQuantity(
                                item.productId,
                                event.target.value,
                              )
                            }
                            className='w-full rounded-xl border border-slate-200 px-3 py-2 font-semibold text-slate-900 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100'
                          />
                        </div>
                        <div>
                          <p className='text-xs uppercase tracking-[0.16em] text-slate-400'>
                            Contract case price
                          </p>
                          <p className='mt-1 text-sm font-semibold text-slate-900'>
                            {formatCurrency(item.casePrice)}
                          </p>
                          <p className='mt-1 text-sm text-slate-500'>
                            Line total {formatCurrency(item.lineTotal)}
                          </p>
                        </div>
                        <BaseButton
                          color='danger'
                          outline
                          label='Remove'
                          onClick={() => removeDraftItem(item.productId)}
                        />
                      </div>
                    </div>
                  ))}

                  {!cartItems.length && (
                    <div className='rounded-2xl border border-dashed border-slate-300 px-4 py-8 text-center text-sm text-slate-500'>
                      Add products from the contract catalog to start the
                      purchase order.
                    </div>
                  )}
                </div>
              </div>

              <div className='mt-5 rounded-3xl border border-amber-200 bg-amber-50 p-4'>
                <div className='flex items-center gap-2 text-sm font-semibold text-amber-800'>
                  <BaseIcon path={mdiFilterVariant} size={18} />
                  Checkout review
                </div>
                <div className='mt-3 space-y-2 text-sm text-amber-800'>
                  {draftWarnings.map((warning) => (
                    <p key={warning}>• {warning}</p>
                  ))}
                  {!draftWarnings.length && (
                    <p>
                      No blocking warnings.{' '}
                      {canCreateOrders
                        ? 'Ready to submit.'
                        : 'Ready for buyer admin submission.'}
                    </p>
                  )}
                  {!canCreateOrders && (
                    <p>
                      Your current role can prepare the purchasing draft, but a
                      buyer admin must submit the PO.
                    </p>
                  )}
                </div>
              </div>

              {!!suggestedItems.length && (
                <div className='mt-5 rounded-3xl border border-blue-100 bg-blue-50 p-4'>
                  <p className='text-sm font-semibold text-blue-900'>
                    Did you forget?
                  </p>
                  <div className='mt-3 space-y-2'>
                    {suggestedItems.map((product) => (
                      <button
                        key={product.id}
                        type='button'
                        onClick={() => addProductToDraft(product)}
                        className='flex w-full items-center justify-between rounded-2xl bg-white px-3 py-2 text-left text-sm text-slate-700 shadow-sm'
                      >
                        <span>{product.product_name}</span>
                        <span className='font-semibold text-blue-700'>
                          {formatCurrency(product.contract_case_price)}
                        </span>
                      </button>
                    ))}
                  </div>
                </div>
              )}

              <div className='mt-5 flex items-center justify-between rounded-3xl bg-slate-950 px-5 py-4 text-white'>
                <div>
                  <p className='text-sm uppercase tracking-[0.16em] text-slate-300'>
                    Draft total
                  </p>
                  <p className='mt-2 text-3xl font-semibold'>
                    {formatCurrency(draftTotal)}
                  </p>
                </div>
                <BaseButton
                  color='info'
                  label={
                    isSubmittingOrder
                      ? 'Submitting…'
                      : canCreateOrders
                        ? 'Submit PO'
                        : 'Order permission required'
                  }
                  onClick={submitDraftOrder}
                  disabled={!canCreateOrders || isSubmittingOrder}
                />
              </div>
            </CardBox>

            <CardBox
              id='samples'
              className='scroll-mt-24 border border-slate-200 bg-white shadow-sm'
            >
              <div className='mb-4 flex items-start justify-between gap-4'>
                <div>
                  <p className='text-sm font-semibold uppercase tracking-[0.22em] text-blue-600'>
                    Sample requests
                  </p>
                  <h3 className='mt-2 text-xl font-semibold text-slate-900'>
                    Request a tasting sample
                  </h3>
                </div>
                <div className='rounded-2xl bg-emerald-50 p-3 text-emerald-600'>
                  <BaseIcon path={mdiPackageVariantClosed} size={20} />
                </div>
              </div>
              <div className='grid gap-4'>
                <FormField label='Sample product'>
                  <select
                    value={sampleProductId}
                    onChange={(event) => setSampleProductId(event.target.value)}
                  >
                    <option value=''>Select a product</option>
                    {(workspace?.catalog || [])
                      .filter((product) => product.is_sample_eligible)
                      .map((product) => (
                        <option key={product.id} value={product.id}>
                          {product.product_name} · {product.sku}
                        </option>
                      ))}
                  </select>
                </FormField>
                <div className='grid gap-4 md:grid-cols-2'>
                  <FormField label='Sample quantity'>
                    <input
                      type='number'
                      min='1'
                      value={sampleQuantity}
                      onChange={(event) =>
                        setSampleQuantity(event.target.value)
                      }
                    />
                  </FormField>
                  <FormField label='Needed by'>
                    <input
                      type='date'
                      value={sampleNeededBy}
                      onChange={(event) =>
                        setSampleNeededBy(event.target.value)
                      }
                    />
                  </FormField>
                </div>
                <FormField label='Notes' hasTextareaHeight>
                  <textarea
                    value={sampleNotes}
                    onChange={(event) => setSampleNotes(event.target.value)}
                    placeholder='Describe the tasting, menu use, or evaluation criteria.'
                  />
                </FormField>
                <BaseButton
                  color='info'
                  label={
                    isSubmittingSample
                      ? 'Sending…'
                      : canCreateSamples
                        ? 'Send sample request'
                        : 'Sample permission required'
                  }
                  onClick={submitSampleRequest}
                  disabled={!canCreateSamples || isSubmittingSample}
                />
              </div>
            </CardBox>

            {createdOrder && (
              <CardBox className='border border-emerald-200 bg-emerald-50 shadow-sm'>
                <p className='text-sm font-semibold uppercase tracking-[0.22em] text-emerald-700'>
                  Order confirmation
                </p>
                <h3 className='mt-2 text-2xl font-semibold text-slate-900'>
                  {createdOrder.order_number}
                </h3>
                <p className='mt-2 text-sm text-slate-600'>
                  {createdOrder.po_number} ·{' '}
                  {formatCurrency(createdOrder.order_total)} ·{' '}
                  {toTitle(createdOrder.order_status)}
                </p>
                <BaseButtons
                  className='mt-4 gap-3'
                  mb='mb-0'
                  type='justify-start'
                >
                  <BaseButton
                    color='info'
                    label='View order'
                    onClick={() =>
                      setDetailPanel({ type: 'order', item: createdOrder })
                    }
                  />
                  <BaseButton
                    color='info'
                    outline
                    label='Open order history'
                    onClick={() => scrollToSection('orders')}
                  />
                </BaseButtons>
              </CardBox>
            )}
          </div>
        </div>

        <div className='grid gap-6 lg:grid-cols-[1.5fr_1fr]'>
          <CardBox
            id='orders'
            className='scroll-mt-24 border border-slate-200 bg-white shadow-sm'
          >
            <div className='mb-5 flex items-start justify-between gap-4'>
              <div>
                <p className='text-sm font-semibold uppercase tracking-[0.22em] text-blue-600'>
                  Order history + reorder
                </p>
                <h3 className='mt-2 text-2xl font-semibold text-slate-900'>
                  Load a previous order into a new draft
                </h3>
                <p className='mt-2 text-sm text-slate-500'>
                  Review delivered and active orders, then reload familiar
                  purchasing patterns into a fresh draft PO.
                </p>
              </div>
            </div>

            <div className='space-y-4'>
              {(workspace?.recentOrders || []).map((order) => (
                <div
                  key={order.id}
                  className='rounded-3xl border border-slate-200 bg-slate-50 p-5'
                >
                  <div className='flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between'>
                    <div>
                      <div className='flex flex-wrap items-center gap-3'>
                        <h4 className='text-xl font-semibold text-slate-900'>
                          {order.order_number}
                        </h4>
                        <StatusPill label={order.order_status} />
                        <span className='text-sm text-slate-500'>
                          PO {order.po_number}
                        </span>
                      </div>
                      <div className='mt-2 flex flex-wrap gap-4 text-sm text-slate-500'>
                        <span>Ordered {formatDate(order.ordered_at)}</span>
                        <span>
                          Requested {formatDate(order.requested_delivery_date)}
                        </span>
                        <span>{order.location?.location_name}</span>
                      </div>
                      <p className='mt-3 text-sm text-slate-600'>
                        {order.buyer_notes}
                      </p>
                    </div>
                    <div className='rounded-2xl bg-white px-4 py-3 text-right shadow-sm'>
                      <p className='text-xs uppercase tracking-[0.16em] text-slate-400'>
                        Order total
                      </p>
                      <p className='mt-2 text-2xl font-semibold text-slate-900'>
                        {formatCurrency(order.order_total)}
                      </p>
                    </div>
                  </div>
                  <div className='mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3'>
                    {order.items.map((item) => (
                      <div
                        key={item.id}
                        className='rounded-2xl border border-slate-200 bg-white p-4'
                      >
                        <div className='flex items-start justify-between gap-3'>
                          <div>
                            <p className='text-sm font-semibold text-slate-900'>
                              {item.product?.product_name}
                            </p>
                            <p className='mt-1 text-xs uppercase tracking-[0.16em] text-slate-400'>
                              {item.product?.sku}
                            </p>
                          </div>
                          <StatusPill label={item.fulfillment_status} />
                        </div>
                        <p className='mt-3 text-sm text-slate-500'>
                          {item.quantity_cases} case(s) ·{' '}
                          {formatCurrency(item.line_total)}
                        </p>
                      </div>
                    ))}
                  </div>
                  <BaseButtons
                    className='mt-4 gap-3'
                    mb='mb-0'
                    type='justify-start'
                  >
                    <BaseButton
                      color='info'
                      label='Load into draft'
                      onClick={() => loadOrderIntoDraft(order)}
                    />
                    <BaseButton
                      color='info'
                      outline
                      label='View details'
                      onClick={() =>
                        setDetailPanel({ type: 'order', item: order })
                      }
                    />
                  </BaseButtons>
                </div>
              ))}

              {!workspace?.recentOrders.length && !isLoading && (
                <div className='rounded-3xl border border-dashed border-slate-300 px-6 py-10 text-center text-slate-500'>
                  No orders yet for this account. Submit the draft PO above to
                  create the first record.
                </div>
              )}
            </div>
          </CardBox>

          <div className='space-y-6'>
          <CardBox
            id='quotes'
            className='scroll-mt-24 border border-slate-200 bg-white shadow-sm'
          >
              <div className='flex items-start justify-between gap-4'>
                <div>
                  <p className='text-sm font-semibold uppercase tracking-[0.22em] text-blue-600'>
                    Quotes
                  </p>
                  <h3 className='mt-2 text-xl font-semibold text-slate-900'>
                    Commercial follow-up
                  </h3>
                </div>
                <div className='rounded-2xl bg-violet-50 p-3 text-violet-600'>
                  <BaseIcon path={mdiFileDocumentOutline} size={20} />
                </div>
              </div>
              <div className='mt-4 space-y-4'>
                {(workspace?.recentQuotes || []).map((quote) => (
                  <div
                    key={quote.id}
                    className='rounded-2xl border border-slate-200 bg-slate-50 p-4'
                  >
                    <div className='flex items-start justify-between gap-3'>
                      <div>
                        <p className='text-sm font-semibold text-slate-900'>
                          {quote.quote_number}
                        </p>
                        <p className='mt-1 text-sm text-slate-500'>
                          Owner: {formatUserName(quote.owner)}
                        </p>
                      </div>
                      <StatusPill label={quote.quote_status} />
                    </div>
                    <p className='mt-3 text-sm text-slate-600'>{quote.notes}</p>
                    <div className='mt-3 flex items-center justify-between text-sm text-slate-500'>
                      <span>Expires {formatDate(quote.expires_at)}</span>
                      <span className='font-semibold text-slate-900'>
                        {formatCurrency(quote.quote_total)}
                      </span>
                    </div>
                    <BaseButtons
                      className='mt-4 gap-3'
                      mb='mb-0'
                      type='justify-start'
                    >
                      <BaseButton
                        color='info'
                        outline
                        label='View quote'
                        onClick={() =>
                          setDetailPanel({ type: 'quote', item: quote })
                        }
                      />
                    </BaseButtons>
                  </div>
                ))}

                {!workspace?.recentQuotes.length && !isLoading && (
                  <div className='rounded-2xl border border-dashed border-slate-300 px-4 py-8 text-center text-sm text-slate-500'>
                    No quotes on file for this account yet.
                  </div>
                )}
              </div>
            </CardBox>

            <CardBox className='border border-slate-200 bg-white shadow-sm'>
              <div className='flex items-start justify-between gap-4'>
                <div>
                  <p className='text-sm font-semibold uppercase tracking-[0.22em] text-blue-600'>
                    Recent samples
                  </p>
                  <h3 className='mt-2 text-xl font-semibold text-slate-900'>
                    Evaluation history
                  </h3>
                </div>
                <div className='rounded-2xl bg-amber-50 p-3 text-amber-600'>
                  <BaseIcon path={mdiPackageVariantClosed} size={20} />
                </div>
              </div>
              <div className='mt-4 space-y-4'>
                {(workspace?.recentSamples || []).map((sample) => (
                  <div
                    key={sample.id}
                    className='rounded-2xl border border-slate-200 bg-slate-50 p-4'
                  >
                    <div className='flex items-start justify-between gap-3'>
                      <div>
                        <p className='text-sm font-semibold text-slate-900'>
                          {sample.sample_request_number}
                        </p>
                        <p className='mt-1 text-sm text-slate-500'>
                          {sample.product?.product_name}
                        </p>
                      </div>
                      <StatusPill label={sample.sample_status} />
                    </div>
                    <p className='mt-3 text-sm text-slate-600'>
                      {sample.notes}
                    </p>
                    <div className='mt-3 flex items-center justify-between text-sm text-slate-500'>
                      <span>Needed {formatDate(sample.needed_by)}</span>
                      <span>{sample.sample_quantity} sample case(s)</span>
                    </div>
                    <BaseButtons
                      className='mt-4 gap-3'
                      mb='mb-0'
                      type='justify-start'
                    >
                      <BaseButton
                        color='info'
                        outline
                        label='View sample'
                        onClick={() =>
                          setDetailPanel({ type: 'sample', item: sample })
                        }
                      />
                    </BaseButtons>
                  </div>
                ))}

                {!workspace?.recentSamples.length && !isLoading && (
                  <div className='rounded-2xl border border-dashed border-slate-300 px-4 py-8 text-center text-sm text-slate-500'>
                    No sample requests yet. Use the sample form above to create
                    the first request.
                  </div>
                )}
              </div>
            </CardBox>
          </div>
        </div>

        <DetailPanel
          detail={detailPanel}
          onClose={() => setDetailPanel(null)}
          onLoadOrder={(order) => {
            setDetailPanel(null);
            loadOrderIntoDraft(order);
          }}
          onLoadSavedList={(savedList) => {
            setDetailPanel(null);
            loadSavedListIntoDraft(savedList);
          }}
        />
      </SectionMain>
    </>
  );
};

BuyerPortalPage.getLayout = function getLayout(page: ReactElement) {
  return (
    <LayoutAuthenticated permission='READ_BUYER_PORTAL'>
      {page}
    </LayoutAuthenticated>
  );
};

export default BuyerPortalPage;
