'use client';

import { useEffect, useState, useRef, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { usePathname, useSearchParams } from 'next/navigation';
import { useAppSelector } from '@/store/hooks';
import AuthModal from '@/components/auth/AuthModal';
import {
  addToWishlist,
  lookupWishlistItem,
  getWishlists,
  getWishlistItems,
  createWishlist,
  moveWishlistItem,
  removeFromWishlist,
} from '@/services/wishlist/wishlist.service';
import type { WishlistItemApi, WishlistSummary } from '@/services/wishlist/wishlist.types';
import { ResponseHotelData } from '@/types/hotel';
import { Heart, Plus, X } from 'lucide-react';
import CreateWishlistModal from '@/components/wishlist/CreateWishlistModal';

const TOAST_DURATION_MS = 10_000;
const REMOVE_TOAST_DURATION_MS = 5_000;

interface AddToWishlistButtonProps {
  hotel?: ResponseHotelData | null;
  /** Use when rendering from search/card without full hotel (e.g. hotelId={hotel.id}) */
  hotelId?: string;
  /** Override dates when URL has no params (e.g. from hotel.searchParams or server) */
  checkinDate?: string;
  checkoutDate?: string;
  onLoginClick?: () => void;
  /**
   * When true, the component will NOT auto-call lookup APIs on mount.
   * Intended for SRP where the parent does a batch lookup.
   */
  disableAutoLookup?: boolean;
  /** Prefetched wishlist state (e.g. from batch lookup). */
  initialWishlistItemId?: number | null;
  /** Optional prefetched wishlist name for display. */
  initialWishlistName?: string;
  /** Optional controlled wishlist item id from parent. */
  controlledWishlistItemId?: number | null;
  /** Optional controlled wishlist name from parent. */
  controlledWishlistName?: string;
  /** Optional callback so parent can sync wishlist state across duplicate render targets. */
  onWishlistStateChange?: (next: { wishlistItemId: number | null; wishlistName: string }) => void;
}

function parseChildrenParam(value: string | null): number[] {
  if (!value || value.trim() === '') return [];
  return value.split(',').map((s) => parseInt(s.trim(), 10)).filter((n) => !Number.isNaN(n));
}

type ExtendedItem = WishlistItemApi & {
  propertyCode?: string;
  rawData?: {
    propertyCode?: string;
    property_code?: string;
    checkinDate?: string;
    checkoutDate?: string;
    id?: number | string;
  };
  id?: number | string;
};

export function AddToWishlistButton({
  hotel,
  hotelId: hotelIdProp,
  checkinDate: checkinDateProp,
  checkoutDate: checkoutDateProp,
  onLoginClick,
  disableAutoLookup,
  initialWishlistItemId,
  initialWishlistName,
  controlledWishlistItemId,
  controlledWishlistName,
  onWishlistStateChange,
}: AddToWishlistButtonProps) {
  const [isMounted, setIsMounted] = useState(false);
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const user = useAppSelector((state) => state.auth.user);
  const redirectAfterAuth = searchParams.toString()
    ? `${pathname}?${searchParams.toString()}`
    : pathname;
  const isAuthenticated = !!user;

  const [status, setStatus] = useState<'idle' | 'loading' | 'added' | 'error'>('idle');
  const [wishlistItemId, setWishlistItemId] = useState<number | null>(null);
  const [currentWishlistName, setCurrentWishlistName] = useState('');
  const [showRemoveToast, setShowRemoveToast] = useState(false);
  const [removeToastName, setRemoveToastName] = useState('');
  const removeToastTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const [showAuthModal, setShowAuthModal] = useState(false);
  const [authView, setAuthView] = useState<'signup' | 'signin' | 'otp'>('signin');

  const [showToast, setShowToast] = useState(false);
  const [toastWishlistName, setToastWishlistName] = useState('');
  const [toastItemId, setToastItemId] = useState<number | null>(null);
  const [toastCurrentWishlistId, setToastCurrentWishlistId] = useState<string | null>(null);
  const toastTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const [showChangeModal, setShowChangeModal] = useState(false);
  const [changeModalLists, setChangeModalLists] = useState<WishlistSummary[]>([]);
  const [changeModalLoading, setChangeModalLoading] = useState(false);
  const [creatingNew, setCreatingNew] = useState(false);
  const [showCreateWishlistModal, setShowCreateWishlistModal] = useState(false);

  const checkinFromUrl = searchParams.get('checkinDate') ?? '';
  const checkoutFromUrl = searchParams.get('checkoutDate') ?? '';
  const checkinDate = (checkinDateProp ?? checkinFromUrl) || '';
  const checkoutDate = (checkoutDateProp ?? checkoutFromUrl) || '';
  const rooms = parseInt(searchParams.get('rooms') ?? '1', 10) || 1;
  const adults = parseInt(searchParams.get('adults') ?? '2', 10) || 2;
  const children = parseChildrenParam(searchParams.get('children'));

  const hotelId = hotel?.hotelID ?? hotel?.id ?? hotelIdProp ?? '';
  const canAdd = Boolean(checkinDate && checkoutDate && hotelId);
  const normalizeDate = useCallback((value: string | null | undefined) => {
    if (!value) return '';
    // Support both "YYYY-MM-DD" and full ISO timestamps.
    return value.length >= 10 ? value.slice(0, 10) : value;
  }, []);

  const clearToastTimer = useCallback(() => {
    if (toastTimerRef.current) {
      clearTimeout(toastTimerRef.current);
      toastTimerRef.current = null;
    }
  }, []);

  /**
   * Hides the toast UI but keeps the last-added context (item id, wishlist id/name)
   * so the user can still move the item in the Change modal.
   */
  const hideToastUi = useCallback(() => {
    clearToastTimer();
    setShowToast(false);
  }, [clearToastTimer]);

  /**
   * Fully dismisses the toast and clears last-added context.
   * Use this when the item is removed or the user explicitly dismisses it.
   */
  const dismissToast = useCallback(() => {
    clearToastTimer();
    setShowToast(false);
    setToastWishlistName('');
    setToastItemId(null);
    setToastCurrentWishlistId(null);
  }, [clearToastTimer]);

  useEffect(() => {
    setIsMounted(true);
    return () => {
      clearToastTimer();
      const tid = removeToastTimerRef.current;
      if (tid) clearTimeout(tid);
    };
  }, [clearToastTimer]);

  // Allow parent to control initial state (SRP batch lookup).
  useEffect(() => {
    if (initialWishlistItemId === undefined) return;
    setWishlistItemId(initialWishlistItemId);
    setCurrentWishlistName(initialWishlistName ?? '');
    setStatus(initialWishlistItemId != null ? 'added' : 'idle');
  }, [initialWishlistItemId, initialWishlistName]);

  // Controlled state sync (used when the same hotel card has duplicate wishlist buttons).
  useEffect(() => {
    if (controlledWishlistItemId === undefined) return;
    setWishlistItemId(controlledWishlistItemId);
    setCurrentWishlistName(controlledWishlistName ?? '');
    setStatus(controlledWishlistItemId != null ? 'added' : 'idle');
  }, [controlledWishlistItemId, controlledWishlistName]);

  useEffect(() => {
    if (disableAutoLookup) return;
    if (!isAuthenticated || !hotelId) return;
    let isMounted = true;
    (async () => {
      try {
        // Best approach: backend lookup across ANY wishlist.
        try {
          const lookup = await lookupWishlistItem({
            property_code: String(hotelId),
            checkinDate: normalizeDate(checkinDate),
            checkoutDate: normalizeDate(checkoutDate),
          });
          const exists = lookup?.data?.exists ?? lookup?.exists;
          const item = lookup?.data?.item ?? lookup?.item;

          if (isMounted && exists && item?.id != null) {
            const idNum = typeof item.id === 'string' ? Number(item.id) : item.id;
            const wishlist = lookup?.data?.wishlist ?? lookup?.wishlist;
            setWishlistItemId(Number.isFinite(idNum) ? idNum : null);
            setCurrentWishlistName(wishlist?.name ?? 'Wishlist');
            setStatus('added');
            return;
          }

          // If lookup says it doesn't exist, we're done (no need to scan).
          if (isMounted && exists === false) {
            setWishlistItemId(null);
            setStatus('idle');
            return;
          }
        } catch {
          // Lookup endpoint not available yet; fall back to scanning.
        }

        // Fallback scan (only if lookup failed): scan lists until match.
        const lists = await getWishlists();
        const uiCheckin = normalizeDate(checkinDate);
        const uiCheckout = normalizeDate(checkoutDate);
        for (const list of lists ?? []) {
          const items = await getWishlistItems(list.id);
          const match = items.find((it: ExtendedItem) => {
            const propCode =
              (it as unknown as { property_code?: string }).property_code ??
              it.propertyCode ??
              it.rawData?.propertyCode ??
              it.rawData?.property_code;
            if (String(propCode) !== String(hotelId)) return false;
            const itemCheckin = normalizeDate(it.checkinDate ?? it.rawData?.checkinDate);
            const itemCheckout = normalizeDate(it.checkoutDate ?? it.rawData?.checkoutDate);
            if (!itemCheckin || !itemCheckout) return true;
            if (!uiCheckin || !uiCheckout) return true;
            return itemCheckin === uiCheckin && itemCheckout === uiCheckout;
          });
          if (match) {
            const rawId =
              (match as unknown as { rawData?: { id?: number | string }; id?: number | string }).rawData
                ?.id ??
              (match as unknown as { id?: number | string }).id;
            const idNum = typeof rawId === 'string' ? Number(rawId) : rawId;
            setWishlistItemId(typeof idNum === 'number' && Number.isFinite(idNum) ? idNum : null);
            setStatus('added');
            return;
          }
        }

        if (isMounted) {
          setWishlistItemId(null);
          setStatus('idle');
        }
      } catch {
        // ignore
      }
    })();
    return () => {
      isMounted = false;
    };
  }, [disableAutoLookup, isAuthenticated, hotelId, checkinDate, checkoutDate, normalizeDate]);

  const handleClick = async () => {
    if (!isAuthenticated) {
      setAuthView('signin');
      setShowAuthModal(true);
      onLoginClick?.();
      return;
    }
    if (!canAdd) return;

    if (wishlistItemId != null) {
      const nameToShow = currentWishlistName || 'Wishlist';
      setStatus('loading');
      try {
        await removeFromWishlist(wishlistItemId);
        setWishlistItemId(null);
        setCurrentWishlistName('');
        setStatus('idle');
        onWishlistStateChange?.({ wishlistItemId: null, wishlistName: '' });
        dismissToast();
        setRemoveToastName(nameToShow);
        setShowRemoveToast(true);
        if (removeToastTimerRef.current) clearTimeout(removeToastTimerRef.current);
        removeToastTimerRef.current = setTimeout(() => {
          setShowRemoveToast(false);
          removeToastTimerRef.current = null;
        }, REMOVE_TOAST_DURATION_MS);
      } catch {
        setStatus('error');
      }
      return;
    }

    setStatus('loading');
    try {
      // sending first image as a thumbnail 
      const firstImage = hotel?.images?.[0]?.href;
      const resp = await addToWishlist({
        property_code: hotel?.hotelID ?? hotel?.id ?? hotelIdProp ?? '',
        checkinDate,
        checkoutDate,
        rooms,
        adults,
        children: children.length > 0 ? children : undefined,
        ...(firstImage && { thumbnail: firstImage }),
      });
      const raw = resp as unknown as {
        data?: { wishlist?: { id: string; name: string }; item?: { id: number | string } };
        wishlist?: { id: string; name: string };
        item?: { id: number | string };
      };
      const data = raw?.data ?? raw;
      const wishlist = data?.wishlist ?? raw?.wishlist;
      const item = data?.item ?? raw?.item;
      const itemId = item?.id != null ? (typeof item.id === 'string' ? Number(item.id) : item.id) : null;
      const wishlistName = wishlist?.name ?? 'Wishlist';
      const wishlistId = wishlist?.id ?? null;

      if (itemId != null) {
        setWishlistItemId(itemId);
        setCurrentWishlistName(wishlistName);
        setStatus('added');
        onWishlistStateChange?.({ wishlistItemId: itemId, wishlistName });
        setToastWishlistName(wishlistName);
        setToastItemId(itemId);
        setToastCurrentWishlistId(wishlistId);
        setShowToast(true);
        clearToastTimer();
        toastTimerRef.current = setTimeout(() => hideToastUi(), TOAST_DURATION_MS);
      } else {
        setStatus('added');
      }
    } catch {
      setStatus('error');
    }
  };

  const openChangeModal = useCallback(async () => {
    hideToastUi();
    setShowChangeModal(true);
    setChangeModalLoading(true);
    try {
      const lists = await getWishlists();
      setChangeModalLists(lists ?? []);
    } catch {
      setChangeModalLists([]);
    } finally {
      setChangeModalLoading(false);
    }
  }, [hideToastUi]);

  const handleSelectWishlist = useCallback(
    async (targetWishlistId: string) => {
      if (toastItemId == null) {
        return;
      }
      setChangeModalLoading(true);
      try {
        const moved = await moveWishlistItem(toastItemId, targetWishlistId);
        const list = changeModalLists.find((l) => l.id === targetWishlistId);
        const nextWishlistName = list?.name ?? 'Wishlist';
        const movedIdRaw = (moved as unknown as { data?: { id?: number | string } })?.data?.id;
        const movedId =
          movedIdRaw != null ? (typeof movedIdRaw === 'string' ? Number(movedIdRaw) : movedIdRaw) : null;
        if (movedId != null && Number.isFinite(movedId)) {
          setToastItemId(movedId);
          setWishlistItemId(movedId);
          onWishlistStateChange?.({ wishlistItemId: movedId, wishlistName: nextWishlistName });
        }
        setToastWishlistName(nextWishlistName);
        setCurrentWishlistName(nextWishlistName);
        setToastCurrentWishlistId(targetWishlistId);
        setShowChangeModal(false);
      } catch (err) {
        console.error('[Wishlist] Move failed:', err);
      } finally {
        setChangeModalLoading(false);
      }
    },
    [toastItemId, changeModalLists, onWishlistStateChange]
  );

  const handleCreateNewAndMove = useCallback(
    async (name: string) => {
      if (toastItemId == null) return;
      setCreatingNew(true);
      try {
        const newList = await createWishlist(name);
        const moved = await moveWishlistItem(toastItemId, newList.id);
        const movedIdRaw = (moved as unknown as { data?: { id?: number | string } })?.data?.id;
        const movedId =
          movedIdRaw != null ? (typeof movedIdRaw === 'string' ? Number(movedIdRaw) : movedIdRaw) : null;
        if (movedId != null && Number.isFinite(movedId)) {
          setToastItemId(movedId);
          setWishlistItemId(movedId);
          onWishlistStateChange?.({ wishlistItemId: movedId, wishlistName: newList.name ?? 'Wishlist' });
        }
        const newName = newList.name ?? 'Wishlist';
        setToastWishlistName(newName);
        setCurrentWishlistName(newName);
        setToastCurrentWishlistId(newList.id);
      } catch (err) {
        console.error('[Wishlist] Create or move failed:', err);
      } finally {
        setCreatingNew(false);
      }
      setShowCreateWishlistModal(false);
      setShowChangeModal(false);
    },
    [toastItemId, onWishlistStateChange]
  );
  const isDisabled = !canAdd || status === 'loading';

  return (
    <>
      <div
        role="button"
        tabIndex={isDisabled ? -1 : 0}
        onClick={(e) => {
          e.preventDefault();
          e.stopPropagation();
          if (!isDisabled) handleClick();
        }}
        onKeyDown={(e) => {
          if (isDisabled) return;
          if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault();
            handleClick();
          }
        }}
        aria-disabled={isDisabled}
        aria-label={status === 'added' ? 'Remove from wishlist' : 'Add to wishlist'}
        className="d-inline-flex align-items-center justify-content-center border-0 bg-transparent p-0"
        style={{ cursor: isDisabled ? 'default' : 'pointer' }}
      >
        <Heart
          size={22}
          fill={status === 'added' ? '#f45d6b' : 'none'}
          stroke={status === 'added' ? '#f45d6b' : 'currentColor'}
          className={status === 'added' ? 'color-text-first' : 'text-muted'}
        />
      </div>

      {isMounted &&
        showToast &&
        createPortal(
          <div
            className="position-fixed bottom-0 start-50 translate-middle-x mb-4 mx-2"
            style={{ zIndex: 2000, minWidth: 280 }}
          >
            <div className="bg-white shadow-sm rounded-3 p-3 d-flex align-items-center justify-content-between gap-2 border">
              <div className="small text-muted flex-grow-1">
                Added to <strong>{toastWishlistName}</strong>
              </div>
              <div className="d-flex align-items-center gap-1">
                <button
                  type="button"
                  className="buttons btnColor-second p-1 rounded-1 text-sm"
                  onClick={openChangeModal}
                >
                  Change
                </button>
                <button
                  type="button"
                  className="btn btn-sm btn-link text-muted p-0"
                  onClick={dismissToast}
                  aria-label="Dismiss"
                >
                  <X size={18} />
                </button>
              </div>
            </div>
          </div>,
          document.body
        )}

      {isMounted &&
        showRemoveToast &&
        createPortal(
          <div
            className="position-fixed bottom-0 start-50 translate-middle-x mb-4 mx-2"
            style={{ zIndex: 2000, minWidth: 280, maxWidth: 400 }}
          >
            <div className="bg-white border-0 shadow-sm rounded-3 p-3 d-flex align-items-center justify-content-center gap-2">
              <span className="small text-muted">
                Removed from <strong>{removeToastName}</strong>
              </span>
              <button
                type="button"
                className="btn btn-sm btn-link text-muted p-0"
                onClick={() => {
                  if (removeToastTimerRef.current) clearTimeout(removeToastTimerRef.current);
                  setShowRemoveToast(false);
                }}
                aria-label="Dismiss"
              >
                <X size={18} />
              </button>
            </div>
          </div>,
          document.body
        )}

      {isMounted &&
        showChangeModal &&
        createPortal(
          <div
            className="modal d-block"
            style={{ backgroundColor: 'rgba(0,0,0,0.5)', zIndex: 2000 }}
            onClick={() => !changeModalLoading && setShowChangeModal(false)}
            role="dialog"
            aria-modal="true"
            aria-labelledby="change-wishlist-title"
          >
            <div className="modal-dialog modal-dialog-centered" onClick={(e) => e.stopPropagation()}>
              <div className="modal-content rounded-3">
                <div className="modal-header border-0 pb-0">
                  <h5 className="modal-title" id="change-wishlist-title">
                    Move to wishlist
                  </h5>
                  <button
                    type="button"
                    className="btn-close"
                    onClick={() => setShowChangeModal(false)}
                    disabled={changeModalLoading}
                    aria-label="Close"
                  />
                </div>
                <div className="modal-body pt-2">
                  {changeModalLoading && changeModalLists.length === 0 ? (
                    <p className="text-muted small mb-0">Loading wishlists…</p>
                  ) : (
                    <ul className="list-group list-group-flush">
                      <li className="list-group-item border-0 px-0">
                        <button
                          type="button"
                          className="buttons btnColor-second w-100 d-inline-flex align-items-center justify-content-center gap-2 p-2"
                        onClick={() => {
                          setShowChangeModal(false);
                          setShowCreateWishlistModal(true);
                        }}
                          disabled={changeModalLoading || creatingNew}
                        >
                          <Plus size={18} stroke="white" />
                          {creatingNew ? 'Creating…' : 'Create new wishlist'}
                        </button>
                      </li>
                      {changeModalLists.map((list) => (
                        <li key={list.id} className="list-group-item border-0 px-0 py-2">
                          <button
                            type="button"
                            className="btn btn-light w-100 text-start d-flex justify-content-between align-items-center"
                            onClick={() => handleSelectWishlist(list.id)}
                            disabled={changeModalLoading || list.id === toastCurrentWishlistId}
                          >
                            <span>{list.name}</span>
                            {list.id === toastCurrentWishlistId && (
                              <span className="badge bg-secondary">Current</span>
                            )}
                          </button>
                        </li>
                      ))}
                    </ul>
                  )}
                </div>
              </div>
            </div>
          </div>,
          document.body
        )}

      {showAuthModal && (
        <AuthModal
          view={authView}
          setView={setAuthView}
          onClose={() => setShowAuthModal(false)}
          redirectAfterAuth={redirectAfterAuth}
        />
      )}

      {isMounted &&
        createPortal(
          <CreateWishlistModal
            open={showCreateWishlistModal}
            onClose={() => setShowCreateWishlistModal(false)}
            onSubmit={handleCreateNewAndMove}
            isSubmitting={creatingNew}
            title="Create new wishlist"
            confirmLabel="Create & move"
          />,
          document.body
        )}
    </>
  );
}
