import { useState } from "preact/hooks";
import type { Meal } from "../../lib/types";
import type { UserLocation } from "../../lib/use-location";
import { PlaceCard } from "../shared/PlaceCard";

export function FoodTab({ meals, location }: { meals: Meal[]; location: UserLocation | null }) {
  const [expandedIdx, setExpandedIdx] = useState<string | null>(null);

  const totalCandidates = meals.reduce((n, m) => n + m.candidates.length, 0);

  return (
    <div class="food-tab">
      <div class="food-tab-header">
        <div class="itin-section-label">Dining</div>
        <div class="food-count">{meals.length} meals · {totalCandidates} options</div>
      </div>

      {meals.map(meal => (
        <div key={meal.id} class="food-meal-section">
          <div class="food-meal-header">
            <div class="food-meal-top">
              <div class="food-meal-label">{meal.label}</div>
              {meal.budget && (
                <div class="food-meal-budget">${meal.budget}/person</div>
              )}
            </div>
            {meal.sub && <div class="food-meal-sub">{meal.sub}</div>}
            {meal.preferences && <div class="food-meal-pref">{meal.preferences}</div>}
            {meal.notes && <div class="food-meal-notes">{meal.notes}</div>}
          </div>
          <div class="food-cards">
            {meal.candidates.map(place => {
              const uid = meal.id + ":" + place.name;
              const isSelected = (meal.selected || []).includes(place.name);
              return (
                <div key={uid} class={isSelected ? "food-candidate selected" : "food-candidate"}>
                  {isSelected && <div class="food-selected-badge">Selected</div>}
                  <PlaceCard
                    place={place}
                    expanded={expandedIdx === uid}
                    onToggle={() => setExpandedIdx(expandedIdx === uid ? null : uid)}
                    location={location}
                  />
                </div>
              );
            })}
          </div>
        </div>
      ))}

      {meals.length === 0 && (
        <div class="empty-state">No meals planned yet.</div>
      )}
    </div>
  );
}
