'use client';

import { useState, useEffect } from 'react';
import { ProductCategory, ServingUnit, ProductSource } from '@meshitrack/shared';
import type { CreateProductInput } from '@meshitrack/shared';
import { lookupBarcode } from '@/services/products';

export interface ProductModalProps {
  open: boolean;
  onClose: () => void;
  onSave: (data: CreateProductInput) => Promise<void>;
  householdId: string;
  initial?: Partial<CreateProductInput>;
  title?: string;
}

const CATEGORY_OPTIONS = Object.values(ProductCategory);
const SERVING_UNIT_OPTIONS = Object.values(ServingUnit);

const SERVING_UNIT_LABELS: Record<string, string> = {
  g: 'Grams (g)',
  ml: 'Milliliters (ml)',
  piece: 'Piece',
  slice: 'Slice',
};

export function ProductModal({
  open,
  onClose,
  onSave,
  householdId,
  initial,
  title,
}: ProductModalProps) {
  const [saving, setSaving] = useState(false);
  const [lookingUp, setLookingUp] = useState(false);
  const [error, setError] = useState('');

  const [name, setName] = useState('');
  const [brand, setBrand] = useState('');
  const [barcode, setBarcode] = useState('');
  const [category, setCategory] = useState<ProductCategory>(ProductCategory.OTHER);
  const [servingSize, setServingSize] = useState<number | ''>('');
  const [servingUnit, setServingUnit] = useState<ServingUnit>(ServingUnit.GRAMS);
  const [densityGPerMl, setDensityGPerMl] = useState<number | ''>('');
  const [tags, setTags] = useState('');
  const [imageUrl, setImageUrl] = useState('');

  // Nutrition
  const [calories, setCalories] = useState<number | ''>('');
  const [protein, setProtein] = useState<number | ''>('');
  const [carbs, setCarbs] = useState<number | ''>('');
  const [fat, setFat] = useState<number | ''>('');
  const [fiber, setFiber] = useState<number | ''>('');
  const [sugar, setSugar] = useState<number | ''>('');
  const [sodium, setSodium] = useState<number | ''>('');
  const [saturatedFat, setSaturatedFat] = useState<number | ''>('');
  const [cholesterol, setCholesterol] = useState<number | ''>('');

  useEffect(() => {
    if (open) {
      setName(initial?.name ?? '');
      setBrand(initial?.brand ?? '');
      setBarcode(initial?.barcode ?? '');
      setCategory(initial?.category ?? ProductCategory.OTHER);
      setServingSize(initial?.servingSize ?? '');
      setServingUnit(initial?.servingUnit ?? ServingUnit.GRAMS);
      setDensityGPerMl(initial?.densityGPerMl ?? '');
      setTags(initial?.tags?.join(', ') ?? '');
      setImageUrl(initial?.imageUrl ?? '');
      setCalories(initial?.nutrition?.calories ?? '');
      setProtein(initial?.nutrition?.protein ?? '');
      setCarbs(initial?.nutrition?.carbs ?? '');
      setFat(initial?.nutrition?.fat ?? '');
      setFiber(initial?.nutrition?.fiber ?? '');
      setSugar(initial?.nutrition?.sugar ?? '');
      setSodium(initial?.nutrition?.sodium ?? '');
      setSaturatedFat(initial?.nutrition?.saturatedFat ?? '');
      setCholesterol(initial?.nutrition?.cholesterol ?? '');
      setError('');
      setSaving(false);
    }
  }, [open, initial]);

  if (!open) return null;

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError('');

    if (!name.trim()) {
      setError('Name is required');
      return;
    }
    if (servingSize === '' || servingSize <= 0) {
      setError('Serving size must be a positive number');
      return;
    }
    if (calories === '' || protein === '' || carbs === '' || fat === '') {
      setError('Calories, protein, carbs, and fat are required');
      return;
    }

    const data: CreateProductInput = {
      name: name.trim(),
      category,
      servingSize: Number(servingSize),
      servingUnit,
      nutrition: {
        calories: Number(calories),
        protein: Number(protein),
        carbs: Number(carbs),
        fat: Number(fat),
        ...(fiber !== '' && { fiber: Number(fiber) }),
        ...(sugar !== '' && { sugar: Number(sugar) }),
        ...(sodium !== '' && { sodium: Number(sodium) }),
        ...(saturatedFat !== '' && { saturatedFat: Number(saturatedFat) }),
        ...(cholesterol !== '' && { cholesterol: Number(cholesterol) }),
      },
      tags: tags
        .split(',')
        .map((t) => t.trim())
        .filter(Boolean),
      source: ProductSource.MANUAL,
      ...(brand.trim() && { brand: brand.trim() }),
      ...(barcode.trim() && { barcode: barcode.trim() }),
      ...(densityGPerMl !== '' && { densityGPerMl: Number(densityGPerMl) }),
      ...(imageUrl.trim() && { imageUrl: imageUrl.trim() }),
    };

    setSaving(true);
    try {
      await onSave(data);
      onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to save');
    } finally {
      setSaving(false);
    }
  }

  const inputStyle: React.CSSProperties = {
    width: '100%',
    padding: '8px 12px',
    borderRadius: 'var(--r-md)',
    border: '1px solid var(--border)',
    background: 'var(--bg-elev)',
    color: 'var(--ink)',
    fontSize: 14,
  };

  const labelStyle: React.CSSProperties = {
    display: 'block',
    fontSize: 12,
    fontWeight: 500,
    color: 'var(--ink-muted)',
    marginBottom: 4,
  };

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed',
        inset: 0,
        background: 'rgba(0,0,0,0.5)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        zIndex: 1000,
        padding: 16,
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: 'var(--bg-base, #fff)',
          borderRadius: 'var(--r-lg, 12px)',
          border: '1px solid var(--border)',
          width: '100%',
          maxWidth: 560,
          maxHeight: '90vh',
          overflowY: 'auto',
          padding: 24,
        }}
      >
        <h2 style={{ margin: '0 0 20px', fontSize: 18, fontWeight: 600, color: 'var(--ink)' }}>
          {title ?? (initial ? 'Edit Product' : 'Add Product')}
        </h2>

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

        <form onSubmit={handleSubmit} noValidate style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {/* Basic info */}
          <div>
            <label style={labelStyle}>Name *</label>
            <input
              style={inputStyle}
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Product name"
              required
            />
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div>
              <label style={labelStyle}>Brand</label>
              <input
                style={inputStyle}
                value={brand}
                onChange={(e) => setBrand(e.target.value)}
                placeholder="Optional"
              />
            </div>
            <div>
              <label style={labelStyle}>Barcode</label>
              <div style={{ display: 'flex', gap: 6 }}>
                <input
                  style={{ ...inputStyle, flex: 1 }}
                  value={barcode}
                  onChange={(e) => setBarcode(e.target.value)}
                  placeholder="8-14 digits"
                />
                <button
                  type="button"
                  disabled={lookingUp || !barcode.trim()}
                  onClick={async () => {
                    if (!barcode.trim()) return;
                    setLookingUp(true);
                    setError('');
                    try {
                      const result = await lookupBarcode(householdId, barcode.trim());
                      if ('found' in result) {
                        setError('Product not found for this barcode');
                      } else {
                        setName(result.name ?? '');
                        setBrand(result.brand ?? '');
                        setCategory((result.category as ProductCategory) ?? ProductCategory.OTHER);
                        setServingSize(result.servingSize ?? '');
                        setServingUnit((result.servingUnit as ServingUnit) ?? ServingUnit.GRAMS);
                        setDensityGPerMl(result.densityGPerMl ?? '');
                        setTags(result.tags?.join(', ') ?? '');
                        setImageUrl(result.imageUrl ?? '');
                        setCalories(result.nutrition?.calories ?? '');
                        setProtein(result.nutrition?.protein ?? '');
                        setCarbs(result.nutrition?.carbs ?? '');
                        setFat(result.nutrition?.fat ?? '');
                        setFiber(result.nutrition?.fiber ?? '');
                        setSugar(result.nutrition?.sugar ?? '');
                        setSodium(result.nutrition?.sodium ?? '');
                        setSaturatedFat(result.nutrition?.saturatedFat ?? '');
                        setCholesterol(result.nutrition?.cholesterol ?? '');
                      }
                    } catch {
                      setError('Barcode lookup failed');
                    } finally {
                      setLookingUp(false);
                    }
                  }}
                  style={{
                    padding: '8px 12px',
                    borderRadius: 'var(--r-md)',
                    border: '1px solid var(--border)',
                    background: 'var(--bg-elev)',
                    color: 'var(--ink-muted)',
                    fontSize: 12,
                    cursor: lookingUp || !barcode.trim() ? 'not-allowed' : 'pointer',
                    whiteSpace: 'nowrap',
                    opacity: lookingUp || !barcode.trim() ? 0.5 : 1,
                  }}
                >
                  {lookingUp ? 'Looking up...' : 'Lookup'}
                </button>
              </div>
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
            <div>
              <label style={labelStyle}>Category *</label>
              <select
                style={inputStyle}
                value={category}
                onChange={(e) => setCategory(e.target.value as ProductCategory)}
              >
                {CATEGORY_OPTIONS.map((cat) => (
                  <option key={cat} value={cat}>
                    {cat.charAt(0).toUpperCase() + cat.slice(1).replace(/_/g, ' ')}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label style={labelStyle}>Serving Size *</label>
              <input
                style={inputStyle}
                type="number"
                min={0}
                step="any"
                value={servingSize}
                onChange={(e) =>
                  setServingSize(e.target.value === '' ? '' : Number(e.target.value))
                }
                placeholder="e.g. 100"
                required
              />
            </div>
            <div>
              <label style={labelStyle}>Serving Unit *</label>
              <select
                style={inputStyle}
                value={servingUnit}
                onChange={(e) => setServingUnit(e.target.value as ServingUnit)}
              >
                {SERVING_UNIT_OPTIONS.map((unit) => (
                  <option key={unit} value={unit}>
                    {SERVING_UNIT_LABELS[unit] ?? unit}
                  </option>
                ))}
              </select>
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div>
              <label style={labelStyle}>Density (g/ml)</label>
              <input
                style={inputStyle}
                type="number"
                min={0}
                step="any"
                value={densityGPerMl}
                onChange={(e) =>
                  setDensityGPerMl(e.target.value === '' ? '' : Number(e.target.value))
                }
                placeholder="Optional"
              />
            </div>
            <div>
              <label style={labelStyle}>Image URL</label>
              <input
                style={inputStyle}
                value={imageUrl}
                onChange={(e) => setImageUrl(e.target.value)}
                placeholder="https://..."
              />
            </div>
          </div>

          <div>
            <label style={labelStyle}>Tags (comma-separated)</label>
            <input
              style={inputStyle}
              value={tags}
              onChange={(e) => setTags(e.target.value)}
              placeholder="e.g. organic, gluten-free"
            />
          </div>

          {/* Nutrition */}
          <div
            style={{
              borderTop: '1px solid var(--border)',
              paddingTop: 16,
              marginTop: 4,
            }}
          >
            <p style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)', margin: '0 0 12px' }}>
              Nutrition (per serving)
            </p>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 12 }}>
              <div>
                <label style={labelStyle}>Calories *</label>
                <input
                  style={inputStyle}
                  type="number"
                  min={0}
                  step="any"
                  value={calories}
                  onChange={(e) => setCalories(e.target.value === '' ? '' : Number(e.target.value))}
                  required
                />
              </div>
              <div>
                <label style={labelStyle}>Protein (g) *</label>
                <input
                  style={inputStyle}
                  type="number"
                  min={0}
                  step="any"
                  value={protein}
                  onChange={(e) => setProtein(e.target.value === '' ? '' : Number(e.target.value))}
                  required
                />
              </div>
              <div>
                <label style={labelStyle}>Carbs (g) *</label>
                <input
                  style={inputStyle}
                  type="number"
                  min={0}
                  step="any"
                  value={carbs}
                  onChange={(e) => setCarbs(e.target.value === '' ? '' : Number(e.target.value))}
                  required
                />
              </div>
              <div>
                <label style={labelStyle}>Fat (g) *</label>
                <input
                  style={inputStyle}
                  type="number"
                  min={0}
                  step="any"
                  value={fat}
                  onChange={(e) => setFat(e.target.value === '' ? '' : Number(e.target.value))}
                  required
                />
              </div>
            </div>

            <div
              style={{
                display: 'grid',
                gridTemplateColumns: '1fr 1fr 1fr 1fr 1fr',
                gap: 12,
                marginTop: 12,
              }}
            >
              <div>
                <label style={labelStyle}>Fiber (g)</label>
                <input
                  style={inputStyle}
                  type="number"
                  min={0}
                  step="any"
                  value={fiber}
                  onChange={(e) => setFiber(e.target.value === '' ? '' : Number(e.target.value))}
                />
              </div>
              <div>
                <label style={labelStyle}>Sugar (g)</label>
                <input
                  style={inputStyle}
                  type="number"
                  min={0}
                  step="any"
                  value={sugar}
                  onChange={(e) => setSugar(e.target.value === '' ? '' : Number(e.target.value))}
                />
              </div>
              <div>
                <label style={labelStyle}>Sodium (mg)</label>
                <input
                  style={inputStyle}
                  type="number"
                  min={0}
                  step="any"
                  value={sodium}
                  onChange={(e) => setSodium(e.target.value === '' ? '' : Number(e.target.value))}
                />
              </div>
              <div>
                <label style={labelStyle}>Sat. Fat (g)</label>
                <input
                  style={inputStyle}
                  type="number"
                  min={0}
                  step="any"
                  value={saturatedFat}
                  onChange={(e) =>
                    setSaturatedFat(e.target.value === '' ? '' : Number(e.target.value))
                  }
                />
              </div>
              <div>
                <label style={labelStyle}>Cholesterol (mg)</label>
                <input
                  style={inputStyle}
                  type="number"
                  min={0}
                  step="any"
                  value={cholesterol}
                  onChange={(e) =>
                    setCholesterol(e.target.value === '' ? '' : Number(e.target.value))
                  }
                />
              </div>
            </div>
          </div>

          {/* Submit */}
          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, marginTop: 8 }}>
            <button
              type="button"
              onClick={onClose}
              style={{
                padding: '8px 16px',
                borderRadius: 'var(--r-md)',
                border: '1px solid var(--border)',
                background: 'transparent',
                color: 'var(--ink-muted)',
                fontSize: 14,
                cursor: 'pointer',
              }}
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={saving}
              style={{
                padding: '8px 20px',
                borderRadius: 'var(--r-md)',
                border: 'none',
                background: 'var(--brand)',
                color: '#fff',
                fontSize: 14,
                fontWeight: 500,
                cursor: saving ? 'not-allowed' : 'pointer',
                opacity: saving ? 0.7 : 1,
              }}
            >
              {saving ? 'Saving...' : 'Save'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
