import { useEffect, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { Package, Plus } from 'lucide-react'
import { Pagination } from '@meshkee/dashboard-ui'
import { Breadcrumbs } from '../components/Breadcrumbs'
import { UserProductCard } from '../components/UserProductCard'
import { UserProductStatusModal } from '../components/UserProductStatusModal'
import { useToast } from '../context/ToastContext'
import { useT } from '../i18n/useT'
import { ApiError, isAbortError } from '../lib/api'
import {
  deleteUserProduct,
  listUserProducts,
  promoteUserProduct,
  updateUserProductStatus,
  type UserProductsListResponse,
} from '../services/userProductsService'
import type { UserProductStatus } from '../types/userProduct'
import pageStyles from '../components/PageContent.module.css'
import styles from './CustomerProductsPage.module.css'

const PAGE_SIZE = 24

export function CustomerProductsPage() {
  const t = useT()
  const navigate = useNavigate()
  const { showToast } = useToast()
  const [data, setData] = useState<UserProductsListResponse | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [page, setPage] = useState(1)
  const [busyId, setBusyId] = useState<string | null>(null)
  const [busyAction, setBusyAction] = useState<
    'remove' | 'promote' | 'status' | null
  >(null)
  const [statusProductId, setStatusProductId] = useState<string | null>(null)

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

    async function load() {
      setLoading(true)
      setError('')
      try {
        const response = await listUserProducts(
          { 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('customerProducts.error.load'),
        )
      } finally {
        if (!controller.signal.aborted) setLoading(false)
      }
    }

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

  const products = data?.items ?? []
  const total = data?.total ?? 0
  const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE))
  const statusProduct = products.find((item) => item.id === statusProductId)

  function handleEdit(id: string) {
    navigate(`/customer-products/${id}/edit`)
  }

  async function handleRemove(id: string) {
    if (!window.confirm(t('customerProducts.removeConfirm'))) return

    setBusyId(id)
    setBusyAction('remove')
    try {
      await deleteUserProduct(id)
      setData((prev) =>
        prev
          ? {
              ...prev,
              items: prev.items.filter((item) => item.id !== id),
              total: Math.max(0, prev.total - 1),
            }
          : prev,
      )
      showToast(t('customerProducts.removeSuccess'), 'success')
    } catch (err) {
      showToast(
        err instanceof ApiError
          ? err.message
          : t('customerProducts.error.remove'),
        'error',
      )
    } finally {
      setBusyId(null)
      setBusyAction(null)
    }
  }

  async function handlePromote(id: string) {
    setBusyId(id)
    setBusyAction('promote')
    try {
      const response = await promoteUserProduct(id)
      setData((prev) =>
        prev
          ? {
              ...prev,
              items: prev.items.map((item) =>
                item.id === id ? { ...item, ...response.product } : item,
              ),
            }
          : prev,
      )
      showToast(t('customerProducts.promoteSuccess'), 'success')
    } catch (err) {
      showToast(
        err instanceof ApiError
          ? err.message
          : t('customerProducts.error.promote'),
        'error',
      )
    } finally {
      setBusyId(null)
      setBusyAction(null)
    }
  }

  async function handleStatusSave(status: UserProductStatus) {
    if (!statusProductId) return
    setBusyId(statusProductId)
    setBusyAction('status')
    try {
      const response = await updateUserProductStatus(statusProductId, status)
      setData((prev) =>
        prev
          ? {
              ...prev,
              items: prev.items.map((item) =>
                item.id === statusProductId
                  ? { ...item, ...response.product }
                  : item,
              ),
            }
          : prev,
      )
      showToast(t('customerProducts.statusSuccess'), 'success')
      setStatusProductId(null)
    } catch (err) {
      showToast(
        err instanceof ApiError
          ? err.message
          : t('customerProducts.error.status'),
        'error',
      )
    } finally {
      setBusyId(null)
      setBusyAction(null)
    }
  }

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

      <div className={pageStyles.pageHeader}>
        <div>
          <h2 className={pageStyles.pageTitle}>{t('customerProducts.title')}</h2>
          <p className={pageStyles.pageSubtitle}>
            {t('customerProducts.subtitle', { count: total })}
          </p>
        </div>
      </div>

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

      {loading ? <p className={styles.status}>{t('customerProducts.loading')}</p> : null}

      {!loading && !error && products.length === 0 ? (
        <div className={styles.empty}>
          <Package size={32} />
          <p>{t('customerProducts.empty')}</p>
          <Link to="/customer-products/new" className={styles.emptyLink}>
            {t('customerProducts.add')}
          </Link>
        </div>
      ) : null}

      {!loading && products.length > 0 ? (
        <>
          <div className={styles.grid}>
            {products.map((product) => (
              <UserProductCard
                key={product.id}
                product={product}
                to={`/customer-products/${product.id}`}
                onEdit={handleEdit}
                onPromote={handlePromote}
                onChangeStatus={setStatusProductId}
                onRemove={handleRemove}
                busyAction={busyId === product.id ? busyAction : null}
              />
            ))}
          </div>
          {totalPages > 1 ? (
            <Pagination
              currentPage={page}
              totalPages={totalPages}
              onPageChange={setPage}
              disabled={loading}
            />
          ) : null}
        </>
      ) : null}

      <div className={styles.fabDock}>
        <Link
          to="/customer-products/new"
          className={styles.addFab}
          aria-label={t('customerProducts.add')}
        >
          <Plus size={22} />
        </Link>
      </div>

      <UserProductStatusModal
        open={Boolean(statusProduct)}
        currentStatus={statusProduct?.status ?? 'draft'}
        saving={busyAction === 'status'}
        onClose={() => setStatusProductId(null)}
        onSave={(status) => void handleStatusSave(status)}
      />
    </main>
  )
}
