'use client';

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

type CategoryNode = Category & { children: CategoryNode[] };

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

const sortOptions = [
  { value: 'createdDesc', label: 'Senast tillagda' },
  { value: 'nameAsc', label: 'Namn A–Ö' },
];

function flattenTree(nodes: CategoryNode[], depth = 0): { id: number; label: string }[] {
  const result: { id: number; label: string }[] = [];
  const sorted = [...nodes].sort((a, b) => a.name.localeCompare(b.name, 'sv'));
  for (const node of sorted) {
    result.push({ id: node.id, label: '\u00a0\u00a0'.repeat(depth) + (depth > 0 ? '↳ ' : '') + node.name });
    if (node.children?.length) result.push(...flattenTree(node.children, depth + 1));
  }
  return result;
}

export default function AdminProductList() {
  const [products, setProducts] = useState<Product[]>([]);
  const [productsLoading, setProductsLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [sort, setSort] = useState('createdDesc');
  const [showUncategorizedOnly, setShowUncategorizedOnly] = useState(false);
  const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set());
  const [bulkCategoryId, setBulkCategoryId] = useState<string>('');
  const [categoryTree, setCategoryTree] = useState<CategoryNode[]>([]);
  const [isBulkPending, setIsBulkPending] = useState(false);
  const [bulkError, setBulkError] = useState<string | null>(null);

  // AI-kategorisering state
  const [aiLoading, setAiLoading] = useState(false);
  const [aiError, setAiError] = useState<string | null>(null);
  const [aiSuggestions, setAiSuggestions] = useState<AiSuggestion[] | null>(null);
  const [aiApproved, setAiApproved] = useState<Set<number>>(new Set());
  const [aiApplying, setAiApplying] = useState(false);

  const refetchProducts = useCallback(() => {
    fetch('/api/products')
      .then(async (r) => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.json();
      })
      .then((data) => {
        if (Array.isArray(data)) setProducts(data);
      })
      .catch((e) => console.error('[AdminProductList] refetchProducts error:', e))
      .finally(() => setProductsLoading(false));
  }, []);

  useEffect(() => {
    refetchProducts();
  }, [refetchProducts]);

  useEffect(() => {
    const handler = () => refetchProducts();
    window.addEventListener('product-created', handler);
    window.addEventListener('product-list-changed', handler);
    return () => {
      window.removeEventListener('product-created', handler);
      window.removeEventListener('product-list-changed', handler);
    };
  }, [refetchProducts]);

  useEffect(() => {
    fetch('/api/categories?tree')
      .then((r) => r.json())
      .then((data) => { if (Array.isArray(data)) setCategoryTree(data); })
      .catch(() => {});
  }, []);

  const categoryOptions = useMemo(() => flattenTree(categoryTree), [categoryTree]);

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();

    let result = products.filter((p) => {
      if (showUncategorizedOnly && p.categoryId != null) return false;
      if (q) {
        return (
          p.name.toLowerCase().includes(q) ||
          (p.canonicalName ?? '').toLowerCase().includes(q) ||
          (p.normalizedName ?? '').toLowerCase().includes(q)
        );
      }
      return true;
    });

    if (sort === 'nameAsc') {
      result.sort((a, b) =>
        (a.canonicalName || a.name).localeCompare(b.canonicalName || b.name, 'sv'),
      );
    } else {
      result.sort((a, b) => b.id - a.id);
    }

    return result;
  }, [products, search, sort, showUncategorizedOnly]);

  const allVisibleSelected = filtered.length > 0 && filtered.every((p) => selectedIds.has(p.id));

  const toggleSelectAll = () => {
    if (allVisibleSelected) {
      setSelectedIds((prev) => {
        const next = new Set(prev);
        filtered.forEach((p) => next.delete(p.id));
        return next;
      });
    } else {
      setSelectedIds((prev) => {
        const next = new Set(prev);
        filtered.forEach((p) => next.add(p.id));
        return next;
      });
    }
  };

  const toggleSelect = (id: number) => {
    setSelectedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const handleBulkApply = async () => {
    setBulkError(null);
    const ids = Array.from(selectedIds);
    if (ids.length === 0) return;
    const categoryId = bulkCategoryId === '' ? null : bulkCategoryId === '__remove__' ? null : Number(bulkCategoryId);
    setIsBulkPending(true);
    try {
      const res = await fetch('/api/admin/bulk-set-category', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids, categoryId }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data?.error || 'Fel vid uppdatering');
      }
      setSelectedIds(new Set());
      setBulkCategoryId('');
      refetchProducts();
    } catch (err) {
      setBulkError(err instanceof Error ? err.message : 'Fel vid uppdatering');
    } finally {
      setIsBulkPending(false);
    }
  };

  const handleAiCategorize = async () => {
    setAiLoading(true);
    setAiError(null);
    setAiSuggestions(null);
    try {
      const res = await fetch('/api/admin/bulk-categorize', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({}) });
      const data = await res.json();
      if (!res.ok) throw new Error(data?.error ?? 'AI-kategorisering misslyckades');
      setAiSuggestions(data);
      setAiApproved(new Set(data.map((r: AiSuggestion) => r.productId)));
    } catch (err) {
      setAiError(err instanceof Error ? err.message : 'AI-kategorisering misslyckades');
    } finally {
      setAiLoading(false);
    }
  };

  const handleAiApply = async () => {
    if (!aiSuggestions) return;
    setAiApplying(true);
    try {
      const approved = aiSuggestions.filter((s) => aiApproved.has(s.productId));
      const grouped = new Map<number, number[]>();
      for (const s of approved) {
        const cid = s.suggestion.categoryId;
        if (!grouped.has(cid)) grouped.set(cid, []);
        grouped.get(cid)!.push(s.productId);
      }
      for (const [categoryId, ids] of grouped.entries()) {
        const res = await fetch('/api/admin/bulk-set-category', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ ids, categoryId }),
        });
        if (!res.ok) {
          const data = await res.json().catch(() => ({}));
          throw new Error(data?.error || 'Fel vid tillämpning');
        }
      }
      setAiSuggestions(null);
      setAiApproved(new Set());
      refetchProducts();
    } catch (err) {
      setAiError(err instanceof Error ? err.message : 'Fel vid tillämpning');
    } finally {
      setAiApplying(false);
    }
  };

  if (productsLoading) {
    return <p style={{ color: '#888', marginTop: '1rem' }}>Laddar produkter…</p>;
  }

  return (
    <>
      {/* Sök + sortering + filter */}
      <div style={{ display: 'flex', gap: '1rem', alignItems: 'center', marginBottom: '1rem', flexWrap: 'wrap' }}>
        <input
          type="search"
          placeholder="Sök produkt…"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          style={{ flex: '1 1 200px', padding: '0.5rem 0.75rem', border: '1px solid #ddd', borderRadius: '6px', fontSize: '1rem' }}
        />

        <div style={{ display: 'flex', gap: '0.4rem', flexWrap: 'wrap' }}>
          {sortOptions.map((opt) => (
            <button
              key={opt.value}
              type="button"
              onClick={() => setSort(opt.value)}
              style={{
                padding: '0.45rem 0.75rem',
                borderRadius: '999px',
                border: '1px solid #ddd',
                background: sort === opt.value ? '#efefef' : '#fff',
                fontWeight: sort === opt.value ? 600 : 400,
                cursor: 'pointer',
                fontSize: '0.9rem',
              }}
            >
              {opt.label}
            </button>
          ))}
          <button
            type="button"
            onClick={() => { setShowUncategorizedOnly((v) => !v); setSelectedIds(new Set()); }}
            style={{
              padding: '0.45rem 0.75rem',
              borderRadius: '999px',
              border: '1px solid ' + (showUncategorizedOnly ? '#f59e0b' : '#ddd'),
              background: showUncategorizedOnly ? '#fffbeb' : '#fff',
              fontWeight: showUncategorizedOnly ? 600 : 400,
              cursor: 'pointer',
              fontSize: '0.9rem',
              color: showUncategorizedOnly ? '#92400e' : 'inherit',
            }}
          >
            Okategoriserade
          </button>
          <button
            type="button"
            onClick={handleAiCategorize}
            disabled={aiLoading}
            style={{
              padding: '0.45rem 0.75rem',
              borderRadius: '999px',
              border: '1px solid #a78bfa',
              background: aiLoading ? '#f5f3ff' : '#ede9fe',
              color: '#5b21b6',
              fontWeight: 600,
              cursor: aiLoading ? 'wait' : 'pointer',
              fontSize: '0.9rem',
            }}
          >
            {aiLoading ? '⏳ AI arbetar…' : '✨ AI-kategorisera okategoriserade'}
          </button>
        </div>

        <span style={{ color: '#666', fontSize: '0.9rem', whiteSpace: 'nowrap' }}>
          {filtered.length} av {products.length} produkter
        </span>
      </div>

      {/* Bulk-åtgärd */}
      {selectedIds.size > 0 && (
        <div style={{
          display: 'flex', gap: '0.75rem', alignItems: 'center', flexWrap: 'wrap',
          padding: '0.75rem 1rem', marginBottom: '1rem',
          background: '#f0f7ff', border: '1px solid #bfdbfe', borderRadius: '8px',
        }}>
          <span style={{ fontWeight: 600, fontSize: '0.9rem' }}>{selectedIds.size} valda</span>
          <select
            value={bulkCategoryId}
            onChange={(e) => setBulkCategoryId(e.target.value)}
            style={{ padding: '0.4rem 0.6rem', border: '1px solid #ddd', borderRadius: '6px', fontSize: '0.9rem', minWidth: '200px' }}
          >
            <option value="">Välj kategori…</option>
            <option value="__remove__">— Ta bort kategori —</option>
            {categoryOptions.map((opt) => (
              <option key={opt.id} value={opt.id}>{opt.label}</option>
            ))}
          </select>
          <button
            type="button"
            onClick={handleBulkApply}
            disabled={isBulkPending}
            style={{ padding: '0.4rem 0.9rem', background: '#0070f3', color: '#fff', border: 'none', borderRadius: '6px', cursor: 'pointer', fontWeight: 600, fontSize: '0.9rem' }}
          >
            {isBulkPending ? 'Sparar…' : 'Sätt kategori'}
          </button>
          <button
            type="button"
            onClick={() => setSelectedIds(new Set())}
            style={{ padding: '0.4rem 0.6rem', background: 'transparent', border: '1px solid #ddd', borderRadius: '6px', cursor: 'pointer', fontSize: '0.9rem' }}
          >
            Avmarkera
          </button>
          {bulkError && <span style={{ color: '#dc2626', fontSize: '0.85rem' }}>{bulkError}</span>}
        </div>
      )}

      {/* Välj alla synliga */}
      {filtered.length > 0 && (
        <div style={{ marginBottom: '0.5rem' }}>
          <label style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', cursor: 'pointer', fontSize: '0.875rem', color: '#555' }}>
            <input type="checkbox" checked={allVisibleSelected} onChange={toggleSelectAll} />
            Välj alla synliga ({filtered.length})
          </label>
        </div>
      )}

      <div style={{ display: 'grid', gap: '1rem' }}>
        {filtered.map((product) => (
          <article
            key={product.id}
            style={{
              border: selectedIds.has(product.id) ? '1px solid #93c5fd' : '1px solid #ddd',
              borderRadius: '8px',
              padding: '1rem',
              display: 'grid',
              gap: '0.5rem',
              background: selectedIds.has(product.id) ? '#f0f7ff' : undefined,
            }}
          >
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: '0.5rem', flexWrap: 'wrap' }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: '0.6rem' }}>
                <input
                  type="checkbox"
                  checked={selectedIds.has(product.id)}
                  onChange={() => toggleSelect(product.id)}
                  style={{ marginTop: '3px', flexShrink: 0 }}
                />
                <div>
                  <strong>{product.canonicalName || product.name}</strong>
                  {product.canonicalName && product.canonicalName !== product.name && (
                    <span style={{ color: '#666', fontSize: '0.85rem', marginLeft: '0.5rem' }}>({product.name})</span>
                  )}
                  {product.categoryRef ? (
                    <span style={{ marginLeft: '0.5rem', fontSize: '0.8rem', background: '#e0f2fe', borderRadius: '999px', padding: '0.15rem 0.5rem', color: '#0369a1' }}>
                      {[product.categoryRef.parent?.parent?.name, product.categoryRef.parent?.name, product.categoryRef.name].filter(Boolean).join(' › ')}
                    </span>
                  ) : product.category ? (
                    <span style={{ marginLeft: '0.5rem', fontSize: '0.8rem', background: '#eee', borderRadius: '999px', padding: '0.15rem 0.5rem', color: '#555' }}>
                      {product.category}
                    </span>
                  ) : (
                    <span style={{ marginLeft: '0.5rem', fontSize: '0.8rem', color: '#f59e0b', fontStyle: 'italic' }}>Okategoriserad</span>
                  )}
                </div>
              </div>
              <span style={{ color: '#aaa', fontSize: '0.8rem' }}>ID: {product.id}</span>
            </div>
            <div style={{ fontSize: '0.8rem', color: '#888' }}>
              Normalized: {product.normalizedName}
            </div>
            <EditProductForm
              product={product}
              onSaved={(updated) => setProducts((prev) => prev.map((p) => p.id === updated.id ? updated : p))}
              onDeleted={(id) => setProducts((prev) => prev.filter((p) => p.id !== id))}
            />
          </article>
        ))}
      </div>

      {/* AI-kategorisering modal */}
      {(aiError || aiSuggestions) && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000 }}>
          <div style={{ background: '#fff', borderRadius: 10, padding: '1.5rem', maxWidth: 700, width: '95%', maxHeight: '85vh', display: 'flex', flexDirection: 'column', gap: '1rem', boxShadow: '0 8px 32px rgba(0,0,0,0.18)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <h3 style={{ margin: 0 }}>✨ AI-kategoriförslag</h3>
              <button onClick={() => { setAiSuggestions(null); setAiError(null); }} style={{ background: 'none', border: 'none', fontSize: 20, cursor: 'pointer', color: '#64748b' }}>✕</button>
            </div>

            {aiError && <div style={{ color: '#dc2626', background: '#fef2f2', border: '1px solid #fecaca', borderRadius: 6, padding: '0.6rem 1rem', fontSize: 14 }}>{aiError}</div>}

            {aiSuggestions && (
              <>
                <p style={{ margin: 0, fontSize: 13, color: '#475569' }}>
                  AI har analyserat {aiSuggestions.length} okategoriserade produkter. Avmarkera rader du inte vill godkänna, klicka sedan "Godkänn valda".
                </p>
                <div style={{ overflowY: 'auto', flex: 1 }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                    <thead>
                      <tr style={{ background: '#f1f5f9', textAlign: 'left' }}>
                        <th style={{ padding: '0.5rem 0.6rem', borderBottom: '2px solid #e2e8f0' }}>
                          <input type="checkbox" checked={aiApproved.size === aiSuggestions.length} onChange={() => setAiApproved(aiApproved.size === aiSuggestions.length ? new Set() : new Set(aiSuggestions.map((s) => s.productId)))} />
                        </th>
                        {['Produkt', 'AI-förslag', 'Säkerhet'].map((h) => <th key={h} style={{ padding: '0.5rem 0.6rem', borderBottom: '2px solid #e2e8f0' }}>{h}</th>)}
                      </tr>
                    </thead>
                    <tbody>
                      {aiSuggestions.map((s) => {
                        const approved = aiApproved.has(s.productId);
                        const isLow = s.suggestion.confidence === 'low' || s.suggestion.usedFallback;
                        return (
                          <tr key={s.productId} style={{ borderBottom: '1px solid #e2e8f0', background: isLow ? '#fffbeb' : approved ? '#f0fdf4' : '#fff', opacity: approved ? 1 : 0.5 }}>
                            <td style={{ padding: '0.5rem 0.6rem' }}>
                              <input type="checkbox" checked={approved} onChange={() => setAiApproved((prev) => { const next = new Set(prev); if (next.has(s.productId)) next.delete(s.productId); else next.add(s.productId); return next; })} />
                            </td>
                            <td style={{ padding: '0.5rem 0.6rem', fontWeight: 500 }}>{s.productName}</td>
                            <td style={{ padding: '0.5rem 0.6rem', color: isLow ? '#92400e' : '#15803d' }}>
                              {isLow ? '⚠ ' : '✓ '}{s.suggestion.path}
                            </td>
                            <td style={{ padding: '0.5rem 0.6rem' }}>
                              <span style={{ display: 'inline-block', padding: '0.15rem 0.5rem', borderRadius: 999, fontSize: 12, fontWeight: 600, background: isLow ? '#fef3c7' : s.suggestion.confidence === 'high' ? '#dcfce7' : '#dbeafe', color: isLow ? '#92400e' : s.suggestion.confidence === 'high' ? '#15803d' : '#1d4ed8' }}>
                                {isLow ? 'Låg' : s.suggestion.confidence === 'high' ? 'Hög' : 'Medium'}
                              </span>
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
                <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end' }}>
                  <button onClick={() => { setAiSuggestions(null); setAiError(null); }} style={{ padding: '0.5rem 1rem', background: '#e2e8f0', border: 'none', borderRadius: 6, cursor: 'pointer', fontWeight: 500 }}>Avbryt</button>
                  <button onClick={handleAiApply} disabled={aiApplying || aiApproved.size === 0} style={{ padding: '0.5rem 1.2rem', background: '#7c3aed', color: '#fff', border: 'none', borderRadius: 6, cursor: 'pointer', fontWeight: 600 }}>
                    {aiApplying ? 'Sparar…' : `Godkänn valda (${aiApproved.size})`}
                  </button>
                </div>
              </>
            )}
          </div>
        </div>
      )}
    </>
  );
}
