'use client';

import { useState } from 'react';
import { PackageX, RefreshCw, CheckCircle2 } from 'lucide-react';
import { toast } from 'sonner';
import { restockMenuItem, type LowStockItem } from '@client/api/menu';
import { useLanguage } from '@client/contexts/LanguageContext';

interface LowStockAlertsProps {
  items: LowStockItem[];
  loading: boolean;
  onRestocked: () => void;
}

export default function LowStockAlerts({ items, loading, onRestocked }: LowStockAlertsProps) {
  const { t } = useLanguage();
  const [busy, setBusy] = useState<Record<string, boolean>>({});

  const handleRestock = async (item: LowStockItem) => {
    let target: number | undefined;
    if (item.daily_reset_count == null) {
      const raw = window.prompt(
        t(
          'dashboard.lowStock.promptTarget',
          `Enter the new stock count for ${item.name}:`,
          { name: item.name }
        ),
        '0'
      );
      if (raw == null) return;
      const parsed = Number(raw);
      if (!Number.isFinite(parsed) || parsed < 0 || !Number.isInteger(parsed)) {
        toast.error(
          t('dashboard.lowStock.invalidTarget', 'Please enter a non-negative whole number.')
        );
        return;
      }
      target = parsed;
    }

    setBusy(prev => ({ ...prev, [item.id]: true }));
    try {
      await restockMenuItem(item.id, target);
      toast.success(
        t('dashboard.lowStock.restocked', `${item.name} restocked`, { name: item.name })
      );
      onRestocked();
    } catch (e) {
      const msg = e instanceof Error ? e.message : 'Failed to restock';
      toast.error(msg);
    } finally {
      setBusy(prev => ({ ...prev, [item.id]: false }));
    }
  };

  if (loading) {
    return (
      <div className="card p-5">
        <div className="flex items-center gap-2 mb-3">
          <PackageX size={16} style={{ color: 'hsl(var(--warning))' }} />
          <p className="section-label">
            {t('dashboard.lowStock.title', 'Low-Stock Items')}
          </p>
        </div>
        <div className="space-y-3">
          {[1, 2].map(i => (
            <div
              key={i}
              className="rounded-xl p-4 animate-pulse"
              style={{ backgroundColor: 'hsl(var(--muted))' }}
            >
              <div className="h-4 w-32 bg-gray-200 rounded mb-2" />
              <div className="h-3 w-48 bg-gray-200 rounded" />
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (items.length === 0) {
    return (
      <div className="card p-5">
        <div className="flex items-center gap-2 mb-3">
          <PackageX size={16} style={{ color: 'hsl(var(--muted-foreground))' }} />
          <p className="section-label">
            {t('dashboard.lowStock.title', 'Low-Stock Items')}
          </p>
        </div>
        <div className="flex flex-col items-center justify-center py-6 text-center">
          <div
            className="w-10 h-10 rounded-full flex items-center justify-center mb-2"
            style={{ backgroundColor: 'hsl(var(--success-bg))', color: 'hsl(var(--success))' }}
          >
            <CheckCircle2 size={18} />
          </div>
          <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>
            {t('dashboard.lowStock.empty', 'Every item is fully stocked')}
          </p>
          <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>
            {t(
              'dashboard.lowStock.emptyHint',
              'Items at or below their threshold will appear here.'
            )}
          </p>
        </div>
      </div>
    );
  }

  return (
    <div
      className="card p-5"
      style={{
        borderColor: 'hsl(var(--warning-border))',
        backgroundColor: 'hsl(var(--warning-bg))',
      }}
    >
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2">
          <PackageX size={16} style={{ color: 'hsl(var(--warning))' }} />
          <p className="text-sm font-semibold" style={{ color: 'hsl(var(--warning))' }}>
            {t('dashboard.lowStock.title', 'Low-Stock Items')}
          </p>
        </div>
        <span className="badge badge-warning">
          {t('dashboard.lowStock.count', `${items.length} low`, { count: items.length })}
        </span>
      </div>

      <div className="space-y-3">
        {items.map(item => {
          const stock = item.stock_count ?? 0;
          const isOut = item.auto_disabled_at_zero || stock <= 0;
          const target = item.daily_reset_count;
          return (
            <div
              key={item.id}
              className="rounded-xl p-4 fade-in"
              style={{
                backgroundColor: 'hsl(var(--surface))',
                border: `1px solid hsl(var(--${isOut ? 'danger' : 'warning'}-border))`,
              }}
            >
              <div className="flex items-start justify-between gap-2 mb-2">
                <div className="min-w-0 flex-1">
                  <p
                    className="text-sm font-semibold truncate"
                    style={{ color: 'hsl(var(--foreground))' }}
                  >
                    {item.name}
                  </p>
                  {item.category_name && (
                    <p
                      className="text-xs truncate"
                      style={{ color: 'hsl(var(--muted-foreground))' }}
                    >
                      {item.category_name}
                    </p>
                  )}
                </div>
                {isOut && (
                  <span className="badge badge-danger shrink-0">
                    {t('dashboard.lowStock.soldOut', 'Sold out')}
                  </span>
                )}
              </div>

              <div
                className="flex items-center gap-3 text-xs mb-3"
                style={{ color: 'hsl(var(--foreground-secondary))' }}
              >
                <span>
                  {t('dashboard.lowStock.stockLabel', 'Stock')}:{' '}
                  <span className="font-mono font-semibold">{stock}</span>
                </span>
                {item.low_stock_threshold != null && (
                  <span>
                    {t('dashboard.lowStock.thresholdLabel', 'Threshold')}:{' '}
                    <span className="font-mono">{item.low_stock_threshold}</span>
                  </span>
                )}
                {target != null && (
                  <span>
                    {t('dashboard.lowStock.resetLabel', 'Daily reset')}:{' '}
                    <span className="font-mono">{target}</span>
                  </span>
                )}
              </div>

              <div className="flex items-center justify-end">
                <button
                  type="button"
                  onClick={() => handleRestock(item)}
                  disabled={!!busy[item.id]}
                  className="btn-primary text-xs px-3 py-1.5 flex items-center gap-1 disabled:opacity-60"
                  title={
                    target != null
                      ? t(
                          'dashboard.lowStock.restockToTarget',
                          `Restock to daily reset target (${target})`,
                          { target }
                        )
                      : t('dashboard.lowStock.restockPrompt', 'Restock (enter quantity)')
                  }
                >
                  <RefreshCw size={12} />
                  {busy[item.id]
                    ? t('dashboard.lowStock.restocking', 'Restocking…')
                    : target != null
                      ? t('dashboard.lowStock.restockTo', `Restock to ${target}`, { target })
                      : t('dashboard.lowStock.restock', 'Restock')}
                </button>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
