import { useEffect, useState } from 'react'
import { Heart } from 'lucide-react'
import { Breadcrumbs, Pagination, useToast } from '@meshkee/dashboard-ui'
import { FavoriteStoreItemCard } from '../components/FavoriteStoreItemCard'
import { useT } from '../i18n/useT'
import { ApiError, isAbortError } from '../lib/api'
import {
  listFavorites,
  removeFavorite,
  type FavoriteListing,
  type FavoritesListResponse,
} from '../services/favoritesService'
import pageStyles from '../components/PageContent.module.css'
import styles from './FavoritesPage.module.css'

const PAGE_SIZE = 24

export function FavoritesPage() {
  const { showToast } = useToast()
  const t = useT()
  const [data, setData] = useState<FavoritesListResponse | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [page, setPage] = useState(1)
  const [removingId, setRemovingId] = useState<string | null>(null)

  useEffect(() => {
    const controller = new AbortController()

    async function load() {
      setLoading(true)
      setError('')

      try {
        const response = await listFavorites({ page, pageSize: PAGE_SIZE }, controller.signal)
        if (controller.signal.aborted) return
        setData(response)
      } catch (err) {
        if (isAbortError(err) || controller.signal.aborted) return
        setError(err instanceof ApiError ? err.message : t('favorites.error.load'))
      } finally {
        if (!controller.signal.aborted) setLoading(false)
      }
    }

    void load()
    return () => controller.abort()
  }, [page, t])

  async function handleRemove(listing: FavoriteListing) {
    setRemovingId(listing.favoriteId)
    try {
      await removeFavorite(listing.productId)
      setData((prev) =>
        prev
          ? {
              ...prev,
              items: prev.items.filter((item) => item.favoriteId !== listing.favoriteId),
              total: Math.max(0, prev.total - 1),
            }
          : prev,
      )
      showToast(t('favorites.toast.removed'), 'success')
    } catch (err) {
      const message =
        err instanceof ApiError ? err.message : t('favorites.error.remove')
      showToast(message, 'error')
    } finally {
      setRemovingId(null)
    }
  }

  function handleAddToCart() {
    showToast(t('favorites.cartSoon'), 'success')
  }

  return (
    <main className={pageStyles.content}>
      <Breadcrumbs
        items={[{ label: t('nav.home'), href: '/' }, { label: t('favorites.title') }]}
      />

      <div className={pageStyles.pageHeader}>
        <div>
          <h2 className={pageStyles.pageTitle}>{t('favorites.title')}</h2>
          <p className={pageStyles.pageSubtitle}>{t('favorites.subtitle')}</p>
        </div>
      </div>

      {error && (
        <div className={styles.error} role="alert">
          {error}
        </div>
      )}

      {loading && <p className={styles.status}>{t('favorites.loading')}</p>}

      {!loading && data?.items.length === 0 && (
        <div className={styles.empty}>
          <Heart size={32} />
          <p>{t('favorites.empty')}</p>
        </div>
      )}

      {!!data?.items.length && (
        <div className={styles.grid}>
          {data.items.map((listing) => (
            <FavoriteStoreItemCard
              key={listing.favoriteId}
              listing={listing}
              onRemove={handleRemove}
              onAddToCart={handleAddToCart}
              removing={removingId === listing.favoriteId}
            />
          ))}
        </div>
      )}

      {data && data.total > PAGE_SIZE && (
        <Pagination
          currentPage={page}
          totalPages={Math.max(1, Math.ceil(data.total / data.pageSize))}
          onPageChange={setPage}
          disabled={loading}
        />
      )}
    </main>
  )
}
