'use client';

import { useState, useTransition } from 'react';
import { updateInventoryItem } from './actions';
import type { InventoryItem } from '../../features/inventory/types';
import { UNIT_OPTIONS } from '../../lib/units';

type Props = {
  item: InventoryItem;
};

function toDateInputValue(value: string | null) {
  if (!value) return '';
  return value.slice(0, 10);
}

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.toLowerCase() || defaultUnit;
  const value = parseFloat(num);
  // Konvertera alltid till defaultUnit
  if (defaultUnit === 'kg') {
    if (unit === 'g' || unit === 'gram') return { quantity: value / 1000, unit: 'kg' };
    if (unit === 'hg' || unit === 'hektogram') return { quantity: value / 10, unit: 'kg' };
    if (unit === 'kg' || unit === 'kilogram' || unit === '') return { quantity: value, unit: 'kg' };
  }
  if (defaultUnit === 'g') {
    if (unit === 'kg' || unit === 'kilogram') return { quantity: value * 1000, unit: 'g' };
    if (unit === 'hg' || unit === 'hektogram') return { quantity: value * 100, unit: 'g' };
    if (unit === 'g' || unit === 'gram' || unit === '') return { quantity: value, unit: 'g' };
  }
  // Lägg till fler konverteringar vid behov
  return { quantity: value, unit: defaultUnit };
}

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

export default function InventoryEditForm({ item }: Props) {
  const [isEditing, setIsEditing] = useState(false);
  const [isPending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);

  if (!isEditing) {
    return (
      <button
        type="button"
        onClick={() => setIsEditing(true)}
        style={{ padding: '0.5rem 0.75rem' }}
      >
        Redigera
      </button>
    );
  }

  return (
    <div
      style={{
        width: '100%',
        display: 'grid',
        gap: '0.75rem',
        marginTop: '0.5rem',
      }}
    >
      <form
        onSubmit={(e) => {
          e.preventDefault();
          setError(null);
          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);
          startTransition(async () => {
            try {
              await updateInventoryItem(formData);
              setIsEditing(false);
            } catch (err) {
              setError(err instanceof Error ? err.message : 'Okänt fel');
            }
          });
        }}
        style={{
          display: 'grid',
          gap: '0.75rem',
          border: '1px solid #eee',
          borderRadius: '8px',
          padding: '0.75rem',
          background: '#fafafa',
        }}
      >
        <input type="hidden" name="id" value={item.id} />

        <div
          style={{
            display: 'grid',
            gap: '0.75rem',
            gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))',
          }}
        >
          <label style={{ display: 'grid', gap: '0.3rem' }}>
            <span style={{ fontWeight: 500, fontSize: '0.9rem' }}>Mängd</span>
            <input
              name="quantity"
              type="text"
              required
              defaultValue={item.quantity}
              style={{ 
                width: '100%', 
                padding: '0.75rem',
                border: '1px solid #ddd',
                borderRadius: '4px',
                fontSize: '1rem',
                boxSizing: 'border-box',
                minHeight: '44px',
              }}
            />
          </label>

          <label style={{ display: 'grid', gap: '0.3rem' }}>
            <span style={{ fontWeight: 500, fontSize: '0.9rem' }}>Enhet</span>
            <select
              name="unit"
              defaultValue={item.unit}
              style={{ 
                width: '100%', 
                padding: '0.75rem',
                border: '1px solid #ddd',
                borderRadius: '4px',
                fontSize: '1rem',
                boxSizing: 'border-box',
                minHeight: '44px',
              }}
            >
              {UNIT_OPTIONS.map((opt) => (
                <option key={opt.value} value={opt.value}>
                  {opt.label}
                </option>
              ))}
            </select>
          </label>

          <label style={{ display: 'grid', gap: '0.3rem' }}>
            <span style={{ fontWeight: 500, fontSize: '0.9rem' }}>Plats</span>
            <select
              name="location"
              defaultValue={item.location || ''}
              style={{ 
                width: '100%', 
                padding: '0.75rem',
                border: '1px solid #ddd',
                borderRadius: '4px',
                fontSize: '1rem',
                boxSizing: 'border-box',
                minHeight: '44px',
              }}
            >
              {LOCATION_OPTIONS.map((opt) => (
                <option key={opt.value} value={opt.value}>
                  {opt.label}
                </option>
              ))}
            </select>
          </label>

          <label style={{ display: 'grid', gap: '0.3rem' }}>
            <span style={{ fontWeight: 500, fontSize: '0.9rem' }}>Varumärke</span>
            <input
              name="brand"
              type="text"
              defaultValue={item.brand || ''}
              style={{ 
                width: '100%', 
                padding: '0.75rem',
                border: '1px solid #ddd',
                borderRadius: '4px',
                fontSize: '1rem',
                boxSizing: 'border-box',
                minHeight: '44px',
              }}
            />
          </label>

          <label style={{ display: 'grid', gap: '0.3rem' }}>
            <span style={{ fontWeight: 500, fontSize: '0.9rem' }}>Bäst före</span>
            <input
              name="bestBeforeDate"
              type="date"
              defaultValue={toDateInputValue(item.bestBeforeDate)}
              style={{ 
                width: '100%', 
                padding: '0.75rem',
                border: '1px solid #ddd',
                borderRadius: '4px',
                fontSize: '1rem',
                boxSizing: 'border-box',
                minHeight: '44px',
              }}
            />
          </label>
        </div>

        <label style={{ display: 'grid', gap: '0.3rem' }}>
          <span style={{ fontWeight: 500, fontSize: '0.9rem' }}>Passar till</span>
          <input
            name="suitableFor"
            type="text"
            defaultValue={item.suitableFor || ''}
            style={{ 
              width: '100%', 
              padding: '0.75rem',
              border: '1px solid #ddd',
              borderRadius: '4px',
              fontSize: '1rem',
              boxSizing: 'border-box',
              minHeight: '44px',
            }}
          />
        </label>

        <label style={{ display: 'grid', gap: '0.3rem' }}>
          <span style={{ fontWeight: 500, fontSize: '0.9rem' }}>Kommentar</span>
          <input
            name="comment"
            type="text"
            defaultValue={item.comment || ''}
            style={{ 
              width: '100%', 
              padding: '0.75rem',
              border: '1px solid #ddd',
              borderRadius: '4px',
              fontSize: '1rem',
              boxSizing: 'border-box',
              minHeight: '44px',
            }}
          />
        </label>

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

        <div style={{ display: 'flex', gap: '0.75rem', flexWrap: 'wrap' }}>
          <button
            type="submit"
            disabled={isPending}
            style={{ 
              padding: '0.75rem 1.5rem',
              background: '#0070f3',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer',
              fontSize: '1rem',
              minHeight: '44px',
              fontWeight: 600,
            }}
          >
            {isPending ? 'Sparar...' : 'Spara ändringar'}
          </button>

          <button
            type="button"
            onClick={() => setIsEditing(false)}
            disabled={isPending}
            style={{ 
              padding: '0.75rem 1.5rem',
              background: '#f0f0f0',
              color: '#333',
              border: '1px solid #ccc',
              borderRadius: '4px',
              cursor: 'pointer',
              fontSize: '1rem',
              minHeight: '44px',
              fontWeight: 600,
            }}
          >
            Avbryt
          </button>
        </div>
      </form>

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