'use client';

import { useState, useTransition } from 'react';
import { consumeInventoryItem } from './actions';

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

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

  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={(e) => {
          e.preventDefault();
          setError(null);

          const form = e.currentTarget;
          const formData = new FormData(form);

          startTransition(async () => {
            try {
              await consumeInventoryItem(formData);
              setIsOpen(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={id} />

        <label>
          Hur mycket använde du? ({unit})
          <br />
          <input
            name="amountUsed"
            type="number"
            step="0.01"
            min="0.01"
            required
            style={{ width: '100%', padding: '0.5rem' }}
          />
        </label>

        <label>
          Kommentar
          <br />
          <input
            name="comment"
            type="text"
            placeholder="t.ex. lagade middag"
            style={{ width: '100%', padding: '0.5rem' }}
          />
        </label>

        <div style={{ display: 'flex', gap: '0.75rem', flexWrap: 'wrap' }}>
          <button
            type="submit"
            disabled={isPending}
            style={{ padding: '0.6rem 0.9rem' }}
          >
            {isPending ? 'Sparar...' : 'Spara användning'}
          </button>

          <button
            type="button"
            onClick={() => setIsOpen(false)}
            disabled={isPending}
            style={{ padding: '0.6rem 0.9rem' }}
          >
            Avbryt
          </button>
        </div>
      </form>

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