'use client'

import { useEffect, useState, useCallback } from 'react'
import {
  Package, Plus, Search, Pencil, Trash2, PackagePlus, X,
  AlertTriangle, DollarSign, XCircle, ArrowDownCircle, ArrowUpCircle,
  Loader2, ChefHat
} from 'lucide-react'
import toast from 'react-hot-toast'
import Pagination, { PaginationData } from '@/components/Pagination'
import { STOCK_MOVEMENT_REASONS, STOCK_MOVEMENT_TYPES, INGREDIENT_UNITS } from '@/lib/constants'

function formatCurrency(val: number) {
  return new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', minimumFractionDigits: 0 }).format(val)
}

function formatDate(dateStr: string) {
  return new Date(dateStr).toLocaleDateString('id-ID', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' })
}

function getStockStatus(current: number, min: number) {
  if (current <= 0) return { label: 'Habis', color: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300' }
  if (current <= min) return { label: 'Stok Rendah', color: 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-300' }
  return { label: 'Aman', color: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300' }
}

const tabs = [
  { id: 'ingredients' as const, label: 'Bahan Baku' },
  { id: 'movements' as const, label: 'Mutasi Stok' },
  { id: 'recipes' as const, label: 'Resep' },
  { id: 'reports' as const, label: 'Laporan Stok' },
]

export default function InventoryPage() {
  const [activeTab, setActiveTab] = useState<'ingredients' | 'movements' | 'recipes' | 'reports'>('ingredients')

  // Alerts
  const [alerts, setAlerts] = useState<any>(null)

  // Ingredients tab
  const [ingredients, setIngredients] = useState<any[]>([])
  const [ingredientSearch, setIngredientSearch] = useState('')
  const [ingredientLoading, setIngredientLoading] = useState(true)
  const [ingredientPagination, setIngredientPagination] = useState<PaginationData>({ page: 1, limit: 20, total: 0, totalPages: 0 })
  const [showIngredientModal, setShowIngredientModal] = useState(false)
  const [editingIngredient, setEditingIngredient] = useState<any>(null)
  const [ingredientForm, setIngredientForm] = useState({ name: '', unit: 'pcs', costPerUnit: '' })
  const [savingIngredient, setSavingIngredient] = useState(false)

  // Stock movement modal
  const [showStockModal, setShowStockModal] = useState(false)
  const [stockForm, setStockForm] = useState({ ingredientId: '', storeId: '', type: 'in', reason: 'purchase', quantity: '', costPerUnit: '', notes: '' })
  const [savingStock, setSavingStock] = useState(false)

  // Movements tab
  const [movements, setMovements] = useState<any[]>([])
  const [movementLoading, setMovementLoading] = useState(false)
  const [movementPagination, setMovementPagination] = useState<PaginationData>({ page: 1, limit: 20, total: 0, totalPages: 0 })
  const [movementFilters, setMovementFilters] = useState({ storeId: '', type: '', reason: '' })

  // Recipes tab
  const [menuItems, setMenuItems] = useState<any[]>([])
  const [selectedMenuItem, setSelectedMenuItem] = useState<any>(null)
  const [recipeIngredients, setRecipeIngredients] = useState<any[]>([])
  const [recipeTotalCost, setRecipeTotalCost] = useState(0)
  const [showRecipeModal, setShowRecipeModal] = useState(false)
  const [recipeForm, setRecipeForm] = useState({ ingredientId: '', quantity: '' })
  const [savingRecipe, setSavingRecipe] = useState(false)

  // Reports tab
  const [reportData, setReportData] = useState<any>(null)
  const [reportLoading, setReportLoading] = useState(false)
  const [reportPeriod, setReportPeriod] = useState('30d')

  // Shared
  const [stores, setStores] = useState<any[]>([])
  const [selectedStoreId, setSelectedStoreId] = useState('')
  const [allIngredients, setAllIngredients] = useState<any[]>([])

  // --- Fetch functions ---
  const fetchAlerts = async () => {
    try {
      const res = await fetch('/api/inventory/alerts')
      const data = await res.json()
      setAlerts(data)
    } catch { /* ignore */ }
  }

  const fetchIngredients = useCallback(async (page = 1) => {
    setIngredientLoading(true)
    try {
      const params = new URLSearchParams()
      params.set('page', String(page))
      if (ingredientSearch) params.set('search', ingredientSearch)
      if (selectedStoreId) params.set('storeId', selectedStoreId)
      const res = await fetch(`/api/inventory/ingredients?${params}`)
      const data = await res.json()
      // Map stockLevels to flat currentStock/minStock for the selected store
      const mapped = (data.ingredients || []).map((ing: any) => {
        const sl = (ing.stockLevels || []).find((s: any) => s.storeId === selectedStoreId) || ing.stockLevels?.[0]
        return {
          ...ing,
          currentStock: sl ? Number(sl.currentStock) : 0,
          minStock: sl ? Number(sl.minStock) : 0,
        }
      })
      setIngredients(mapped)
      if (data.pagination) setIngredientPagination(data.pagination)
    } catch { toast.error('Gagal memuat bahan baku') }
    finally { setIngredientLoading(false) }
  }, [ingredientSearch, selectedStoreId])

  const fetchAllIngredients = async () => {
    try {
      const res = await fetch('/api/inventory/ingredients?limit=1000')
      const data = await res.json()
      setAllIngredients(data.ingredients || [])
    } catch { /* ignore */ }
  }

  const fetchMovements = useCallback(async (page = 1) => {
    setMovementLoading(true)
    try {
      const params = new URLSearchParams()
      params.set('page', String(page))
      if (movementFilters.storeId) params.set('storeId', movementFilters.storeId)
      if (movementFilters.type) params.set('type', movementFilters.type)
      if (movementFilters.reason) params.set('reason', movementFilters.reason)
      const res = await fetch(`/api/inventory/movements?${params}`)
      const data = await res.json()
      setMovements(data.movements || [])
      if (data.pagination) setMovementPagination(data.pagination)
    } catch { toast.error('Gagal memuat mutasi stok') }
    finally { setMovementLoading(false) }
  }, [movementFilters])

  const fetchStores = async () => {
    try {
      const res = await fetch('/api/stores')
      const data = await res.json()
      const storeList = data.stores || []
      setStores(storeList)
      if (storeList.length > 0 && !selectedStoreId) {
        setSelectedStoreId(storeList[0].id)
      }
    } catch { /* ignore */ }
  }

  const fetchMenuItems = async () => {
    try {
      const res = await fetch('/api/menu')
      const data = await res.json()
      setMenuItems(data.items || data.menuItems || [])
    } catch { toast.error('Gagal memuat menu') }
  }

  const fetchRecipe = async (menuItemId: string) => {
    try {
      const res = await fetch(`/api/inventory/recipes/${menuItemId}`)
      const data = await res.json()
      setRecipeIngredients(data.ingredients || [])
      setRecipeTotalCost(data.totalCost || 0)
    } catch { toast.error('Gagal memuat resep') }
  }

  const fetchReports = useCallback(async () => {
    setReportLoading(true)
    try {
      const params = new URLSearchParams()
      if (selectedStoreId) params.set('storeId', selectedStoreId)
      params.set('period', reportPeriod)
      const res = await fetch(`/api/inventory/reports?${params}`)
      const data = await res.json()
      setReportData(data)
    } catch { toast.error('Gagal memuat laporan') }
    finally { setReportLoading(false) }
  }, [selectedStoreId, reportPeriod])

  // --- useEffect triggers ---
  useEffect(() => {
    fetchStores()
    fetchAlerts()
  }, [])

  useEffect(() => {
    if (selectedStoreId || stores.length === 0) {
      fetchIngredients()
      fetchAllIngredients()
    }
  }, [selectedStoreId, fetchIngredients])

  useEffect(() => {
    if (activeTab === 'movements') fetchMovements()
  }, [activeTab, fetchMovements])

  useEffect(() => {
    if (activeTab === 'recipes') fetchMenuItems()
  }, [activeTab])

  useEffect(() => {
    if (activeTab === 'reports') fetchReports()
  }, [activeTab, fetchReports])

  // Debounce ingredient search
  useEffect(() => {
    const timer = setTimeout(() => {
      fetchIngredients(1)
    }, 300)
    return () => clearTimeout(timer)
  }, [ingredientSearch, fetchIngredients])

  // --- Handle functions ---
  const handleSaveIngredient = async () => {
    if (!ingredientForm.name.trim()) { toast.error('Nama bahan wajib diisi'); return }
    setSavingIngredient(true)
    try {
      const url = editingIngredient
        ? `/api/inventory/ingredients/${editingIngredient.id}`
        : '/api/inventory/ingredients'
      const method = editingIngredient ? 'PUT' : 'POST'
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: ingredientForm.name,
          unit: ingredientForm.unit,
          costPerUnit: ingredientForm.costPerUnit ? parseFloat(ingredientForm.costPerUnit) : 0,
        }),
      })
      if (!res.ok) { const d = await res.json(); throw new Error(d.error || 'Gagal menyimpan') }
      toast.success(editingIngredient ? 'Bahan baku diupdate' : 'Bahan baku ditambahkan')
      setShowIngredientModal(false)
      setEditingIngredient(null)
      setIngredientForm({ name: '', unit: 'pcs', costPerUnit: '' })
      fetchIngredients(ingredientPagination.page)
      fetchAllIngredients()
      fetchAlerts()
    } catch (err: any) { toast.error(err.message) }
    finally { setSavingIngredient(false) }
  }

  const handleDeleteIngredient = async (id: string) => {
    if (!confirm('Yakin ingin menghapus bahan baku ini?')) return
    try {
      const res = await fetch(`/api/inventory/ingredients/${id}`, { method: 'DELETE' })
      if (!res.ok) { const d = await res.json(); throw new Error(d.error || 'Gagal menghapus') }
      toast.success('Bahan baku dihapus')
      fetchIngredients(ingredientPagination.page)
      fetchAllIngredients()
      fetchAlerts()
    } catch (err: any) { toast.error(err.message) }
  }

  const handleSaveStockMovement = async () => {
    if (!stockForm.ingredientId) { toast.error('Pilih bahan baku'); return }
    if (!stockForm.quantity || parseFloat(stockForm.quantity) <= 0) { toast.error('Jumlah harus lebih dari 0'); return }
    setSavingStock(true)
    try {
      const res = await fetch('/api/inventory/movements', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ingredientId: stockForm.ingredientId,
          storeId: stockForm.storeId || selectedStoreId,
          type: stockForm.type,
          reason: stockForm.reason,
          quantity: parseFloat(stockForm.quantity),
          costPerUnit: stockForm.costPerUnit ? parseFloat(stockForm.costPerUnit) : undefined,
          notes: stockForm.notes,
        }),
      })
      if (!res.ok) { const d = await res.json(); throw new Error(d.error || 'Gagal menyimpan') }
      toast.success('Mutasi stok berhasil')
      setShowStockModal(false)
      setStockForm({ ingredientId: '', storeId: '', type: 'in', reason: 'purchase', quantity: '', costPerUnit: '', notes: '' })
      fetchIngredients(ingredientPagination.page)
      if (activeTab === 'movements') fetchMovements(movementPagination.page)
      fetchAlerts()
    } catch (err: any) { toast.error(err.message) }
    finally { setSavingStock(false) }
  }

  const handleSaveRecipe = async () => {
    if (!selectedMenuItem) return
    if (!recipeForm.ingredientId) { toast.error('Pilih bahan baku'); return }
    if (!recipeForm.quantity || parseFloat(recipeForm.quantity) <= 0) { toast.error('Jumlah harus lebih dari 0'); return }
    setSavingRecipe(true)
    try {
      const res = await fetch(`/api/inventory/recipes/${selectedMenuItem.id}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ingredientId: recipeForm.ingredientId,
          quantity: parseFloat(recipeForm.quantity),
        }),
      })
      if (!res.ok) { const d = await res.json(); throw new Error(d.error || 'Gagal menyimpan') }
      toast.success('Bahan resep ditambahkan')
      setShowRecipeModal(false)
      setRecipeForm({ ingredientId: '', quantity: '' })
      fetchRecipe(selectedMenuItem.id)
    } catch (err: any) { toast.error(err.message) }
    finally { setSavingRecipe(false) }
  }

  const handleDeleteRecipe = async (ingredientId: string) => {
    if (!selectedMenuItem) return
    if (!confirm('Hapus bahan dari resep ini?')) return
    try {
      const res = await fetch(`/api/inventory/recipes/${selectedMenuItem.id}?ingredientId=${ingredientId}`, { method: 'DELETE' })
      if (!res.ok) { const d = await res.json(); throw new Error(d.error || 'Gagal menghapus') }
      toast.success('Bahan dihapus dari resep')
      fetchRecipe(selectedMenuItem.id)
    } catch (err: any) { toast.error(err.message) }
  }

  const openEditIngredient = (ing: any) => {
    setEditingIngredient(ing)
    setIngredientForm({ name: ing.name, unit: ing.unit, costPerUnit: String(ing.costPerUnit || '') })
    setShowIngredientModal(true)
  }

  const openStockModalForIngredient = (ing: any) => {
    setStockForm({ ingredientId: ing.id, storeId: selectedStoreId, type: 'in', reason: 'purchase', quantity: '', costPerUnit: String(ing.costPerUnit || ''), notes: '' })
    setShowStockModal(true)
  }

  return (
    <div className="space-y-6">
      {/* Alert Banner */}
      {alerts && alerts.totalAlerts > 0 && (
        <div className="bg-orange-50 dark:bg-orange-900/20 border border-orange-200 dark:border-orange-800 rounded-lg p-4 flex items-center gap-3">
          <AlertTriangle className="w-5 h-5 text-orange-500" />
          <span className="text-orange-800 dark:text-orange-300 text-sm">
            {alerts.totalAlerts} bahan baku stok rendah/habis.
          </span>
          <button onClick={() => setActiveTab('ingredients')} className="text-orange-600 dark:text-orange-400 text-sm font-medium underline">
            Lihat Detail
          </button>
        </div>
      )}

      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Manajemen Inventori</h1>
          <p className="text-gray-600 dark:text-gray-300 mt-1">Kelola bahan baku, stok, dan resep menu Anda.</p>
        </div>
      </div>

      {/* Tabs */}
      <div className="border-b border-gray-200 dark:border-gray-700">
        <nav className="flex gap-4 -mb-px">
          {tabs.map(tab => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`py-3 px-1 text-sm font-medium border-b-2 transition-colors ${
                activeTab === tab.id
                  ? 'border-primary-500 text-primary-600 dark:text-primary-400'
                  : 'border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
              }`}
            >
              {tab.label}
            </button>
          ))}
        </nav>
      </div>

      {/* Tab content */}
      {activeTab === 'ingredients' && (
        <div className="space-y-4">
          {/* Filters & Actions */}
          <div className="card">
            <div className="flex flex-wrap gap-3 items-center">
              {stores.length > 1 && (
                <select
                  className="input-field w-auto dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                  value={selectedStoreId}
                  onChange={(e) => setSelectedStoreId(e.target.value)}
                >
                  {stores.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
                </select>
              )}
              <div className="relative flex-1 min-w-[200px]">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 dark:text-gray-500" />
                <input
                  type="text"
                  placeholder="Cari bahan baku..."
                  className="input-field pl-10 dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                  value={ingredientSearch}
                  onChange={(e) => setIngredientSearch(e.target.value)}
                />
              </div>
              <button
                onClick={() => { setEditingIngredient(null); setIngredientForm({ name: '', unit: 'pcs', costPerUnit: '' }); setShowIngredientModal(true) }}
                className="btn-primary flex items-center gap-2"
              >
                <Plus className="w-4 h-4" />
                Tambah Bahan
              </button>
            </div>
          </div>

          {/* Table */}
          <div className="card overflow-x-auto">
            {ingredientLoading ? (
              <div className="flex items-center justify-center py-12">
                <Loader2 className="w-6 h-6 animate-spin text-primary-600" />
              </div>
            ) : ingredients.length === 0 ? (
              <div className="text-center py-12 text-gray-500 dark:text-gray-400">
                <Package className="w-12 h-12 mx-auto mb-3 text-gray-300 dark:text-gray-600" />
                <p className="font-medium">Belum ada bahan baku</p>
                <p className="text-sm mt-1">Tambahkan bahan baku pertama Anda.</p>
              </div>
            ) : (
              <>
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b border-gray-200 dark:border-gray-700">
                      <th className="text-left py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Nama</th>
                      <th className="text-left py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Satuan</th>
                      <th className="text-right py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Harga/Unit</th>
                      <th className="text-right py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Stok Saat Ini</th>
                      <th className="text-right py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Stok Minimum</th>
                      <th className="text-center py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Status</th>
                      <th className="text-right py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Aksi</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-100 dark:divide-gray-700">
                    {ingredients.map((ing) => {
                      const status = getStockStatus(ing.currentStock ?? 0, ing.minStock ?? 0)
                      return (
                        <tr key={ing.id} className="hover:bg-gray-50 dark:hover:bg-gray-700/50">
                          <td className="py-3 px-3 font-medium text-gray-900 dark:text-white">{ing.name}</td>
                          <td className="py-3 px-3 text-gray-600 dark:text-gray-300">{ing.unit}</td>
                          <td className="py-3 px-3 text-right text-gray-600 dark:text-gray-300">{formatCurrency(ing.costPerUnit || 0)}</td>
                          <td className="py-3 px-3 text-right text-gray-900 dark:text-white font-medium">{ing.currentStock ?? 0}</td>
                          <td className="py-3 px-3 text-right text-gray-600 dark:text-gray-300">{ing.minStock ?? 0}</td>
                          <td className="py-3 px-3 text-center">
                            <span className={`inline-flex px-2 py-0.5 rounded-full text-xs font-medium ${status.color}`}>
                              {status.label}
                            </span>
                          </td>
                          <td className="py-3 px-3 text-right">
                            <div className="flex items-center justify-end gap-1">
                              <button onClick={() => openEditIngredient(ing)} className="btn-ghost p-1.5" title="Edit">
                                <Pencil className="w-4 h-4" />
                              </button>
                              <button onClick={() => openStockModalForIngredient(ing)} className="btn-ghost p-1.5" title="Atur Stok">
                                <PackagePlus className="w-4 h-4" />
                              </button>
                              <button onClick={() => handleDeleteIngredient(ing.id)} className="btn-ghost p-1.5 text-red-500 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300" title="Hapus">
                                <Trash2 className="w-4 h-4" />
                              </button>
                            </div>
                          </td>
                        </tr>
                      )
                    })}
                  </tbody>
                </table>
                <Pagination
                  pagination={ingredientPagination}
                  onPageChange={(page) => fetchIngredients(page)}
                  itemLabel="bahan"
                />
              </>
            )}
          </div>
        </div>
      )}

      {activeTab === 'movements' && (
        <div className="space-y-4">
          {/* Filters */}
          <div className="card">
            <div className="flex flex-wrap gap-3 items-center">
              <select
                className="input-field w-auto dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                value={movementFilters.storeId}
                onChange={(e) => setMovementFilters(f => ({ ...f, storeId: e.target.value }))}
              >
                <option value="">Semua Cabang</option>
                {stores.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
              </select>
              <select
                className="input-field w-auto dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                value={movementFilters.type}
                onChange={(e) => setMovementFilters(f => ({ ...f, type: e.target.value }))}
              >
                <option value="">Semua Tipe</option>
                <option value="in">Masuk</option>
                <option value="out">Keluar</option>
              </select>
              <select
                className="input-field w-auto dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                value={movementFilters.reason}
                onChange={(e) => setMovementFilters(f => ({ ...f, reason: e.target.value }))}
              >
                <option value="">Semua Alasan</option>
                {Object.entries(STOCK_MOVEMENT_REASONS).map(([k, v]) => (
                  <option key={k} value={k}>{v.label}</option>
                ))}
              </select>
              <div className="flex-1" />
              <button
                onClick={() => { setStockForm({ ingredientId: '', storeId: selectedStoreId, type: 'in', reason: 'purchase', quantity: '', costPerUnit: '', notes: '' }); setShowStockModal(true) }}
                className="btn-primary flex items-center gap-2"
              >
                <Plus className="w-4 h-4" />
                Tambah Mutasi
              </button>
            </div>
          </div>

          {/* Table */}
          <div className="card overflow-x-auto">
            {movementLoading ? (
              <div className="flex items-center justify-center py-12">
                <Loader2 className="w-6 h-6 animate-spin text-primary-600" />
              </div>
            ) : movements.length === 0 ? (
              <div className="text-center py-12 text-gray-500 dark:text-gray-400">
                <ArrowDownCircle className="w-12 h-12 mx-auto mb-3 text-gray-300 dark:text-gray-600" />
                <p className="font-medium">Belum ada mutasi stok</p>
                <p className="text-sm mt-1">Tambahkan mutasi stok pertama Anda.</p>
              </div>
            ) : (
              <>
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b border-gray-200 dark:border-gray-700">
                      <th className="text-left py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Tanggal</th>
                      <th className="text-left py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Bahan</th>
                      <th className="text-left py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Cabang</th>
                      <th className="text-center py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Tipe</th>
                      <th className="text-left py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Alasan</th>
                      <th className="text-right py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Jumlah</th>
                      <th className="text-left py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Catatan</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-100 dark:divide-gray-700">
                    {movements.map((mv) => {
                      const typeInfo = STOCK_MOVEMENT_TYPES[mv.type] || { label: mv.type, color: 'bg-gray-100 text-gray-800' }
                      const reasonInfo = STOCK_MOVEMENT_REASONS[mv.reason] || { label: mv.reason }
                      return (
                        <tr key={mv.id} className="hover:bg-gray-50 dark:hover:bg-gray-700/50">
                          <td className="py-3 px-3 text-gray-600 dark:text-gray-300 whitespace-nowrap">{formatDate(mv.createdAt)}</td>
                          <td className="py-3 px-3 font-medium text-gray-900 dark:text-white">{mv.ingredient?.name || '-'}</td>
                          <td className="py-3 px-3 text-gray-600 dark:text-gray-300">{mv.store?.name || '-'}</td>
                          <td className="py-3 px-3 text-center">
                            <span className={`inline-flex px-2 py-0.5 rounded-full text-xs font-medium ${typeInfo.color}`}>
                              {typeInfo.label}
                            </span>
                          </td>
                          <td className="py-3 px-3 text-gray-600 dark:text-gray-300">{reasonInfo.label}</td>
                          <td className="py-3 px-3 text-right font-medium text-gray-900 dark:text-white">{mv.quantity}</td>
                          <td className="py-3 px-3 text-gray-500 dark:text-gray-400 max-w-[200px] truncate">{mv.notes || '-'}</td>
                        </tr>
                      )
                    })}
                  </tbody>
                </table>
                <Pagination
                  pagination={movementPagination}
                  onPageChange={(page) => fetchMovements(page)}
                  itemLabel="mutasi"
                />
              </>
            )}
          </div>
        </div>
      )}

      {activeTab === 'recipes' && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Left: Menu list */}
          <div className="lg:col-span-1">
            <div className="card">
              <h3 className="font-semibold text-gray-900 dark:text-white mb-3">Daftar Menu</h3>
              <div className="space-y-1 max-h-[500px] overflow-y-auto">
                {menuItems.length === 0 ? (
                  <p className="text-sm text-gray-500 dark:text-gray-400 py-4 text-center">Belum ada menu.</p>
                ) : (
                  menuItems.map((item) => (
                    <button
                      key={item.id}
                      onClick={() => { setSelectedMenuItem(item); fetchRecipe(item.id) }}
                      className={`w-full text-left px-3 py-2.5 rounded-lg text-sm transition-colors ${
                        selectedMenuItem?.id === item.id
                          ? 'bg-primary-50 text-primary-700 dark:bg-primary-900/30 dark:text-primary-400'
                          : 'text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700'
                      }`}
                    >
                      <div className="flex items-center justify-between">
                        <span className="font-medium truncate">{item.name}</span>
                        {item._count?.recipeIngredients != null && (
                          <span className="text-xs bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 px-1.5 py-0.5 rounded-full">
                            {item._count.recipeIngredients}
                          </span>
                        )}
                      </div>
                    </button>
                  ))
                )}
              </div>
            </div>
          </div>

          {/* Right: Recipe detail */}
          <div className="lg:col-span-2">
            <div className="card">
              {!selectedMenuItem ? (
                <div className="text-center py-12 text-gray-500 dark:text-gray-400">
                  <ChefHat className="w-12 h-12 mx-auto mb-3 text-gray-300 dark:text-gray-600" />
                  <p className="font-medium">Pilih menu untuk melihat resep</p>
                  <p className="text-sm mt-1">Klik menu di sebelah kiri untuk melihat dan mengelola resep.</p>
                </div>
              ) : (
                <>
                  <div className="flex items-center justify-between mb-4">
                    <div>
                      <h3 className="font-semibold text-gray-900 dark:text-white">{selectedMenuItem.name}</h3>
                      <p className="text-sm text-gray-500 dark:text-gray-400">Resep & Bahan Baku</p>
                    </div>
                    <button
                      onClick={() => { setRecipeForm({ ingredientId: '', quantity: '' }); setShowRecipeModal(true) }}
                      className="btn-primary flex items-center gap-2 text-sm"
                    >
                      <Plus className="w-4 h-4" />
                      Tambah Bahan
                    </button>
                  </div>

                  {recipeIngredients.length === 0 ? (
                    <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                      <p className="text-sm">Belum ada bahan dalam resep ini.</p>
                    </div>
                  ) : (
                    <>
                      <table className="w-full text-sm">
                        <thead>
                          <tr className="border-b border-gray-200 dark:border-gray-700">
                            <th className="text-left py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Bahan</th>
                            <th className="text-right py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Jumlah per Porsi</th>
                            <th className="text-left py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Satuan</th>
                            <th className="text-right py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Biaya per Porsi</th>
                            <th className="text-right py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Aksi</th>
                          </tr>
                        </thead>
                        <tbody className="divide-y divide-gray-100 dark:divide-gray-700">
                          {recipeIngredients.map((ri) => (
                            <tr key={ri.ingredientId || ri.id} className="hover:bg-gray-50 dark:hover:bg-gray-700/50">
                              <td className="py-3 px-3 font-medium text-gray-900 dark:text-white">{ri.ingredient?.name || ri.name || '-'}</td>
                              <td className="py-3 px-3 text-right text-gray-900 dark:text-white">{ri.quantity}</td>
                              <td className="py-3 px-3 text-gray-600 dark:text-gray-300">{ri.ingredient?.unit || ri.unit || '-'}</td>
                              <td className="py-3 px-3 text-right text-gray-600 dark:text-gray-300">{formatCurrency(ri.costPerServing || (ri.quantity * (ri.ingredient?.costPerUnit || 0)))}</td>
                              <td className="py-3 px-3 text-right">
                                <button
                                  onClick={() => handleDeleteRecipe(ri.ingredientId || ri.id)}
                                  className="btn-ghost p-1.5 text-red-500 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300"
                                  title="Hapus"
                                >
                                  <Trash2 className="w-4 h-4" />
                                </button>
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                      <div className="flex justify-end mt-3 pt-3 border-t border-gray-200 dark:border-gray-700">
                        <div className="text-sm">
                          <span className="text-gray-500 dark:text-gray-400">Total biaya per porsi: </span>
                          <span className="font-semibold text-gray-900 dark:text-white">{formatCurrency(recipeTotalCost)}</span>
                        </div>
                      </div>
                    </>
                  )}
                </>
              )}
            </div>
          </div>
        </div>
      )}

      {activeTab === 'reports' && (
        <div className="space-y-6">
          {/* Filters */}
          <div className="card">
            <div className="flex flex-wrap gap-3 items-center">
              <select
                className="input-field w-auto dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                value={selectedStoreId}
                onChange={(e) => setSelectedStoreId(e.target.value)}
              >
                <option value="">Semua Cabang</option>
                {stores.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
              </select>
              <select
                className="input-field w-auto dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                value={reportPeriod}
                onChange={(e) => setReportPeriod(e.target.value)}
              >
                <option value="7d">7 Hari</option>
                <option value="30d">30 Hari</option>
                <option value="90d">90 Hari</option>
              </select>
            </div>
          </div>

          {reportLoading ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="w-6 h-6 animate-spin text-primary-600" />
            </div>
          ) : reportData ? (
            <>
              {/* Summary Cards */}
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                <div className="card">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 bg-green-100 dark:bg-green-900/30 rounded-lg flex items-center justify-center flex-shrink-0">
                      <DollarSign className="w-5 h-5 text-green-600 dark:text-green-400" />
                    </div>
                    <div>
                      <p className="text-sm text-gray-500 dark:text-gray-400">Nilai Stok Total</p>
                      <p className="text-lg font-bold text-gray-900 dark:text-white">{formatCurrency(reportData.totalStockValue || 0)}</p>
                    </div>
                  </div>
                </div>
                <div className="card">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 bg-blue-100 dark:bg-blue-900/30 rounded-lg flex items-center justify-center flex-shrink-0">
                      <Package className="w-5 h-5 text-blue-600 dark:text-blue-400" />
                    </div>
                    <div>
                      <p className="text-sm text-gray-500 dark:text-gray-400">Bahan Baku Aktif</p>
                      <p className="text-lg font-bold text-gray-900 dark:text-white">{reportData.activeIngredients || 0}</p>
                    </div>
                  </div>
                </div>
                <div className="card">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 bg-orange-100 dark:bg-orange-900/30 rounded-lg flex items-center justify-center flex-shrink-0">
                      <AlertTriangle className="w-5 h-5 text-orange-600 dark:text-orange-400" />
                    </div>
                    <div>
                      <p className="text-sm text-gray-500 dark:text-gray-400">Stok Rendah</p>
                      <p className="text-lg font-bold text-gray-900 dark:text-white">{reportData.lowStockCount || 0}</p>
                    </div>
                  </div>
                </div>
                <div className="card">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 bg-red-100 dark:bg-red-900/30 rounded-lg flex items-center justify-center flex-shrink-0">
                      <XCircle className="w-5 h-5 text-red-600 dark:text-red-400" />
                    </div>
                    <div>
                      <p className="text-sm text-gray-500 dark:text-gray-400">Stok Habis</p>
                      <p className="text-lg font-bold text-gray-900 dark:text-white">{reportData.outOfStockCount || 0}</p>
                    </div>
                  </div>
                </div>
              </div>

              {/* Stock Status Table */}
              {reportData.stockStatus && reportData.stockStatus.length > 0 && (
                <div className="card overflow-x-auto">
                  <h3 className="font-semibold text-gray-900 dark:text-white mb-4">Status Stok</h3>
                  <table className="w-full text-sm">
                    <thead>
                      <tr className="border-b border-gray-200 dark:border-gray-700">
                        <th className="text-left py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Bahan</th>
                        <th className="text-left py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Satuan</th>
                        <th className="text-right py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Stok</th>
                        <th className="text-right py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Min. Stok</th>
                        <th className="text-right py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Nilai</th>
                        <th className="text-center py-3 px-3 font-medium text-gray-500 dark:text-gray-400">Status</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-100 dark:divide-gray-700">
                      {reportData.stockStatus.map((item: any) => {
                        const status = getStockStatus(item.currentStock ?? 0, item.minStock ?? 0)
                        return (
                          <tr key={item.id} className="hover:bg-gray-50 dark:hover:bg-gray-700/50">
                            <td className="py-3 px-3 font-medium text-gray-900 dark:text-white">{item.name}</td>
                            <td className="py-3 px-3 text-gray-600 dark:text-gray-300">{item.unit}</td>
                            <td className="py-3 px-3 text-right text-gray-900 dark:text-white font-medium">{item.currentStock ?? 0}</td>
                            <td className="py-3 px-3 text-right text-gray-600 dark:text-gray-300">{item.minStock ?? 0}</td>
                            <td className="py-3 px-3 text-right text-gray-600 dark:text-gray-300">{formatCurrency(item.stockValue || 0)}</td>
                            <td className="py-3 px-3 text-center">
                              <span className={`inline-flex px-2 py-0.5 rounded-full text-xs font-medium ${status.color}`}>
                                {status.label}
                              </span>
                            </td>
                          </tr>
                        )
                      })}
                    </tbody>
                  </table>
                </div>
              )}

              {/* Top Used Ingredients */}
              {reportData.topUsed && reportData.topUsed.length > 0 && (
                <div className="card">
                  <h3 className="font-semibold text-gray-900 dark:text-white mb-4">Bahan Baku Paling Banyak Digunakan</h3>
                  <div className="space-y-3">
                    {reportData.topUsed.slice(0, 10).map((item: any, idx: number) => (
                      <div key={item.id || idx} className="flex items-center justify-between py-2">
                        <div className="flex items-center gap-3">
                          <span className="w-6 h-6 bg-gray-100 dark:bg-gray-700 rounded-full flex items-center justify-center text-xs font-medium text-gray-600 dark:text-gray-300">
                            {idx + 1}
                          </span>
                          <span className="text-sm font-medium text-gray-900 dark:text-white">{item.name}</span>
                        </div>
                        <span className="text-sm text-gray-500 dark:text-gray-400">
                          {item.totalUsed || 0} {item.unit}
                        </span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </>
          ) : (
            <div className="card text-center py-12 text-gray-500 dark:text-gray-400">
              <p className="font-medium">Tidak ada data laporan</p>
            </div>
          )}
        </div>
      )}

      {/* Ingredient Modal */}
      {showIngredientModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div className="fixed inset-0 bg-black/50" onClick={() => setShowIngredientModal(false)} />
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl w-full max-w-md relative z-10">
            <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                {editingIngredient ? 'Edit Bahan Baku' : 'Tambah Bahan Baku'}
              </h3>
              <button onClick={() => setShowIngredientModal(false)} className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200">
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-4 space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">Nama Bahan</label>
                <input
                  type="text"
                  className="input-field dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                  placeholder="Mis: Beras, Ayam, Minyak Goreng"
                  value={ingredientForm.name}
                  onChange={(e) => setIngredientForm(f => ({ ...f, name: e.target.value }))}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">Satuan</label>
                <select
                  className="input-field dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                  value={ingredientForm.unit}
                  onChange={(e) => setIngredientForm(f => ({ ...f, unit: e.target.value }))}
                >
                  {INGREDIENT_UNITS.map(u => <option key={u} value={u}>{u}</option>)}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">Harga per Unit (Rp)</label>
                <input
                  type="number"
                  className="input-field dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                  placeholder="0"
                  min="0"
                  value={ingredientForm.costPerUnit}
                  onChange={(e) => setIngredientForm(f => ({ ...f, costPerUnit: e.target.value }))}
                />
              </div>
            </div>
            <div className="flex justify-end gap-3 p-4 border-t border-gray-200 dark:border-gray-700">
              <button onClick={() => setShowIngredientModal(false)} className="btn-secondary">Batal</button>
              <button onClick={handleSaveIngredient} disabled={savingIngredient} className="btn-primary flex items-center gap-2">
                {savingIngredient && <Loader2 className="w-4 h-4 animate-spin" />}
                {editingIngredient ? 'Simpan' : 'Tambah'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Stock Movement Modal */}
      {showStockModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div className="fixed inset-0 bg-black/50" onClick={() => setShowStockModal(false)} />
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl w-full max-w-md relative z-10">
            <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white">Mutasi Stok</h3>
              <button onClick={() => setShowStockModal(false)} className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200">
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-4 space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">Bahan Baku</label>
                <select
                  className="input-field dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                  value={stockForm.ingredientId}
                  onChange={(e) => setStockForm(f => ({ ...f, ingredientId: e.target.value }))}
                >
                  <option value="">Pilih bahan baku</option>
                  {allIngredients.map(i => <option key={i.id} value={i.id}>{i.name} ({i.unit})</option>)}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">Cabang</label>
                <select
                  className="input-field dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                  value={stockForm.storeId}
                  onChange={(e) => setStockForm(f => ({ ...f, storeId: e.target.value }))}
                >
                  <option value="">Pilih cabang</option>
                  {stores.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-2">Tipe</label>
                <div className="flex gap-4">
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="radio"
                      name="stockType"
                      value="in"
                      checked={stockForm.type === 'in'}
                      onChange={() => setStockForm(f => ({ ...f, type: 'in', reason: 'purchase' }))}
                      className="text-primary-600 focus:ring-primary-500"
                    />
                    <span className="text-sm text-gray-700 dark:text-gray-200">Masuk</span>
                  </label>
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="radio"
                      name="stockType"
                      value="out"
                      checked={stockForm.type === 'out'}
                      onChange={() => setStockForm(f => ({ ...f, type: 'out', reason: 'usage' }))}
                      className="text-primary-600 focus:ring-primary-500"
                    />
                    <span className="text-sm text-gray-700 dark:text-gray-200">Keluar</span>
                  </label>
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">Alasan</label>
                <select
                  className="input-field dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                  value={stockForm.reason}
                  onChange={(e) => setStockForm(f => ({ ...f, reason: e.target.value }))}
                >
                  {Object.entries(STOCK_MOVEMENT_REASONS).map(([k, v]) => (
                    <option key={k} value={k}>{v.label}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">Jumlah</label>
                <input
                  type="number"
                  className="input-field dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                  placeholder="0"
                  min="0"
                  step="any"
                  value={stockForm.quantity}
                  onChange={(e) => setStockForm(f => ({ ...f, quantity: e.target.value }))}
                />
              </div>
              {stockForm.type === 'in' && stockForm.reason === 'purchase' && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">Harga per Unit (Rp)</label>
                  <input
                    type="number"
                    className="input-field dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                    placeholder="0"
                    min="0"
                    value={stockForm.costPerUnit}
                    onChange={(e) => setStockForm(f => ({ ...f, costPerUnit: e.target.value }))}
                  />
                </div>
              )}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">Catatan</label>
                <textarea
                  className="input-field dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                  rows={2}
                  placeholder="Catatan tambahan (opsional)"
                  value={stockForm.notes}
                  onChange={(e) => setStockForm(f => ({ ...f, notes: e.target.value }))}
                />
              </div>
            </div>
            <div className="flex justify-end gap-3 p-4 border-t border-gray-200 dark:border-gray-700">
              <button onClick={() => setShowStockModal(false)} className="btn-secondary">Batal</button>
              <button onClick={handleSaveStockMovement} disabled={savingStock} className="btn-primary flex items-center gap-2">
                {savingStock && <Loader2 className="w-4 h-4 animate-spin" />}
                Simpan
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Recipe Modal */}
      {showRecipeModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div className="fixed inset-0 bg-black/50" onClick={() => setShowRecipeModal(false)} />
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl w-full max-w-md relative z-10">
            <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white">Tambah Bahan ke Resep</h3>
              <button onClick={() => setShowRecipeModal(false)} className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200">
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-4 space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">Bahan Baku</label>
                <select
                  className="input-field dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                  value={recipeForm.ingredientId}
                  onChange={(e) => setRecipeForm(f => ({ ...f, ingredientId: e.target.value }))}
                >
                  <option value="">Pilih bahan baku</option>
                  {allIngredients.map(i => <option key={i.id} value={i.id}>{i.name} ({i.unit})</option>)}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1">Jumlah per Porsi</label>
                <input
                  type="number"
                  className="input-field dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                  placeholder="0"
                  min="0"
                  step="any"
                  value={recipeForm.quantity}
                  onChange={(e) => setRecipeForm(f => ({ ...f, quantity: e.target.value }))}
                />
              </div>
            </div>
            <div className="flex justify-end gap-3 p-4 border-t border-gray-200 dark:border-gray-700">
              <button onClick={() => setShowRecipeModal(false)} className="btn-secondary">Batal</button>
              <button onClick={handleSaveRecipe} disabled={savingRecipe} className="btn-primary flex items-center gap-2">
                {savingRecipe && <Loader2 className="w-4 h-4 animate-spin" />}
                Tambah
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
