'use client';

import { useState } from 'react';
import { createInventoryItem } from './actions';
import type { Product } from '../../features/inventory/types';

type Props = {
  products: Product[];
};

export default function InventoryForm({ products }: Props) {
  const [isPending, setIsPending] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const UNIT_OPTIONS = [
    { value: '', label: 'Välj enhet' },
    { value: 'g', label: 'g (gram)' },
    { value: 'kg', label: 'kg (kilogram)' },
    { value: 'hg', label: 'hg (hektogram)' },
    { value: 'ml', label: 'ml (milliliter)' },
    { value: 'dl', label: 'dl (deciliter)' },
    { value: 'l', label: 'l (liter)' },
    { value: 'st', label: 'st (styck)' },
    { value: 'tsk', label: 'tsk (tesked)' },
    { value: 'msk', label: 'msk (matsked)' },
  ];

  const LOCATION_OPTIONS = [
    { value: '', label: 'Välj plats' },
    { value: 'Kyl', label: 'Kyl' },
    { value: 'Frys', label: 'Frys' },
    { value: 'Skafferi', label: 'Skafferi' },
    { value: 'Annat', label: 'Annat' },
  ];

  function parseQuantityInput(input: string, defaultUnit: string) {
    const match = input.trim().match(/^([\d.,]+)\s*([a-zA-Z]*)$/);
    if (!match) return { quantity: NaN, unit: defaultUnit };
    let [, num, unit] = match;
    num = num.replace(',', '.');
    unit = unit || defaultUnit;
    if (defaultUnit === 'kg' && (unit === 'g' || unit === 'gram')) return { quantity: parseFloat(num) / 1000, unit: 'kg' };
    if (defaultUnit === 'g' && (unit === 'kg' || unit === 'kilogram')) return { quantity: parseFloat(num) * 1000, unit: 'g' };
    return { quantity: parseFloat(num), unit };
  }

  return (
    <form
      onSubmit={async (e) => {
        e.preventDefault();
        setError(null);
        setIsPending(true);
        const form = e.currentTarget;
        const formData = new FormData(form);
        const raw = formData.get('quantity') as string;
        const unit = formData.get('unit') as string;
        const { quantity, unit: parsedUnit } = parseQuantityInput(raw, unit);
        formData.set('quantity', String(quantity));
        formData.set('unit', parsedUnit);
        try {
          await createInventoryItem(formData);
          form.reset();
        } catch (err) {
          setError(err instanceof Error ? err.message : 'Okänt fel');
        } finally {
          setIsPending(false);
        }
      }}
      style={{
        display: 'grid',
        gap: '0.75rem',
        padding: '1rem',
        border: '1px solid #ddd',
        borderRadius: '8px',
        marginBottom: '1.5rem',
      }}
    >
      <h2 style={{ margin: 0 }}>Lägg till hemmavara</h2>

      <label>
        Produkt
        <br />
        <select name="productId" required style={{ width: '100%', padding: '0.5rem' }}>
          <option value="">Välj produkt</option>
          {products.map((product) => (
            <option key={product.id} value={product.id}>
              {product.canonicalName || product.name}
            </option>
          ))}
        </select>
      </label>

      <label>
        Mängd
        <br />
        <input
          name="quantity"
          type="text"
          required
          style={{ width: '100%', padding: '0.5rem' }}
        />
      </label>

      <label>
        Enhet
        <br />
        <select
          name="unit"
          required
          style={{ width: '100%', padding: '0.5rem' }}
        >
          {UNIT_OPTIONS.map((opt) => (
            <option key={opt.value} value={opt.value}>
              {opt.label}
            </option>
          ))}
        </select>
      </label>

      <label>
        Plats
        <br />
        <select
          name="location"
          required
          style={{ width: '100%', padding: '0.5rem' }}
        >
          {LOCATION_OPTIONS.map((opt) => (
            <option key={opt.value} value={opt.value}>
              {opt.label}
            </option>
          ))}
        </select>
      </label>
      
       <label>
        Varumärke
        <br />
        <input
          name="brand"
          type="text"
          placeholder="t.ex. Eldorado, Kronfågel, Garant, ICA Basic, Motti"
          style={{ width: '100%', padding: '0.5rem' }}
        />
      </label>

      <label>
        Passar till
        <br />
        <input
          name="suitableFor"
          type="text"
          placeholder="Wok, Gryta..."
          style={{ width: '100%', padding: '0.5rem' }}
        />
      </label>

      <label>
        Bäst före
        <br />
        <input
          name="bestBeforeDate"
          type="date"
          style={{ width: '100%', padding: '0.5rem' }}
        />
      </label>

      <label style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
        <input name="opened" type="checkbox" />
        Öppnad
      </label>

      <button type="submit" disabled={isPending} style={{ padding: '0.75rem' }}>
        {isPending ? 'Sparar...' : 'Lägg till'}
      </button>

      {error ? <p style={{ color: 'crimson', margin: 0 }}>{error}</p> : null}
    </form>
  );
}