import * as React from 'react'
import type { MenuCategory, MenuItem } from '~/lib/types'

const CATEGORY_ICONS: Record<string, string> = {
  'brew-bites': 'tapas',
  'sharing-plates': 'restaurant_menu',
  salads: 'eco',
  platters: 'restaurant',
  'international-appetizers': 'public',
  'indian-appetizers': 'local_dining',
  'main-course': 'dinner_dining',
  curries: 'soup_kitchen',
  'biryanis-rice-breads': 'rice_bowl',
  desserts: 'icecream',
  pizzas: 'local_pizza',
}

export function MenuBrowser({
  categories,
  items,
}: {
  categories: MenuCategory[]
  items: MenuItem[]
}) {
  const [active, setActive] = React.useState<string>('all')

  const visible = items.filter((item) => active === 'all' || item.category === active)

  return (
    <>
      {/* Sticky Menu Navigation Filter */}
      <section className="sticky top-20 z-40 bg-surface/90 py-space-md shadow-md backdrop-blur-md">
        <div className="no-scrollbar mx-auto flex max-w-7xl items-center justify-start gap-space-sm overflow-x-auto px-grid-margin md:justify-center">
          <FilterTab
            key="all"
            label="All Offerings"
            active={active === 'all'}
            onClick={() => setActive('all')}
          />
          {categories.map((category) => (
            <FilterTab
              key={category.slug}
              label={category.name}
              active={active === category.slug}
              onClick={() => setActive(category.slug)}
            />
          ))}
        </div>
      </section>

      {/* Main Menu Grid */}
      <section className="mx-auto w-full max-w-7xl px-grid-margin py-space-xl">
        <div className="grid grid-cols-1 gap-grid-gutter md:grid-cols-2">
          {visible.map((item) => (
            <MenuCard key={item.uid} item={item} />
          ))}
        </div>
      </section>
    </>
  )
}

function MenuCard({ item }: { item: MenuItem }) {
  const icon = CATEGORY_ICONS[item.category] ?? 'restaurant'
  const showFooter = Boolean(item.pairing || item.tag)

  return (
    <div className="flex flex-col overflow-hidden rounded-xl bg-surface-container shadow-md transition-all duration-300 hover:shadow-xl">
      {item.image ? (
        <div
          className="relative h-64 w-full bg-cover bg-center"
          style={{ backgroundImage: `url('${item.image}')` }}
        >
          {item.group ? (
            <div className="absolute right-space-sm top-space-sm rounded bg-surface/85 px-space-sm py-space-xs backdrop-blur-sm">
              <DietBadge group={item.group} />
            </div>
          ) : null}
        </div>
      ) : (
        <div className="relative flex h-32 w-full items-center justify-center bg-surface-container-high">
          <span className="material-symbols-outlined text-[44px] text-primary/60">{icon}</span>
          {item.group ? (
            <div className="absolute right-space-sm top-space-sm">
              <DietBadge group={item.group} />
            </div>
          ) : null}
        </div>
      )}

      <div className="flex flex-grow flex-col justify-between">
        <div className="p-space-lg">
          <div className="mb-space-xs flex items-start justify-between gap-space-md">
            <h3 className="font-headline-md text-on-surface">{item.name}</h3>
            {item.price ? (
              <span className="shrink-0 font-headline-md text-primary">₹{item.price}</span>
            ) : null}
          </div>
          {item.description ? (
            <p className="text-body-md text-on-surface-variant">{item.description}</p>
          ) : null}
        </div>

        {showFooter ? (
          <div className="mt-space-md flex items-center justify-between gap-space-md border-t border-outline-variant/20 bg-surface-container-low px-space-lg py-space-md">
            {item.pairing ? (
              <div className="flex items-center gap-space-sm">
                <span
                  className="material-symbols-outlined text-[20px] text-primary"
                  style={{ fontVariationSettings: "'FILL' 1" }}
                >
                  sports_bar
                </span>
                <span className="text-label-md text-on-surface">
                  Perfect Pairing: <strong className="text-primary">{item.pairing}</strong>
                </span>
              </div>
            ) : (
              <span />
            )}
            {item.tag ? (
              <span className="rounded bg-surface-container-highest px-space-sm py-space-xs text-label-md uppercase text-on-surface-variant">
                {item.tag}
              </span>
            ) : null}
          </div>
        ) : null}
      </div>
    </div>
  )
}

/** FSSAI-style dietary mark: green square for veg, red for non-veg. */
function DietBadge({ group }: { group: string }) {
  const isVeg = group === 'veg'
  const border = isVeg ? 'border-green-500' : 'border-red-500'
  const dot = isVeg ? 'bg-green-500' : 'bg-red-500'
  return (
    <span
      title={isVeg ? 'Vegetarian' : 'Non-Vegetarian'}
      className={`flex h-3.5 w-3.5 items-center justify-center rounded-[2px] border-2 bg-surface ${border}`}
    >
      <span className={`h-1 w-1 rounded-full ${dot}`} />
    </span>
  )
}

function FilterTab({
  label,
  active,
  onClick,
}: {
  label: string
  active: boolean
  onClick: () => void
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={
        active
          ? 'whitespace-nowrap rounded-lg bg-primary-container px-space-md py-space-sm text-label-lg font-bold text-on-primary-container transition-all'
          : 'whitespace-nowrap rounded-lg bg-surface-container px-space-md py-space-sm text-label-lg text-on-surface-variant transition-all hover:bg-surface-container-high'
      }
    >
      {label}
    </button>
  )
}
