'use client';

import { useEffect, useState } from 'react';
import DOMPurify from 'dompurify';
import { wishlistsApi, itemsApi, claimingApi, settingsApi, type Wishlist, type Item, type Settings } from '@/lib/api';
import Header from '@/components/header';
import Footer from '@/components/footer';
import PasswordLockGuard from '@/components/password-lock-guard';

export default function Home() {
  const [wishlist, setWishlist] = useState<Wishlist | null>(null);
  const [items, setItems] = useState<Item[]>([]);
  const [showClaimed, setShowClaimed] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [settings, setSettings] = useState<Settings>({ siteTitle: 'Chá do Martin', homepageSubtext: 'Escolha um presente da lista!' });

  const [claimingItemId, setClaimingItemId] = useState<string | null>(null);
  const [claimNote, setClaimNote] = useState('');
  const [isClaiming, setIsClaiming] = useState(false);
  const [claimError, setClaimError] = useState('');
  const [justClaimedItemId, setJustClaimedItemId] = useState<string | null>(null);
  const [justClaimedNote, setJustClaimedNote] = useState('');

  const [isUnclaiming, setIsUnclaiming] = useState(false);
  const [unclaimError, setUnclaimError] = useState('');

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

  const bootstrap = async () => {
    try {
      const [settingsData, wishlists] = await Promise.all([
        settingsApi.getSettings().catch(() => null),
        wishlistsApi.getAllPublic(),
      ]);
      if (settingsData) setSettings(settingsData);

      if (wishlists.length === 0) {
        setIsLoading(false);
        return;
      }

      const primary = wishlists[0];
      setWishlist(primary);
      const itemsData = await itemsApi.getAll(primary.id);
      setItems(itemsData.sort((a, b) => a.sortOrder - b.sortOrder));
    } catch (error) {
      console.error('Failed to load home page:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const refetchItems = async () => {
    if (!wishlist) return;
    const itemsData = await itemsApi.getAll(wishlist.id);
    setItems(itemsData.sort((a, b) => a.sortOrder - b.sortOrder));
  };

  const handleClaimItem = (itemId: string) => {
    setClaimingItemId(itemId);
    setClaimError('');
    setClaimNote('');
    setJustClaimedItemId(null);
  };

  const handleSubmitClaim = async (e: React.FormEvent, itemId: string) => {
    e.preventDefault();
    setIsClaiming(true);
    setClaimError('');
    try {
      await claimingApi.claim(itemId, undefined, claimNote);
      setJustClaimedItemId(itemId);
      setJustClaimedNote(claimNote);
      setClaimingItemId(null);
      setClaimNote('');
      await refetchItems();
    } catch (err: any) {
      setClaimError(err.message || 'Erro ao reservar item');
    } finally {
      setIsClaiming(false);
    }
  };

  const handleUnclaim = async (itemId: string) => {
    if (!confirm('Tem certeza que deseja cancelar a reserva deste item?')) return;
    setIsUnclaiming(true);
    setUnclaimError('');
    try {
      await claimingApi.unclaim(itemId);
      await refetchItems();
    } catch (err: any) {
      setUnclaimError(err.message || 'Erro ao cancelar reserva');
    } finally {
      setIsUnclaiming(false);
    }
  };

  const filteredItems = showClaimed
    ? items
    : items.filter((item) => !item.claimedAt || item.id === justClaimedItemId);

  const formatPrice = (price: number | null, currency: string) => {
    if (!price) return null;
    return new Intl.NumberFormat('pt-BR', {
      style: 'currency',
      currency: currency || 'BRL',
    }).format(price);
  };

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

        <div className="max-w-5xl mx-auto py-12 sm:px-6 lg:px-8">
          <div className="px-4 sm:px-0">
            {isLoading ? (
              <div className="text-center py-12">
                <p className="text-[color:var(--muted)]">Carregando...</p>
              </div>
            ) : !wishlist ? (
              <div className="text-center py-12 bg-card rounded-2xl shadow-soft">
                <p className="text-[color:var(--muted)]">Nenhuma lista disponível ainda</p>
              </div>
            ) : (
              <>
                {wishlist.preferences && (
                  <div className="mb-8 bg-card rounded-2xl shadow-soft p-6">
                    <h2 className="text-xl font-bold text-[color:var(--ink)] mb-3">
                      Interesses e Preferências
                    </h2>
                    <div
                      className="prose prose-indigo dark:prose-invert max-w-none text-[color:var(--ink-soft)] [&_a]:text-[color:var(--accent)] [&_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>
                )}

                <div className="mb-6 flex items-center justify-between">
                  <label className="flex items-center">
                    <input
                      type="checkbox"
                      checked={showClaimed}
                      onChange={(e) => setShowClaimed(e.target.checked)}
                      className="h-4 w-4 rounded border-[color:var(--border)] accent-[color:var(--accent)]"
                    />
                    <span className="ml-2 text-sm text-[color:var(--ink-soft)]">Mostrar itens reservados</span>
                  </label>
                  <div className="text-sm text-[color:var(--muted)]">
                    {filteredItems.length} de {items.length} itens
                  </div>
                </div>

                {filteredItems.length === 0 ? (
                  <div className="text-center py-12 bg-card rounded-2xl shadow-soft">
                    <p className="text-[color:var(--muted)]">
                      {showClaimed ? 'Nenhum item nesta lista ainda' : 'Todos os itens já foram reservados!'}
                    </p>
                  </div>
                ) : (
                  <div className="space-y-6">
                    {filteredItems.map((item) => (
                      <div
                        key={item.id}
                        className="bg-card rounded-2xl shadow-soft hover:shadow-lifted transition-all duration-300 overflow-hidden"
                      >
                        <div className="flex flex-col md:flex-row">
                          {item.imageUrl && (
                            <div className="md:w-48 md:flex-shrink-0">
                              <img
                                src={item.imageUrl}
                                alt={item.name}
                                className="w-full h-48 md:h-full object-cover"
                              />
                            </div>
                          )}

                          <div className="flex-1 p-6">
                            <h3 className="text-2xl font-bold text-[color:var(--ink)] mb-3">
                              {item.name}
                            </h3>
                            {item.description && (
                              <p className="text-base text-[color:var(--ink-soft)] mb-4">
                                {item.description}
                              </p>
                            )}
                          </div>

                          <div className="md:w-80 md:flex-shrink-0 p-6 bg-card-soft border-t md:border-t-0 md:border-l border-[color:var(--border)] flex flex-col">
                            <div className="mb-4">
                              {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-base px-4 py-3 rounded-xl hover:bg-[color:var(--accent-soft)] transition-colors cursor-pointer border border-[color:var(--border)]"
                                    >
                                      <span className="text-[color:var(--accent)] font-medium">
                                        {url.label}
                                      </span>
                                      <span className="text-[color:var(--ink)] font-bold text-lg">
                                        {item.price && formatPrice(item.price, item.currency)}
                                      </span>
                                    </a>
                                  ))}
                                </div>
                              )}
                            </div>

                            <div className="mt-auto">
                              {justClaimedItemId === item.id ? (
                                <div className="bg-[color:var(--success-soft)] border border-[color:var(--success-border)] rounded-xl p-4">
                                  <div className="flex items-center justify-center mb-2">
                                    <div className="w-12 h-12 bg-[color:var(--success)] rounded-full flex items-center justify-center">
                                      <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                                      </svg>
                                    </div>
                                  </div>
                                  <p className="text-center text-lg font-semibold text-[color:var(--ink)] mb-1">
                                    Item reservado!
                                  </p>
                                  <p className="text-center text-sm text-[color:var(--ink-soft)] mb-2">
                                    O status está confirmado.
                                  </p>
                                  {justClaimedNote && (
                                    <p className="text-center text-xs text-[color:var(--ink-soft)] italic">
                                      Sua nota: &quot;{justClaimedNote}&quot;
                                    </p>
                                  )}
                                </div>
                              ) : item.claimedAt ? (
                                <div className="bg-[color:var(--success-soft)] border border-[color:var(--success-border)] rounded-xl p-3">
                                  <p className="text-sm font-medium text-[color:var(--success-ink)]">
                                    Reservado por {item.claimedByName}
                                  </p>
                                  {item.claimedByNote && (
                                    <p className="text-xs text-[color:var(--success-ink)] mt-1">
                                      Nota: {item.claimedByNote}
                                    </p>
                                  )}
                                  {item.isPurchased && (
                                    <p className="text-xs text-[color:var(--success-ink)] mt-1 font-medium">
                                      ✓ Comprado
                                    </p>
                                  )}
                                  {showClaimed && (
                                    <button
                                      onClick={() => handleUnclaim(item.id)}
                                      disabled={isUnclaiming}
                                      className="mt-3 w-full px-4 py-2 bg-rose-400 text-white rounded-xl hover:bg-rose-500 font-medium disabled:opacity-50 transition-colors cursor-pointer text-sm"
                                    >
                                      {isUnclaiming ? 'Cancelando...' : 'Cancelar reserva'}
                                    </button>
                                  )}
                                </div>
                              ) : claimingItemId === item.id ? (
                                <form onSubmit={(e) => handleSubmitClaim(e, item.id)} className="space-y-3">
                                  {claimError && (
                                    <div className="p-2 bg-rose-50 dark:bg-rose-900/20 text-rose-700 dark:text-rose-300 rounded text-xs">
                                      {claimError}
                                    </div>
                                  )}
                                  <div>
                                    <label htmlFor={`claim-note-${item.id}`} className="block text-sm font-medium text-[color:var(--ink-soft)] mb-1">
                                      Deixe uma nota (opcional):
                                    </label>
                                    <textarea
                                      id={`claim-note-${item.id}`}
                                      rows={3}
                                      placeholder="Ex: 'Vou comprar na semana que vem' ou 'Achei uma boa promoção'"
                                      className="w-full px-3 py-2 text-sm border border-[color:var(--border)] rounded-xl focus:outline-none focus:ring-2 focus:ring-[color:var(--accent)] resize-none"
                                      value={claimNote}
                                      onChange={(e) => setClaimNote(e.target.value)}
                                    />
                                  </div>
                                  <button
                                    type="submit"
                                    disabled={isClaiming}
                                    className="w-full px-4 py-2 bg-[color:var(--success)] text-white rounded-xl hover:brightness-105 font-medium disabled:opacity-50 transition-all cursor-pointer"
                                  >
                                    {isClaiming ? 'Reservando...' : 'Confirmar reserva'}
                                  </button>
                                </form>
                              ) : (
                                <button
                                  onClick={() => handleClaimItem(item.id)}
                                  className="w-full px-4 py-2 bg-[color:var(--accent)] text-white rounded-xl hover:brightness-110 font-medium transition-all cursor-pointer shadow-soft"
                                >
                                  Vou dar este presente
                                </button>
                              )}
                            </div>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </>
            )}
          </div>
        </div>

        <Footer />
      </div>
    </PasswordLockGuard>
  );
}
