'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';

type Props = {
  id: number;
  unit: string;
};

export default function InventoryConsumeForm({ id, unit }: Props) {
  const [isOpen, setIsOpen] = useState(false);
  const [isPending, setIsPending] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const router = useRouter();

  if (!isOpen) {
    return (
      <button
        type="button"
        onClick={() => setIsOpen(true)}
        style={{ padding: '0.5rem 0.75rem' }}
      >
        Använt
      </button>
    );
  }

  return (
    <div
      style={{
        width: '100%',
        display: 'grid',
        gap: '0.75rem',
        marginTop: '0.5rem',
      }}
    >
      <form
        onSubmit={async (e) => {
          e.preventDefault();
          setError(null);
          const form = e.currentTarget;
          const formData = new FormData(form);
          const raw = formData.get('amountUsed') as string;
          const { quantity, unit: parsedUnit } = parseQuantityInput(raw, unit);
          formData.set('amountUsed', String(quantity));
          formData.set('unit', parsedUnit);
          const comment = String(formData.get('comment') || '').trim();
          const payload: Record<string, unknown> = { amountUsed: quantity };
          if (comment) payload.comment = comment;
          setIsPending(true);
          try {
            const res = await fetch(`/api/admin/inventory-item/${id}/consume`, {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify(payload),
            });
            if (!res.ok) {
              const data = await res.json().catch(() => ({}));
              throw new Error(data?.error || 'Kunde inte förbruka');
            }
            setIsOpen(false);
            router.refresh();
          } catch (err) {
            setError(err instanceof Error ? err.message : 'Okänt fel');
          } finally {
            setIsPending(false);
          }
        }}
        style={{
          display: 'grid',
          gap: '0.75rem',
          border: '1px solid #eee',
          borderRadius: '8px',
          padding: '0.75rem',
          background: '#fafafa',
        }}
      >
        <input type="hidden" name="id" value={id} />

        <label style={{ display: 'grid', gap: '0.3rem' }}>
          <span style={{ fontWeight: 500, fontSize: '0.9rem' }}>Hur mycket använde du? ({unit})</span>
          <input
            name="amountUsed"
            type="text"
            required
            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"
            placeholder="t.ex. lagade middag"
            style={{ 
              width: '100%', 
              padding: '0.75rem',
              border: '1px solid #ddd',
              borderRadius: '4px',
              fontSize: '1rem',
              boxSizing: 'border-box',
              minHeight: '44px',
            }}
          />
        </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 användning'}
          </button>

          <button
            type="button"
            onClick={() => setIsOpen(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>
  );
}

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 };
}