import { useEffect, useMemo, useState } from 'react'
import { Breadcrumbs, Pagination, useLocale } from '@meshkee/dashboard-ui'
import { OrderItemsModal } from '../components/OrderItemsModal'
import { OrderRow } from '../components/OrderRow'
import { useT } from '../i18n/useT'
import { ApiError, isAbortError } from '../lib/api'
import {
  listOrders,
  type Order,
  type OrdersListResponse,
} from '../services/orderService'
import { DEFAULT_ORDER_PROCESS_STEPS } from '../utils/orderSteps'
import pageStyles from '../components/PageContent.module.css'
import styles from './OrdersPage.module.css'

const PAGE_SIZE = 20
const COLUMN_COUNT = 7

export function OrdersPage() {
  const t = useT()
  const { locale } = useLocale()
  const [data, setData] = useState<OrdersListResponse | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [page, setPage] = useState(1)
  const [viewOrder, setViewOrder] = useState<Order | null>(null)

  const processSteps = DEFAULT_ORDER_PROCESS_STEPS

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

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

      try {
        const response = await listOrders({ 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('orders.error.load'))
      } finally {
        if (!controller.signal.aborted) setLoading(false)
      }
    }

    void load()
    return () => controller.abort()
  }, [page, 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])

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

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

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

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

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

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

              {!loading &&
                data?.items.map((order) => (
                  <OrderRow
                    key={order.id}
                    order={order}
                    processSteps={processSteps}
                    onViewItems={setViewOrder}
                  />
                ))}
            </tbody>
          </table>

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

      <OrderItemsModal
        open={viewOrder !== null}
        order={viewOrder}
        onClose={() => setViewOrder(null)}
      />
    </main>
  )
}
