'use client';

import { useState, useEffect, useCallback } from 'react';
import { listProducts, deleteProduct, createProduct, updateProduct } from '@/services/products';
import { ProductCategory, type ServingUnit } from '@meshitrack/shared';
import type { z } from 'zod/v4';
import type { ProductResponseSchema, CreateProductInput } from '@meshitrack/shared';
import { ProductModal } from './ProductModal';
import { ImportDialog } from './ImportDialog';

type Product = z.infer<typeof ProductResponseSchema>;

const CATEGORY_OPTIONS = Object.values(ProductCategory);

const SERVING_UNIT_LABELS: Record<string, string> = {
  g: 'g',
  ml: 'ml',
  piece: 'pc',
  slice: 'sl',
};

export function ProductList({ householdId }: { householdId: string }) {
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [search, setSearch] = useState('');
  const [category, setCategory] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');
  const [addModalOpen, setAddModalOpen] = useState(false);
  const [importDialogOpen, setImportDialogOpen] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);

  // Debounce search input
  useEffect(() => {
    const timer = setTimeout(() => setDebouncedSearch(search), 300);
    return () => clearTimeout(timer);
  }, [search]);

  const fetchProducts = useCallback(async () => {
    if (!householdId) return;
    setLoading(true);
    setError('');
    try {
      const result = await listProducts(householdId, {
        q: debouncedSearch || undefined,
        category: category || undefined,
        limit: 50,
      });
      setProducts(result.data);
    } catch (err) {
      if (err instanceof Error) setError(err.message);
    } finally {
      setLoading(false);
    }
  }, [householdId, debouncedSearch, category]);

  useEffect(() => {
    fetchProducts();
  }, [fetchProducts]);

  async function handleDelete(id: string, name: string) {
    if (!confirm(`Delete "${name}"?`)) return;
    try {
      await deleteProduct(householdId, id);
      setProducts((prev) => prev.filter((p) => p._id !== id));
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to delete');
    }
  }

  async function handleCreate(data: CreateProductInput) {
    await createProduct(householdId, data);
    await fetchProducts();
  }

  async function handleEdit(data: CreateProductInput) {
    if (!editingProduct) return;
    await updateProduct(householdId, editingProduct._id, data);
    await fetchProducts();
  }

  return (
    <div style={{ padding: '28px 32px 56px', maxWidth: 1200 }}>
      {/* Filters */}
      <div
        style={{
          display: 'flex',
          gap: 12,
          marginBottom: 24,
          alignItems: 'center',
          flexWrap: 'wrap',
        }}
      >
        <input
          type="text"
          placeholder="Search products..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          style={{
            padding: '8px 12px',
            borderRadius: 'var(--r-md)',
            border: '1px solid var(--border)',
            background: 'var(--bg-elev)',
            color: 'var(--ink)',
            fontSize: 14,
            minWidth: 240,
          }}
        />
        <select
          value={category}
          onChange={(e) => setCategory(e.target.value)}
          style={{
            padding: '8px 12px',
            borderRadius: 'var(--r-md)',
            border: '1px solid var(--border)',
            background: 'var(--bg-elev)',
            color: 'var(--ink)',
            fontSize: 14,
          }}
        >
          <option value="">All categories</option>
          {CATEGORY_OPTIONS.map((cat) => (
            <option key={cat} value={cat}>
              {cat.charAt(0).toUpperCase() + cat.slice(1).replace(/_/g, ' ')}
            </option>
          ))}
        </select>
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
          <button
            type="button"
            onClick={() => setImportDialogOpen(true)}
            style={{
              padding: '8px 14px',
              borderRadius: 'var(--r-md)',
              border: '1px solid var(--border)',
              background: 'var(--bg-elev)',
              color: 'var(--ink)',
              fontSize: 14,
              cursor: 'pointer',
            }}
          >
            Import
          </button>
          <button
            type="button"
            onClick={() => setAddModalOpen(true)}
            style={{
              padding: '8px 14px',
              borderRadius: 'var(--r-md)',
              border: 'none',
              background: 'var(--brand)',
              color: '#fff',
              fontSize: 14,
              fontWeight: 500,
              cursor: 'pointer',
            }}
          >
            Add Product
          </button>
        </div>
      </div>

      {error && <p style={{ color: 'var(--danger)', marginBottom: 16, fontSize: 14 }}>{error}</p>}

      {loading ? (
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
            gap: 16,
          }}
        >
          {[...Array(6)].map((_, i) => (
            <div
              key={i}
              style={{
                height: 120,
                background: 'var(--bg-elev)',
                borderRadius: 'var(--r-md)',
                opacity: 0.5,
              }}
            />
          ))}
        </div>
      ) : products.length === 0 ? (
        <div
          style={{
            textAlign: 'center',
            padding: '64px 24px',
            color: 'var(--ink-muted)',
            fontSize: 14,
          }}
        >
          <p>No products yet. Add your first product to get started.</p>
        </div>
      ) : (
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
            gap: 16,
          }}
        >
          {products.map((product) => (
            <ProductCard
              key={product._id}
              product={product}
              onDelete={() => handleDelete(product._id, product.name)}
              onEdit={() => setEditingProduct(product)}
            />
          ))}
        </div>
      )}

      <ProductModal
        open={addModalOpen}
        onClose={() => setAddModalOpen(false)}
        onSave={handleCreate}
        householdId={householdId}
        title="Add Product"
      />

      <ProductModal
        open={editingProduct !== null}
        onClose={() => setEditingProduct(null)}
        onSave={handleEdit}
        householdId={householdId}
        initial={
          editingProduct
            ? {
                name: editingProduct.name,
                brand: editingProduct.brand,
                barcode: editingProduct.barcode,
                category: editingProduct.category as ProductCategory,
                servingSize: editingProduct.servingSize,
                servingUnit: editingProduct.servingUnit as ServingUnit,
                densityGPerMl: editingProduct.densityGPerMl,
                nutrition: editingProduct.nutrition,
                tags: editingProduct.tags,
                imageUrl: editingProduct.imageUrl,
              }
            : undefined
        }
        title="Edit Product"
      />

      <ImportDialog
        open={importDialogOpen}
        onClose={() => setImportDialogOpen(false)}
        householdId={householdId}
        onSuccess={fetchProducts}
      />
    </div>
  );
}

function ProductCard({
  product,
  onDelete,
  onEdit,
}: {
  product: Product;
  onDelete: () => void;
  onEdit: () => void;
}) {
  return (
    <div
      style={{
        background: 'var(--bg-elev)',
        border: '1px solid var(--border)',
        borderRadius: 'var(--r-md)',
        padding: 16,
        display: 'flex',
        flexDirection: 'column',
        gap: 8,
      }}
    >
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div>
          <p style={{ fontWeight: 600, fontSize: 14, margin: 0, color: 'var(--ink)' }}>
            {product.name}
          </p>
          {product.brand && (
            <p style={{ fontSize: 12, color: 'var(--ink-muted)', margin: 0 }}>{product.brand}</p>
          )}
        </div>
        <span
          style={{
            fontSize: 11,
            padding: '2px 8px',
            borderRadius: 'var(--r-sm)',
            background: 'var(--brand-soft, #e8f0fe)',
            color: 'var(--brand)',
            textTransform: 'capitalize',
          }}
        >
          {product.category.replace(/_/g, ' ')}
        </span>
      </div>

      <div style={{ display: 'flex', gap: 16, fontSize: 13, color: 'var(--ink-muted)' }}>
        <span>{product.nutrition.calories} kcal</span>
        <span>
          {product.servingSize}
          {SERVING_UNIT_LABELS[product.servingUnit] ?? product.servingUnit}
        </span>
      </div>

      <div style={{ display: 'flex', gap: 8, fontSize: 12, color: 'var(--ink-dim)' }}>
        <span>P: {product.nutrition.protein}g</span>
        <span>C: {product.nutrition.carbs}g</span>
        <span>F: {product.nutrition.fat}g</span>
      </div>

      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 4 }}>
        <button
          onClick={onEdit}
          aria-label="Edit product"
          style={{
            padding: '4px 10px',
            fontSize: 12,
            borderRadius: 'var(--r-sm)',
            border: '1px solid var(--border)',
            background: 'transparent',
            color: 'var(--ink-muted)',
            cursor: 'pointer',
          }}
        >
          Edit
        </button>
        <button
          onClick={onDelete}
          aria-label="Delete product"
          style={{
            padding: '4px 10px',
            fontSize: 12,
            borderRadius: 'var(--r-sm)',
            border: '1px solid var(--danger)',
            background: 'transparent',
            color: 'var(--danger)',
            cursor: 'pointer',
          }}
        >
          Delete
        </button>
      </div>
    </div>
  );
}
