'use client';

import { useState, useEffect } from 'react';
import type { Product } from '../../../features/inventory/types';

type CategoryNode = {
  id: number;
  name: string;
  parentId: number | null;
  children: CategoryNode[];
};

type AiSuggestion = {
  categoryId: number;
  categoryName: string;
  path: string;
  confidence: 'high' | 'medium' | 'low';
  usedFallback: boolean;
};

type Props = {
  product: Product;
  onSaved: (updated: Product) => void;
  onDeleted: (id: number) => void;
};

const inputStyle: React.CSSProperties = {
  padding: '0.5rem 0.75rem',
  border: '1px solid #ddd',
  borderRadius: '4px',
  fontSize: '1rem',
  width: '100%',
  boxSizing: 'border-box',
};

export default function EditProductForm({ product, onSaved, onDeleted }: Props) {
  const [isOpen, setIsOpen] = useState(false);
  const [isPending, setIsPending] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);
  const [tagInput, setTagInput] = useState(
    product.tags?.map((pt) => pt.tag.name).join(', ') ?? ''
  );

  // Kategoriträd från API
  const [categoryTree, setCategoryTree] = useState<CategoryNode[]>([]);
  const [selectedCategoryId, setSelectedCategoryId] = useState<number | ''>(
    (product as any).categoryId ?? ''
  );

  // AI-suggestion state
  const [aiSuggestion, setAiSuggestion] = useState<AiSuggestion | null>(null);
  const [aiLoading, setAiLoading] = useState(false);
  const [aiError, setAiError] = useState<string | null>(null);

  useEffect(() => {
    if (isOpen && categoryTree.length === 0) {
      fetch('/api/categories?tree')
        .then((r) => r.json())
        .then((data: unknown) => {
          if (Array.isArray(data)) setCategoryTree(data as CategoryNode[]);
        })
        .catch(() => {});
    }
  }, [isOpen]);

  // Bygg flat lista för select med indragna nivåer
  function flattenTree(nodes: CategoryNode[], depth = 0): { id: number; name: string; label: string }[] {
    const result: { id: number; name: string; label: string }[] = [];
    const sorted = [...nodes].sort((a, b) => a.name.localeCompare(b.name, 'sv'));
    for (const node of sorted) {
      const prefix = depth === 0 ? '' : depth === 1 ? '\u00a0\u00a0\u00a0↳ ' : '\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0↳ ';
      result.push({ id: node.id, name: node.name, label: prefix + node.name });
      if (node.children?.length) result.push(...flattenTree(node.children, depth + 1));
    }
    return result;
  }

  const flatCategories = flattenTree(categoryTree);

  async function handleAiSuggest() {
    setAiLoading(true);
    setAiError(null);
    setAiSuggestion(null);
    try {
      const res = await fetch(`/api/admin/suggest-category/${product.id}`);
      const data = await res.json();
      if (!res.ok) throw new Error(data?.error ?? 'AI-kategorisering misslyckades');
      setAiSuggestion(data);
    } catch (err) {
      setAiError(err instanceof Error ? err.message : 'AI-kategorisering misslyckades');
    } finally {
      setAiLoading(false);
    }
  }

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    const rawTags = tagInput.split(',').map((t) => t.trim().toLowerCase()).filter(Boolean);
    setIsPending(true);
    setError(null);
    setSuccess(false);
    try {
      const res = await fetch(`/api/admin/product/${product.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: formData.get('name'),
          canonicalName: formData.get('canonicalName') ?? '',
          category: formData.get('category') ?? '',
          subcategory: formData.get('subcategory') ?? '',
          brand: formData.get('brand') ?? '',
          categoryId: selectedCategoryId !== '' ? selectedCategoryId : null,
          tags: rawTags,
        }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data?.error ?? 'Okänt fel');
        return;
      }
      setSuccess(true);
      setIsOpen(false);
      onSaved(data as Product);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Okänt fel');
    } finally {
      setIsPending(false);
    }
  }

  async function handleDelete() {
    if (!confirm(`Ta bort "${product.name}"? Detta är en mjukradering och kan återställas.`)) return;
    setError(null);
    setSuccess(false);
    setIsPending(true);
    try {
      const res = await fetch(`/api/admin/product/${product.id}`, { method: 'DELETE' });
      console.log('[EditProductForm] handleDelete: HTTP', res.status);
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        setError(data?.error ?? 'Kunde inte ta bort produkt');
        return;
      }
      onDeleted(product.id);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Okänt fel');
    } finally {
      setIsPending(false);
    }
  }

  return (
    <div>
      <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', flexWrap: 'wrap' }}>
        <button
          type="button"
          onClick={() => { setIsOpen(!isOpen); setError(null); setSuccess(false); }}
          style={{
            padding: '0.4rem 1rem',
            border: '1px solid #0070f3',
            borderRadius: '4px',
            background: isOpen ? '#0070f3' : '#fff',
            color: isOpen ? '#fff' : '#0070f3',
            cursor: 'pointer',
            fontSize: '0.9rem',
            fontWeight: 600,
          }}
        >
          {isOpen ? 'Stäng' : 'Redigera'}
        </button>
        {success && <span style={{ color: 'green', fontSize: '0.9rem' }}>✓ Sparat!</span>}
      </div>

      {error && <div style={{ color: 'crimson', marginTop: '0.5rem', fontSize: '0.9rem' }}>{error}</div>}

      {isOpen && (
        <form
          onSubmit={handleSubmit}
          style={{ marginTop: '0.75rem', display: 'grid', gap: '0.75rem', maxWidth: '480px' }}
        >
          <input type="hidden" name="id" value={product.id} />

          <label style={{ display: 'grid', gap: '0.25rem', fontSize: '0.9rem' }}>
            <span style={{ fontWeight: 600 }}>Namn</span>
            <input
              name="name"
              type="text"
              defaultValue={product.name}
              required
              style={inputStyle}
            />
          </label>

          <label style={{ display: 'grid', gap: '0.25rem', fontSize: '0.9rem' }}>
            <span style={{ fontWeight: 600 }}>Canonical name</span>
            <input
              name="canonicalName"
              type="text"
              defaultValue={product.canonicalName ?? ''}
              style={inputStyle}
              placeholder="Lämna tomt för att använda namn"
            />
            <span style={{ color: '#666', fontSize: '0.8rem' }}>
              Används för att gruppera liknande produkter (t.ex. "Kyckling" för alla kycklingvarianter)
            </span>
          </label>

          <label style={{ display: 'grid', gap: '0.25rem', fontSize: '0.9rem' }}>
            <span style={{ fontWeight: 600 }}>Kategori (ny hierarki)</span>
            <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', flexWrap: 'wrap' }}>
              <select
                value={selectedCategoryId}
                onChange={(e) => { setSelectedCategoryId(e.target.value === '' ? '' : Number(e.target.value)); setAiSuggestion(null); }}
                style={{ ...inputStyle, flex: 1, minWidth: 180 }}
              >
                <option value="">— Ingen kategori —</option>
                {flatCategories.map((cat) => (
                  <option key={cat.id} value={cat.id}>{cat.label}</option>
                ))}
              </select>
              <button
                type="button"
                onClick={handleAiSuggest}
                disabled={aiLoading}
                title="Låt AI föreslå kategori"
                style={{ padding: '0.45rem 0.75rem', background: '#ede9fe', border: '1px solid #a78bfa', borderRadius: 4, cursor: aiLoading ? 'wait' : 'pointer', fontSize: 13, color: '#5b21b6', fontWeight: 600, whiteSpace: 'nowrap' }}
              >
                {aiLoading ? '⏳' : '✨ Fråga AI'}
              </button>
            </div>
            {aiError && <span style={{ color: '#dc2626', fontSize: 12 }}>{aiError}</span>}
            {aiSuggestion && (
              <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', marginTop: 4, flexWrap: 'wrap' }}>
                <span style={{ fontSize: 12, padding: '0.2rem 0.6rem', borderRadius: 999, fontWeight: 600, background: aiSuggestion.usedFallback ? '#fef3c7' : aiSuggestion.confidence === 'high' ? '#dcfce7' : '#dbeafe', color: aiSuggestion.usedFallback ? '#92400e' : aiSuggestion.confidence === 'high' ? '#15803d' : '#1d4ed8', border: `1px solid ${aiSuggestion.usedFallback ? '#fcd34d' : aiSuggestion.confidence === 'high' ? '#86efac' : '#93c5fd'}` }}>
                  {aiSuggestion.usedFallback ? '⚠ AI osäker — ' : 'AI föreslår: '}{aiSuggestion.path}
                </span>
                <button type="button" onClick={() => { setSelectedCategoryId(aiSuggestion.categoryId); setAiSuggestion(null); }} style={{ padding: '0.2rem 0.5rem', background: '#16a34a', color: '#fff', border: 'none', borderRadius: 4, cursor: 'pointer', fontSize: 12 }}>✓</button>
                <button type="button" onClick={() => setAiSuggestion(null)} style={{ padding: '0.2rem 0.5rem', background: '#e2e8f0', border: 'none', borderRadius: 4, cursor: 'pointer', fontSize: 12 }}>✕</button>
              </div>
            )}
          </label>

          <label style={{ display: 'grid', gap: '0.25rem', fontSize: '0.9rem' }}>
            <span style={{ fontWeight: 600 }}>Varumärke</span>
            <input
              name="brand"
              type="text"
              defaultValue={product.brand ?? ''}
              style={inputStyle}
              placeholder="T.ex. Arla, ICA, Överlopps"
            />
          </label>

          <label style={{ display: 'grid', gap: '0.25rem', fontSize: '0.9rem' }}>
            <span style={{ fontWeight: 600 }}>Taggar</span>
            <input
              type="text"
              value={tagInput}
              onChange={(e) => setTagInput(e.target.value)}
              style={inputStyle}
              placeholder="t.ex. svensk, ekologisk, glutenfri"
            />
            <span style={{ color: '#666', fontSize: '0.8rem' }}>Kommaseparerade taggar (gemener)</span>
          </label>

          <div style={{ display: 'grid', gap: '0.25rem', fontSize: '0.85rem', color: '#888' }}>
            <span><strong style={{ color: '#555' }}>Normaliserat namn:</strong> {product.normalizedName}</span>
            <span><strong style={{ color: '#555' }}>Aktiv:</strong> {product.isActive ? 'Ja' : 'Nej'}</span>
          </div>

          <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }}>
            <button
              type="submit"
              disabled={isPending}
              style={{
                padding: '0.6rem 1.25rem',
                background: '#0070f3',
                color: '#fff',
                border: 'none',
                borderRadius: '4px',
                cursor: isPending ? 'not-allowed' : 'pointer',
                fontWeight: 600,
                fontSize: '0.9rem',
                opacity: isPending ? 0.7 : 1,
              }}
            >
              {isPending ? 'Sparar...' : 'Spara'}
            </button>

            <button
              type="button"
              onClick={handleDelete}
              disabled={isPending}
              style={{
                padding: '0.6rem 1.25rem',
                background: '#fff',
                color: '#c00',
                border: '1px solid #c00',
                borderRadius: '4px',
                cursor: isPending ? 'not-allowed' : 'pointer',
                fontWeight: 600,
                fontSize: '0.9rem',
                opacity: isPending ? 0.7 : 1,
              }}
            >
              Ta bort (mjukradering)
            </button>
          </div>
        </form>
      )}
    </div>
  );
}
