'use client';

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

export default function MergePreviewForm() {
  const [products, setProducts] = useState<Product[]>([]);
  const [sourceProductId, setSourceProductId] = useState('');
  const [targetProductId, setTargetProductId] = useState('');
  const [preview, setPreview] = useState<MergePreview | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [isPending, startTransition] = useTransition();
  const [isConfirming, setIsConfirming] = useState(false);
  const [isExpanded, setIsExpanded] = useState(false);

  useEffect(() => {
    if (isExpanded && products.length === 0) {
      fetch('/api/products')
        .then((r) => r.json())
        .then((data) => { if (Array.isArray(data)) setProducts(data); })
        .catch(() => {});
    }
  }, [isExpanded]);

  const fetchPreview = () => {
    setError(null);
    setSuccessMessage(null);
    setPreview(null);
    setIsConfirming(false);

    if (!sourceProductId || !targetProductId) {
      setError('Välj både source och target.');
      return;
    }

    if (sourceProductId === targetProductId) {
      setError('Source och target kan inte vara samma produkt.');
      return;
    }

    startTransition(async () => {
      try {
        const res = await fetch(
          `/api/admin/merge-preview-proxy?sourceProductId=${sourceProductId}&targetProductId=${targetProductId}`,
          {
            method: 'GET',
            cache: 'no-store',
          },
        );

        if (!res.ok) {
          const text = await res.text();
          throw new Error(text || 'Kunde inte hämta preview.');
        }

        const data: MergePreview = await res.json();
        setPreview(data);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Okänt fel');
      }
    });
  };

  const confirmMerge = () => {
    setError(null);
    setSuccessMessage(null);

    if (!preview) {
      setError('Ingen preview finns att bekräfta.');
      return;
    }

    startTransition(async () => {
      try {
        const res = await fetch('/api/admin/merge-products', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            sourceProductId: preview.source.id,
            targetProductId: preview.target.id,
          }),
        });

        if (!res.ok) {
          const data = await res.json().catch(() => ({}));
          throw new Error(data?.error || 'Sammanslagning misslyckades');
        }

        setSuccessMessage(
          `Produkten "${preview.source.canonicalName || preview.source.name}" slogs ihop med "${preview.target.canonicalName || preview.target.name}".`,
        );
        setPreview(null);
        setIsConfirming(false);
        setSourceProductId('');
        setTargetProductId('');
        window.dispatchEvent(new CustomEvent('product-list-changed'));
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Okänt fel');
      }
    });
  };

  return (
    <section
      style={{
        border: '2px solid #10b981',
        borderRadius: '8px',
        marginBottom: '1.5rem',
        overflow: 'hidden',
      }}
    >
      <button
        type="button"
        onClick={() => setIsExpanded(!isExpanded)}
        style={{
          width: '100%',
          padding: '1rem',
          background: '#10b981',
          color: 'white',
          border: 'none',
          fontSize: '1.1rem',
          fontWeight: 600,
          cursor: 'pointer',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          transition: 'background 0.2s',
        }}
        onMouseEnter={(e) => {
          (e.target as HTMLElement).style.background = '#059669';
        }}
        onMouseLeave={(e) => {
          (e.target as HTMLElement).style.background = '#10b981';
        }}
      >
        <span>🔄 Förhandsgranska merge</span>
        <span style={{ fontSize: '1.5rem', transform: isExpanded ? 'rotate(180deg)' : 'rotate(0deg)', transition: 'transform 0.2s' }}>
          ▼
        </span>
      </button>

      {isExpanded && (
        <div style={{ padding: '1rem', background: '#f9fafb', display: 'grid', gap: '1rem' }}>
          <div style={{ display: 'grid', gap: '0.75rem', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))' }}>
            <label style={{ display: 'grid', gap: '0.3rem' }}>
              <span style={{ fontWeight: 500, fontSize: '0.9rem' }}>Source product (ska bort)</span>
              <select
                value={sourceProductId}
                onChange={(e) => setSourceProductId(e.target.value)}
                style={{ 
                  width: '100%', 
                  padding: '0.75rem',
                  border: '1px solid #ddd',
                  borderRadius: '4px',
                  fontSize: '1rem',
                  boxSizing: 'border-box',
                  minHeight: '44px',
                }}
              >
                <option value="">Välj source</option>
                {products.map((product) => (
                  <option key={product.id} value={product.id}>
                    {product.canonicalName || product.name} (ID {product.id})
                  </option>
                ))}
              </select>
            </label>

            <label style={{ display: 'grid', gap: '0.3rem' }}>
              <span style={{ fontWeight: 500, fontSize: '0.9rem' }}>Target product (ska behållas)</span>
              <select
                value={targetProductId}
                onChange={(e) => setTargetProductId(e.target.value)}
                style={{ 
                  width: '100%', 
                  padding: '0.75rem',
                  border: '1px solid #ddd',
                  borderRadius: '4px',
                  fontSize: '1rem',
                  boxSizing: 'border-box',
                  minHeight: '44px',
                }}
              >
                <option value="">Välj target</option>
                {products.map((product) => (
                  <option key={product.id} value={product.id}>
                    {product.canonicalName || product.name} (ID {product.id})
                  </option>
                ))}
              </select>
            </label>
          </div>

          <div style={{ display: 'flex', gap: '0.75rem', flexWrap: 'wrap' }}>
            <button
              type="button"
              onClick={fetchPreview}
              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 ? 'Hämtar preview...' : 'Förhandsgranska merge'}
            </button>

            {preview ? (
              <button
                type="button"
                onClick={() => setIsConfirming((prev) => !prev)}
                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,
                }}
              >
                {isConfirming ? 'Avbryt bekräftelse' : 'Gå vidare till bekräftelse'}
              </button>
            ) : null}
          </div>

          {error ? <p style={{ color: 'crimson', margin: 0 }}>{error}</p> : null}
          {successMessage ? <p style={{ color: 'green', margin: 0 }}>{successMessage}</p> : null}

          {preview ? (
            <div style={{ display: 'grid', gap: '1rem' }}>
              <div
                style={{
                  display: 'grid',
                  gap: '1rem',
                  gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))',
                }}
              >
                <article style={{ border: '1px solid #ddd', borderRadius: '8px', padding: '1rem' }}>
                  <h3 style={{ marginTop: 0 }}>Source</h3>
                  <div><strong>ID:</strong> {preview.source.id}</div>
                  <div><strong>Namn:</strong> {preview.source.name}</div>
                  <div><strong>Canonical:</strong> {preview.source.canonicalName || 'Saknas'}</div>
                  <div><strong>Normalized:</strong> {preview.source.normalizedName}</div>
                  <div><strong>Aktiv:</strong> {preview.source.isActive ? 'Ja' : 'Nej'}</div>
                  <div><strong>Inventory count:</strong> {preview.source.inventoryCount}</div>
                </article>

                <article style={{ border: '1px solid #ddd', borderRadius: '8px', padding: '1rem' }}>
                  <h3 style={{ marginTop: 0 }}>Target</h3>
                  <div><strong>ID:</strong> {preview.target.id}</div>
                  <div><strong>Namn:</strong> {preview.target.name}</div>
                  <div><strong>Canonical:</strong> {preview.target.canonicalName || 'Saknas'}</div>
                  <div><strong>Normalized:</strong> {preview.target.normalizedName}</div>
                  <div><strong>Aktiv:</strong> {preview.target.isActive ? 'Ja' : 'Nej'}</div>
                  <div><strong>Inventory count:</strong> {preview.target.inventoryCount}</div>
                </article>
              </div>

              <article
                style={{
                  border: '1px solid #ddd',
                  borderRadius: '8px',
                  padding: '1rem',
                  background: '#fafafa',
                }}
              >
                <h3 style={{ marginTop: 0 }}>Det här kommer att hända</h3>
                <div>
                  <strong>Inventory som flyttas:</strong> {preview.outcome.inventoryItemsToMove}
                </div>
                <div>
                  <strong>Source soft-deletas:</strong>{' '}
                  {preview.outcome.sourceWillBeSoftDeleted ? 'Ja' : 'Nej'}
                </div>
                <div>
                  <strong>Target förblir aktiv:</strong>{' '}
                  {preview.outcome.targetWillRemainActive ? 'Ja' : 'Nej'}
                </div>
              </article>

              {isConfirming ? (
                <article
                  style={{
                    border: '1px solid #e0b4b4',
                    borderRadius: '8px',
                    padding: '1rem',
                    background: '#fff6f6',
                    display: 'grid',
                    gap: '0.75rem',
                  }}
                >
                  <h3 style={{ marginTop: 0 }}>Bekräfta merge</h3>
                  <p style={{ margin: 0 }}>
                    Du är på väg att slå ihop{' '}
                    <strong>{preview.source.canonicalName || preview.source.name}</strong> in i{' '}
                    <strong>{preview.target.canonicalName || preview.target.name}</strong>.
                  </p>
                  <p style={{ margin: 0 }}>
                    Source-produkten kommer att soft-deletas och kan återställas senare, men
                    inventory flyttas till target.
                  </p>

                  <div style={{ display: 'flex', gap: '0.75rem', flexWrap: 'wrap' }}>
                    <button
                      type="button"
                      onClick={confirmMerge}
                      disabled={isPending}
                      style={{ 
                        padding: '0.75rem 1.5rem',
                        background: '#c0392b',
                        color: 'white',
                        border: 'none',
                        borderRadius: '4px',
                        cursor: 'pointer',
                        fontSize: '1rem',
                        minHeight: '44px',
                        fontWeight: 600,
                      }}
                    >
                      {isPending ? 'Slår ihop...' : 'Bekräfta merge'}
                    </button>

                    <button
                      type="button"
                      onClick={() => setIsConfirming(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>
                </article>
              ) : null}
            </div>
          ) : null}
        </div>
      )}
    </section>
  );
}