import { useEffect, useMemo, useState } from 'react'
import { Play, RotateCcw, Search, Trash2 } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import { useLocale } from '@meshkee/dashboard-ui'
import { Breadcrumbs } from '../components/Breadcrumbs'
import { ConfirmDeleteModal } from '../components/ConfirmDeleteModal'
import { Pagination } from '../components/Pagination'
import { Tooltip } from '../components/Tooltip'
import { useToast } from '../context/ToastContext'
import { useT } from '../i18n/useT'
import { ApiError, isAbortError } from '../lib/api'
import { formatCellForDisplay } from '../lib/cellNumber'
import {
  listShoppingCards,
  removeShoppingCard,
  type ShoppingCard,
  type ShoppingCardsListResponse,
} from '../services/shoppingCardService'
import { RESUME_SHOPPING_CARD_KEY } from '../types/draftCart'
import { formatIrtInput, formatIrtPrice, parseIrtInput } from '../utils/irtPrice'
import filterStyles from '../components/ListFiltersPanel.module.css'
import pageStyles from '../components/PageContent.module.css'
import tableStyles from './OrdersPage.module.css'
import styles from './ShoppingCardsPage.module.css'

const PAGE_SIZE = 24
const COLUMN_COUNT = 5

interface AppliedFilters {
  customerQuery?: string
  dateFrom?: string
  dateTo?: string
  minTotal?: number
  maxTotal?: number
}

function displayName(card: ShoppingCard) {
  const name = [card.customer.firstName, card.customer.lastName]
    .filter(Boolean)
    .join(' ')
    .trim()
  return name || '—'
}

function formatDateTime(value: string, locale: 'en' | 'fa') {
  const d = new Date(value)
  if (Number.isNaN(d.getTime())) return { date: value, time: '' }
  const intlLocale = locale === 'fa' ? 'fa-IR' : 'en-US'
  return {
    date: d.toLocaleDateString(intlLocale, { year: 'numeric', month: 'short', day: '2-digit' }),
    time: d.toLocaleTimeString(intlLocale, { hour: '2-digit', minute: '2-digit' }),
  }
}

function totalItemQuantity(card: ShoppingCard) {
  return card.items.reduce((sum, item) => sum + item.quantity, 0)
}

export function ShoppingCardsPage() {
  const t = useT()
  const { locale } = useLocale()
  const navigate = useNavigate()
  const { showToast } = useToast()
  const [data, setData] = useState<ShoppingCardsListResponse | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  const [appliedFilters, setAppliedFilters] = useState<AppliedFilters>({})
  const [page, setPage] = useState(1)

  const [draftCustomer, setDraftCustomer] = useState('')
  const [draftDateFrom, setDraftDateFrom] = useState('')
  const [draftDateTo, setDraftDateTo] = useState('')
  const [draftMinCost, setDraftMinCost] = useState('')
  const [draftMaxCost, setDraftMaxCost] = useState('')

  const [removeTarget, setRemoveTarget] = useState<ShoppingCard | null>(null)
  const [removing, setRemoving] = useState(false)

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

    async function load() {
      setLoading(true)
      setError('')
      try {
        const result = await listShoppingCards(
          {
            page,
            pageSize: PAGE_SIZE,
            ...appliedFilters,
          },
          controller.signal,
        )
        if (controller.signal.aborted) return
        setData(result)
      } catch (err) {
        if (isAbortError(err) || controller.signal.aborted) return
        setError(err instanceof ApiError ? err.message : t('shoppingCards.error.load'))
      } finally {
        if (!controller.signal.aborted) setLoading(false)
      }
    }

    void load()

    return () => {
      controller.abort()
    }
  }, [
    page,
    appliedFilters.customerQuery,
    appliedFilters.dateFrom,
    appliedFilters.dateTo,
    appliedFilters.minTotal,
    appliedFilters.maxTotal,
    t,
  ])

  const totalPages = useMemo(() => {
    const total = data?.total ?? 0
    return Math.max(1, Math.ceil(total / PAGE_SIZE))
  }, [data?.total])

  const showingFrom = useMemo(() => {
    if (!data || data.total === 0) return 0
    return (page - 1) * PAGE_SIZE + 1
  }, [data, page])

  const showingTo = useMemo(() => {
    if (!data) return 0
    return Math.min(data.total, page * PAGE_SIZE)
  }, [data, page])

  function applyFilters() {
    const minTotal = parseIrtInput(draftMinCost)
    const maxTotal = parseIrtInput(draftMaxCost)

    if (minTotal !== null && maxTotal !== null && minTotal > maxTotal) {
      setError(t('orders.error.minMax'))
      return
    }

    setPage(1)
    setAppliedFilters({
      ...(draftCustomer.trim() ? { customerQuery: draftCustomer.trim() } : {}),
      ...(draftDateFrom ? { dateFrom: draftDateFrom } : {}),
      ...(draftDateTo ? { dateTo: draftDateTo } : {}),
      ...(minTotal !== null ? { minTotal } : {}),
      ...(maxTotal !== null ? { maxTotal } : {}),
    })
  }

  function clearFilters() {
    setDraftCustomer('')
    setDraftDateFrom('')
    setDraftDateTo('')
    setDraftMinCost('')
    setDraftMaxCost('')
    setPage(1)
    setAppliedFilters({})
    setError('')
  }

  function handleContinue(card: ShoppingCard) {
    sessionStorage.setItem(RESUME_SHOPPING_CARD_KEY, JSON.stringify(card))
    navigate('/store/items')
  }

  async function confirmRemove() {
    if (!removeTarget) return
    setRemoving(true)
    setError('')
    try {
      await removeShoppingCard(removeTarget.id)
      setData((prev) => {
        if (!prev) return prev
        return {
          ...prev,
          total: Math.max(0, prev.total - 1),
          items: prev.items.filter((item) => item.id !== removeTarget.id),
        }
      })
      showToast(t('shoppingCards.removed'), 'success')
      setRemoveTarget(null)
    } catch (err) {
      setError(err instanceof ApiError ? err.message : t('shoppingCards.error.remove'))
    } finally {
      setRemoving(false)
    }
  }

  return (
    <main className={pageStyles.content}>
      <Breadcrumbs
        items={[
          { label: 'Home', href: '/' },
          { label: 'Store', href: '/store' },
          { label: 'Shopping Cards' },
        ]}
      />

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

      <div className={filterStyles.filtersPanel}>
        <div className={filterStyles.filtersTitle}>{t('orders.filters')}</div>
        <div className={filterStyles.filtersGrid}>
          <div className={styles.filtersRow}>
            <div className={`${filterStyles.field} ${styles.filterCustomer}`}>
              <input
                id="filter-card-customer"
                value={draftCustomer}
                onChange={(e) => setDraftCustomer(e.target.value)}
                placeholder={t('orders.filter.customer')}
                aria-label={t('orders.filter.customer')}
                autoComplete="off"
              />
            </div>
            <div className={`${filterStyles.field} ${styles.filterDate}`}>
              <input
                id="filter-card-date-from"
                type="date"
                value={draftDateFrom}
                onChange={(e) => setDraftDateFrom(e.target.value)}
                aria-label={t('orders.filter.dateFrom')}
                title={t('orders.filter.dateFrom')}
              />
            </div>
            <div className={`${filterStyles.field} ${styles.filterDate}`}>
              <input
                id="filter-card-date-to"
                type="date"
                value={draftDateTo}
                onChange={(e) => setDraftDateTo(e.target.value)}
                aria-label={t('orders.filter.dateTo')}
                title={t('orders.filter.dateTo')}
              />
            </div>
            <div className={`${filterStyles.field} ${styles.filterCost}`}>
              <input
                id="filter-card-min-cost"
                type="text"
                inputMode="numeric"
                value={draftMinCost}
                onChange={(e) => setDraftMinCost(formatIrtInput(e.target.value))}
                placeholder={t('orders.filter.minCost')}
                aria-label={t('orders.filter.minCost')}
                autoComplete="off"
              />
            </div>
            <div className={`${filterStyles.field} ${styles.filterCost}`}>
              <input
                id="filter-card-max-cost"
                type="text"
                inputMode="numeric"
                value={draftMaxCost}
                onChange={(e) => setDraftMaxCost(formatIrtInput(e.target.value))}
                placeholder={t('orders.filter.maxCost')}
                aria-label={t('orders.filter.maxCost')}
                autoComplete="off"
              />
            </div>
          </div>
          <div className={filterStyles.filterActions}>
            <button
              type="button"
              className={`${filterStyles.iconActionBtn} ${filterStyles.iconActionBtnPrimary}`}
              onClick={applyFilters}
              disabled={loading}
              aria-label={t('orders.search')}
              title={t('orders.search')}
            >
              <Search size={18} />
            </button>
            <button
              type="button"
              className={`${filterStyles.iconActionBtn} ${filterStyles.iconActionBtnGhost}`}
              onClick={clearFilters}
              disabled={loading}
              aria-label={t('orders.clearFilters')}
              title={t('orders.clearFilters')}
            >
              <RotateCcw size={18} />
            </button>
          </div>
        </div>
      </div>

      <div className={tableStyles.tablePanel}>
        <div className={tableStyles.tableWrap}>
          <div className={tableStyles.tableHeader}>
            <div className={tableStyles.tableHeaderTitle}>{t('shoppingCards.listTitle')}</div>
            <div className={tableStyles.meta}>
              {data ? (
                data.total > 0 ? (
                  t('orders.showing', {
                    from: showingFrom,
                    to: showingTo,
                    total: data.total,
                  })
                ) : (
                  t('shoppingCards.none')
                )
              ) : (
                ' '
              )}
            </div>
          </div>

          {error && <div className={tableStyles.errorBanner}>{error}</div>}

          <table className={tableStyles.table} dir={locale === 'fa' ? 'rtl' : 'ltr'}>
            <colgroup>
              <col className={styles.colCustomer} />
              <col className={styles.colItems} />
              <col className={styles.colTotal} />
              <col className={styles.colDate} />
              <col className={styles.colActions} />
            </colgroup>
            <thead>
              <tr>
                <th className={tableStyles.th}>{t('orders.col.customer')}</th>
                <th className={tableStyles.th}>{t('orders.col.items')}</th>
                <th className={tableStyles.th}>{t('orders.col.total')}</th>
                <th className={tableStyles.th}>{t('orders.col.date')}</th>
                <th className={`${tableStyles.th} ${tableStyles.thActions}`}>
                  {t('orders.col.actions')}
                </th>
              </tr>
            </thead>
            <tbody>
              {loading && (
                <tr>
                  <td className={tableStyles.td} colSpan={COLUMN_COUNT}>
                    {t('shoppingCards.loading')}
                  </td>
                </tr>
              )}

              {!loading && data?.items?.length === 0 && (
                <tr>
                  <td className={tableStyles.td} colSpan={COLUMN_COUNT}>
                    {t('shoppingCards.empty')}
                  </td>
                </tr>
              )}

              {!loading &&
                data?.items?.map((card) => {
                  const { date, time } = formatDateTime(card.createdAt, locale)
                  const itemQty = totalItemQuantity(card)

                  return (
                    <tr key={card.id}>
                      <td className={tableStyles.td}>
                        <div className={tableStyles.customerName}>{displayName(card)}</div>
                        <div className={tableStyles.customerCell}>
                          {formatCellForDisplay(card.customer.cellNumber)}
                        </div>
                      </td>
                      <td className={tableStyles.td}>
                        {itemQty > 0 ? itemQty : <span className={tableStyles.subText}>0</span>}
                      </td>
                      <td className={tableStyles.td}>{formatIrtPrice(card.total)}</td>
                      <td className={`${tableStyles.td} ${tableStyles.dateCell}`}>
                        <div className={tableStyles.dateTime}>{date}</div>
                        {time && <div className={tableStyles.dateTimeSub}>{time}</div>}
                      </td>
                      <td className={`${tableStyles.td} ${tableStyles.tdActions}`}>
                        <div className={tableStyles.rowActions}>
                          <Tooltip label={t('shoppingCards.continue')}>
                            <button
                              type="button"
                              className={tableStyles.actionBtn}
                              onClick={() => handleContinue(card)}
                              aria-label={t('shoppingCards.continueAria')}
                            >
                              <Play size={15} />
                            </button>
                          </Tooltip>
                          <Tooltip label={t('shoppingCards.remove')}>
                            <button
                              type="button"
                              className={`${tableStyles.actionBtn} ${tableStyles.actionBtnDanger}`}
                              onClick={() => setRemoveTarget(card)}
                              aria-label={t('shoppingCards.removeAria')}
                              disabled={removing}
                            >
                              <Trash2 size={15} />
                            </button>
                          </Tooltip>
                        </div>
                      </td>
                    </tr>
                  )
                })}
            </tbody>
          </table>

          <div className={tableStyles.pagination}>
            <div>
              {t('orders.pageMeta', {
                page,
                totalPages,
                pageSize: PAGE_SIZE,
                total: data?.total ?? 0,
              })}
            </div>
            <Pagination
              currentPage={page}
              totalPages={totalPages}
              onPageChange={setPage}
              disabled={loading}
              variant="inline"
            />
          </div>
        </div>
      </div>

      <ConfirmDeleteModal
        open={removeTarget !== null}
        title={t('shoppingCards.deleteTitle')}
        message={
          removeTarget
            ? t('shoppingCards.deleteMessage', { name: displayName(removeTarget) })
            : ''
        }
        onCancel={() => setRemoveTarget(null)}
        onConfirm={() => void confirmRemove()}
      />
    </main>
  )
}
