'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import type { InventoryItem } from '../../features/inventory/types';
import { UNIT_OPTIONS } from '../../lib/units';

type Props = {
  item: InventoryItem;
  onUpdated?: () => void;
};

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, onUpdated }: Props) {
  const [isEditing, setIsEditing] = useState(false);
  const [isPending, setIsPending] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const router = useRouter();

  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={async (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);

          const payload: Record<string, unknown> = { opened: formData.get('opened') === 'on' };
          if (raw) payload.quantity = quantity;
          if (parsedUnit) payload.unit = parsedUnit;
          payload.location = String(formData.get('location') || '').trim();
          payload.brand = String(formData.get('brand') || '').trim();
          payload.suitableFor = String(formData.get('suitableFor') || '').trim();
          payload.comment = String(formData.get('comment') || '').trim();
          const bestBeforeDate = String(formData.get('bestBeforeDate') || '').trim();
          payload.bestBeforeDate = bestBeforeDate || null;

          setIsPending(true);
          try {
            const res = await fetch(`/api/admin/inventory-item/${item.id}`, {
              method: 'PATCH',
              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 uppdatera');
            }
            setIsEditing(false);
            if (onUpdated) onUpdated();
            else 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={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>
  );
}