'use client';

import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import DOMPurify from 'dompurify';
import { authApi, wishlistsApi, itemsApi, claimingApi, settingsApi, type Wishlist, type Item, type Settings } from '@/lib/api';
import Header from '@/components/header';
import GuestGuard from '@/components/guest-guard';

export default function PublicWishlistPage() {
  return (
    <GuestGuard>
      <PublicWishlistContent />
    </GuestGuard>
  );
}

function PublicWishlistContent() {
  const params = useParams();
  const [wishlist, setWishlist] = useState<Wishlist | null>(null);
  const [items, setItems] = useState<Item[]>([]);
  const [siteSettings, setSiteSettings] = useState<Settings>({ siteTitle: '', homepageSubtext: '', claimingEnabled: true, showQuantity: true });
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState('');

  // Current viewer
  const [currentGuestId, setCurrentGuestId] = useState<string | null>(null);
  const [isAdmin, setIsAdmin] = useState(false);

  // Claim form state
  const [claimingItemId, setClaimingItemId] = useState<string | null>(null);
  const [claimNote, setClaimNote] = useState('');
  const [claimQty, setClaimQty] = useState(1);
  const [isClaiming, setIsClaiming] = useState(false);
  const [claimError, setClaimError] = useState('');
  const [justClaimedItemId, setJustClaimedItemId] = useState<string | null>(null);

  // Unclaim state
  const [isUnclaiming, setIsUnclaiming] = useState(false);

  useEffect(() => {
    (async () => {
      try {
        const who = await authApi.whoami();
        if (who.role === 'admin') {
          setIsAdmin(true);
          if (who.guest) setCurrentGuestId(who.guest.id);
        } else if (who.role === 'guest') {
          setCurrentGuestId(who.guest.id);
        }
      } catch {
        /* ignore */
      }
    })();
  }, []);

  useEffect(() => {
    settingsApi.getSettings().then(setSiteSettings).catch(() => {});
    fetchWishlist();
  }, [params.slug]);

  const fetchWishlist = async () => {
    if (!params.slug) return;

    try {
      const wishlistData = await wishlistsApi.getBySlug(params.slug as string);
      setWishlist(wishlistData);

      const itemsData = await itemsApi.getAll(wishlistData.id);
      setItems(itemsData.sort((a, b) => a.sortOrder - b.sortOrder));
    } catch (err: any) {
      setError(err.message || 'Wishlist not found');
    } finally {
      setIsLoading(false);
    }
  };

  const myClaimFor = (item: Item) => item.claims.find((c) => c.guest.id === currentGuestId);

  const handleStartClaim = (item: Item) => {
    const my = myClaimFor(item);
    setClaimingItemId(item.id);
    setClaimError('');
    setClaimNote(my?.note ?? '');
    setClaimQty(my?.quantity ?? 1);
    setJustClaimedItemId(null);
  };

  const handleSubmitClaim = async (e: React.FormEvent, itemId: string) => {
    e.preventDefault();

    setIsClaiming(true);
    setClaimError('');

    try {
      await claimingApi.claim(itemId, { quantity: claimQty, note: claimNote });

      setJustClaimedItemId(itemId);
      setClaimingItemId(null);
      setClaimNote('');
      setClaimQty(1);
      fetchWishlist();
    } catch (err: any) {
      setClaimError(err.message || 'Erro ao reservar item');
    } finally {
      setIsClaiming(false);
    }
  };

  const handleUnclaim = async (itemId: string, guestId?: string) => {
    if (!confirm('Cancelar a reserva?')) return;

    setIsUnclaiming(true);

    try {
      await claimingApi.unclaim(itemId, guestId ? { guestId } : {});
      fetchWishlist();
    } catch (err: any) {
      alert(err.message || 'Erro ao cancelar reserva');
    } finally {
      setIsUnclaiming(false);
    }
  };

  const filteredItems = items.filter((item) => {
    const my = myClaimFor(item);
    return item.remainingQuantity > 0 || my || item.id === justClaimedItemId;
  });


  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center">
        <p className="text-gray-600 dark:text-gray-400">Carregando...</p>
      </div>
    );
  }

  if (error || !wishlist) {
    return (
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">Lista não encontrada</h1>
          <p className="text-gray-600 dark:text-gray-400">{error || 'Esta lista não existe ou não é pública.'}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-cosmic">
      <Header
        title={wishlist.name}
        subtitle={wishlist.description || undefined}
        imageUrl={wishlist.imageUrl || undefined}
        maxWidth="max-w-5xl"
      />

      {/* Main Content */}
      <div className="max-w-5xl mx-auto py-12 sm:px-6 lg:px-8">
        <div className="px-4 sm:px-0">
          {/* Preferences Section */}
          {wishlist.preferences && (
            <div className="mb-8 bg-white dark:bg-gray-800 rounded-lg shadow p-6">
              <h2 className="text-xl font-bold text-gray-900 dark:text-white mb-3">
                Interesses e Preferências
              </h2>
              <div
                className="prose prose-indigo dark:prose-invert max-w-none text-gray-700 dark:text-gray-300 [&_a]:text-indigo-600 [&_a]:dark:text-indigo-400 [&_a]:hover:underline"
                dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(wishlist.preferences) }}
                onClick={(e) => {
                  const target = e.target as HTMLElement;
                  if (target.tagName === 'A') {
                    e.preventDefault();
                    window.open((target as HTMLAnchorElement).href, '_blank', 'noopener,noreferrer');
                  }
                }}
              />
            </div>
          )}

          {/* Controls */}
          {siteSettings.claimingEnabled && (
            <div className="mb-6 flex items-center justify-end">
              <div className="text-sm text-gray-600 dark:text-gray-400">
                {filteredItems.length} de {items.length} itens
              </div>
            </div>
          )}

          {/* Items List */}
          {filteredItems.length === 0 ? (
            <div className="text-center py-12 bg-white dark:bg-gray-800 rounded-lg shadow">
              <p className="text-gray-500 dark:text-gray-400">
                Todos os itens já foram reservados!
              </p>
            </div>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
              {filteredItems.map((item) => {
                const myClaim = myClaimFor(item);
                const maxForMe = item.remainingQuantity + (myClaim?.quantity ?? 0);
                const showQuantitySummary = item.quantity > 1 && siteSettings.showQuantity;
                const sold = item.remainingQuantity === 0 && !myClaim;
                const canClaim = siteSettings.claimingEnabled && Boolean(currentGuestId);

                return (
                  <div
                    key={item.id}
                    className="bg-white dark:bg-gray-800 rounded-lg shadow hover:shadow-lg transition-all duration-300 overflow-hidden flex flex-col"
                  >
                    {/* Top: Image */}
                    {item.imageUrl && (
                      <div className="flex-shrink-0">
                        <img
                          src={item.imageUrl}
                          alt={item.name}
                          className="w-full h-48 object-cover"
                        />
                      </div>
                    )}

                    {/* Middle: Item Details */}
                    <div className="flex-1 p-5">
                      <h3 className="text-xl font-bold text-gray-900 dark:text-white mb-1">
                        {item.name}
                      </h3>
                      {item.price != null && (
                        <p className="text-base font-semibold text-indigo-600 dark:text-indigo-400 mb-1">
                          {new Intl.NumberFormat('pt-BR', { style: 'currency', currency: item.currency || 'BRL' }).format(item.price)}
                        </p>
                      )}
                      {showQuantitySummary && (
                        <p className="text-sm text-gray-500 dark:text-gray-400 mb-2">
                          {item.claimedQuantity} de {item.quantity} reservados
                        </p>
                      )}
                      {item.description && (
                        <p className="text-sm text-gray-600 dark:text-gray-300 mb-3">
                          {item.description}
                        </p>
                      )}

                      {/* Existing claims list */}
                      {item.claims.length > 0 && (
                        <ul className="text-sm text-gray-700 dark:text-gray-300 space-y-1 mt-3 border-t border-gray-200 dark:border-gray-700 pt-3">
                          {item.claims.map((c) => {
                            const isMine = c.guest.id === currentGuestId;
                            const canCancel = isMine || isAdmin;
                            return (
                              <li key={c.id} className="flex items-center justify-between gap-2">
                                <div>
                                  <span className="font-medium">{isMine ? 'Você' : 'Reservado'}</span>
                                  {item.quantity > 1 && (
                                    <span className="text-gray-500"> · {c.quantity} un.</span>
                                  )}
                                  {c.note && isMine && (
                                    <span className="block text-xs italic text-gray-500">
                                      &quot;{c.note}&quot;
                                    </span>
                                  )}
                                </div>
                                {canCancel && (
                                  <button
                                    onClick={() => handleUnclaim(item.id, isMine ? undefined : c.guest.id)}
                                    disabled={isUnclaiming}
                                    className="text-xs text-red-600 hover:underline disabled:opacity-50 cursor-pointer"
                                  >
                                    Cancelar
                                  </button>
                                )}
                              </li>
                            );
                          })}
                        </ul>
                      )}
                    </div>

                    {/* Bottom: Action Area */}
                    <div className="p-5 bg-gray-50 dark:bg-gray-900/50 border-t border-gray-200 dark:border-gray-700 flex flex-col gap-3">
                      {item.purchaseUrls && item.purchaseUrls.length > 0 && (
                        <div className="space-y-2">
                          {item.purchaseUrls.map((url, idx) => (
                            <a
                              key={idx}
                              href={url.url}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="flex items-center justify-between text-sm px-3 py-2 rounded-lg hover:bg-indigo-50 dark:hover:bg-indigo-900/20 transition-colors cursor-pointer border border-gray-200 dark:border-gray-700"
                            >
                              <span className="text-indigo-600 dark:text-indigo-400 hover:text-indigo-800 dark:hover:text-indigo-300 font-medium">
                                {url.label}
                              </span>
                            </a>
                          ))}
                        </div>
                      )}

                      {!canClaim ? null : sold ? (
                        <div className="bg-gray-100 dark:bg-gray-700 rounded p-3 text-center text-sm text-gray-700 dark:text-gray-300">
                          Esgotado
                        </div>
                      ) : claimingItemId === item.id ? (
                        <form onSubmit={(e) => handleSubmitClaim(e, item.id)} className="space-y-3">
                          {claimError && (
                            <div className="p-2 bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-400 rounded text-xs">
                              {claimError}
                            </div>
                          )}

                          {item.quantity > 1 && siteSettings.showQuantity && (
                            <div>
                              <label htmlFor={`claim-qty-${item.id}`} className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                Quantidade (máx {maxForMe}):
                              </label>
                              <input
                                id={`claim-qty-${item.id}`}
                                type="number"
                                min={1}
                                max={maxForMe}
                                value={claimQty}
                                onChange={(e) => setClaimQty(Math.max(1, Math.min(maxForMe, Number(e.target.value) || 1)))}
                                className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 dark:bg-gray-700 dark:text-white"
                              />
                            </div>
                          )}

                          <div>
                            <label htmlFor={`claim-note-${item.id}`} className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                              Deixe uma nota (opcional):
                            </label>
                            <textarea
                              id={`claim-note-${item.id}`}
                              rows={3}
                              className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 dark:bg-gray-700 dark:text-white resize-none"
                              value={claimNote}
                              onChange={(e) => setClaimNote(e.target.value)}
                            />
                          </div>

                          <button
                            type="submit"
                            disabled={isClaiming}
                            className="w-full px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600 font-medium disabled:opacity-50 transition-colors cursor-pointer"
                          >
                            {isClaiming ? 'Reservando...' : (myClaim ? 'Atualizar reserva' : 'Confirmar reserva')}
                          </button>
                          <button
                            type="button"
                            onClick={() => setClaimingItemId(null)}
                            className="w-full px-4 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer"
                          >
                            Cancelar
                          </button>
                        </form>
                      ) : (
                        <button
                          onClick={() => handleStartClaim(item)}
                          className="w-full px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 font-medium transition-colors cursor-pointer"
                        >
                          {myClaim ? 'Atualizar reserva' : 'Reservar'}
                        </button>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
