import { useCallback, useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { apiClient } from '../../api/client'
import PageMeta from '../../components/common/PageMeta'
import PageBreadcrumb from '../../components/common/PageBreadCrumb'
import Badge from '../../components/ui/badge/Badge'
import { DateRangeFilter } from '../../components/DateRangeFilter'
import { Pagination } from '../../components/Pagination'
import { SortableTh, type SortOrder } from '../../components/ui/table'
import { TableSkeleton } from '../../components/ui/skeleton'
import TableCheckbox from '../../components/form/input/TableCheckbox'
import { IfPermission } from '../../components/auth/RequirePermission'

interface MetalItem {
  id: number
  transaction_number: string
  order_id: number
  product_id: number
  grams: number
  status: string
  notes?: string
  created_at?: string
  order?: {
    id: number
    order_number: string
    order_type: string
    user?: { id: number; name: string; mobile?: string }
  }
  product?: { id: number; name: string }
}

const statusLabels: Record<string, string> = {
  IN_PROGRESS: 'در حال پردازش',
  WEIGHED: 'وزن‌کشی شده',
  DELIVERED_RECEIVED: 'تحویل/دریافت داده شده',
}

const getStatusBadge = (status: string) => {
  const colorMap: Record<string, 'primary' | 'success' | 'warning' | 'light'> = {
    IN_PROGRESS: 'warning',
    WEIGHED: 'primary',
    DELIVERED_RECEIVED: 'success',
  }
  return (
    <Badge color={colorMap[status] || 'light'} variant="light" size="sm">
      {statusLabels[status] || status}
    </Badge>
  )
}

const formatNum = (n: number) => new Intl.NumberFormat('fa-IR', { maximumFractionDigits: 3 }).format(n)

export const MetalsPage = () => {
  const [searchParams, setSearchParams] = useSearchParams()
  const [items, setItems] = useState<MetalItem[]>([])
  const [loading, setLoading] = useState(true)
  const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set())
  const [bulkDeleting, setBulkDeleting] = useState(false)
  const [deletingId, setDeletingId] = useState<number | null>(null)

  const [search, setSearch] = useState(searchParams.get('search') || '')
  const [orderIdFilter, setOrderIdFilter] = useState(searchParams.get('order_id') || '')
  const [statusFilter, setStatusFilter] = useState(searchParams.get('status') || '')
  const [fromDate, setFromDate] = useState(searchParams.get('from_date') || '')
  const [toDate, setToDate] = useState(searchParams.get('to_date') || '')
  const [page, setPage] = useState(Number(searchParams.get('page')) || 1)
  const [perPage, setPerPage] = useState(Number(searchParams.get('per_page')) || 20)
  const [sortBy, setSortBy] = useState<string | null>(searchParams.get('sort') || 'id')
  const [sortOrder, setSortOrder] = useState<SortOrder>((searchParams.get('order') as SortOrder) || 'desc')
  const [pagination, setPagination] = useState<{
    current_page: number
    last_page: number
    per_page: number
    total: number
  } | null>(null)

  const handleSort = (key: string) => {
    setSortBy(key)
    setSortOrder((prev) => (prev === 'asc' ? 'desc' : 'asc'))
    setPage(1)
    setSelectedIds(new Set())
  }

  const load = useCallback(async () => {
    try {
      setLoading(true)
      const params = new URLSearchParams()
      if (orderIdFilter) params.set('order_id', orderIdFilter)
      if (statusFilter) params.set('status', statusFilter)
      if (fromDate) params.set('from_date', fromDate)
      if (toDate) params.set('to_date', toDate)
      params.set('page', String(page))
      params.set('per_page', String(perPage))
      if (sortBy) params.set('sort', sortBy)
      params.set('order', sortOrder)

      const res = await apiClient.get(`/metals?${params.toString()}`)
      const paginatedData =
        res && typeof res === 'object' && 'current_page' in res ? res : (res?.data ?? res)

      if (paginatedData && typeof paginatedData === 'object' && 'data' in paginatedData) {
        const data = (paginatedData as { data: MetalItem[] }).data ?? []
        setItems(Array.isArray(data) ? data : [])
        setPagination({
          current_page: (paginatedData as { current_page: number }).current_page,
          last_page: (paginatedData as { last_page: number }).last_page,
          per_page: (paginatedData as { per_page: number }).per_page,
          total: (paginatedData as { total: number }).total,
        })
      } else {
        const list = Array.isArray(paginatedData) ? paginatedData : (paginatedData?.data ?? [])
        setItems(Array.isArray(list) ? list : [])
        setPagination(null)
      }
    } finally {
      setLoading(false)
    }
  }, [orderIdFilter, statusFilter, fromDate, toDate, page, perPage, sortBy, sortOrder])

  useEffect(() => {
    load()
  }, [load])

  useEffect(() => {
    const params = new URLSearchParams()
    if (search) params.set('search', search)
    if (orderIdFilter) params.set('order_id', orderIdFilter)
    if (statusFilter) params.set('status', statusFilter)
    if (fromDate) params.set('from_date', fromDate)
    if (toDate) params.set('to_date', toDate)
    if (page > 1) params.set('page', String(page))
    if (perPage !== 20) params.set('per_page', String(perPage))
    if (sortBy && sortBy !== 'id') params.set('sort', sortBy)
    if (sortOrder !== 'desc') params.set('order', sortOrder)
    setSearchParams(params, { replace: true })
  }, [search, orderIdFilter, statusFilter, fromDate, toDate, page, perPage, sortBy, sortOrder, setSearchParams])

  const filteredItems = items.filter((row) => {
    if (!search) return true
    const q = search.toLowerCase()
    return (
      row.transaction_number?.toLowerCase().includes(q) ||
      row.order?.order_number?.toLowerCase().includes(q) ||
      row.order?.user?.name?.toLowerCase().includes(q) ||
      row.order?.user?.mobile?.toLowerCase().includes(q) ||
      row.product?.name?.toLowerCase().includes(q) ||
      String(row.grams).includes(search) ||
      row.notes?.toLowerCase().includes(q)
    )
  })

  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedIds(new Set(filteredItems.map((item) => item.id)))
    } else {
      setSelectedIds(new Set())
    }
  }

  const handleSelectOne = (id: number, checked: boolean) => {
    const newSelected = new Set(selectedIds)
    if (checked) {
      newSelected.add(id)
    } else {
      newSelected.delete(id)
    }
    setSelectedIds(newSelected)
  }

  const handleBulkDelete = async () => {
    if (selectedIds.size === 0) return

    if (!confirm(`آیا از حذف ${selectedIds.size} تراکنش فلز انتخاب شده اطمینان دارید؟`)) {
      return
    }

    setBulkDeleting(true)
    try {
      await Promise.all(Array.from(selectedIds).map((id) => apiClient.delete(`/metals/${id}`)))
      await load()
      setSelectedIds(new Set())
    } catch (err: any) {
      alert(err.response?.data?.message || 'خطا در حذف تراکنش‌های فلز')
    } finally {
      setBulkDeleting(false)
    }
  }

  const handleDelete = async (row: MetalItem) => {
    if (
      !confirm(
        `آیا از حذف فلز ${row.transaction_number} اطمینان دارید؟${
          row.status === 'DELIVERED_RECEIVED'
            ? '\nاثر این مورد از موجودی انبار برگردانده می‌شود.'
            : ''
        }`
      )
    )
      return
    setDeletingId(row.id)
    try {
      await apiClient.delete(`/metals/${row.id}`)
      await load()
    } finally {
      setDeletingId(null)
    }
  }

  const allSelected = filteredItems.length > 0 && filteredItems.every((item) => selectedIds.has(item.id))
  const someSelected = selectedIds.size > 0

  const hasActiveFilters = !!(orderIdFilter || statusFilter || fromDate || toDate)

  return (
    <>
      <PageMeta title="فلز | آیرون" description="لیست دریافت/تحویل فلز" />
      <PageBreadcrumb pageTitle="فلز" />

      {/* Header */}
      <div className="mb-6 flex flex-wrap items-center justify-between gap-4">
        <div>
          <h2 className="text-xl font-semibold text-gray-800 dark:text-white/90">
            لیست فلز
            <span className="mr-2 font-normal text-gray-500 dark:text-gray-400">
              (
              {pagination?.total != null
                ? new Intl.NumberFormat('fa-IR').format(pagination.total)
                : loading
                  ? '…'
                  : '۰'}{' '}
              مورد)
            </span>
          </h2>
          <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
            ثبت دریافت یا تحویل فلز برای سفارشات. با وضعیت «تحویل/دریافت داده شده» موجودی انبار به‌روز می‌شود.
          </p>
        </div>
        <IfPermission permission="create_metals">
          <Link
            to="/metals/new"
            className="inline-flex items-center gap-2 rounded-lg bg-brand-500 px-4 py-2.5 text-sm font-medium text-white shadow-theme-xs hover:bg-brand-600"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
            فلز جدید
          </Link>
        </IfPermission>
      </div>

      {/* Search and Filters */}
      <div className="mb-4 flex flex-wrap items-center gap-3">
        <div className="relative min-w-[200px] flex-1">
          <svg
            className="absolute right-3 top-1/2 h-5 w-5 -translate-y-1/2 text-gray-400"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
          <input
            type="text"
            placeholder="جستجو در شماره، سفارش، مشتری، محصول، گرم..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="h-10 w-full rounded-lg border border-gray-200 bg-white pr-10 pl-4 text-sm text-gray-800 placeholder:text-gray-400 focus:border-brand-300 focus:outline-none focus:ring-3 focus:ring-brand-500/10 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
          />
        </div>

        <input
          type="text"
          placeholder="شماره سفارش"
          value={orderIdFilter}
          onChange={(e) => {
            setOrderIdFilter(e.target.value)
            setPage(1)
          }}
          className="h-10 w-32 rounded-lg border border-gray-200 bg-white px-3 text-sm text-gray-800 focus:border-brand-300 focus:outline-none focus:ring-3 focus:ring-brand-500/10 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
        />

        <select
          value={statusFilter}
          onChange={(e) => {
            setStatusFilter(e.target.value)
            setPage(1)
          }}
          className="h-10 rounded-lg border border-gray-200 bg-white px-3 text-sm text-gray-800 focus:border-brand-300 focus:outline-none focus:ring-3 focus:ring-brand-500/10 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
        >
          <option value="">همه وضعیت‌ها</option>
          {Object.entries(statusLabels).map(([value, label]) => (
            <option key={value} value={value}>
              {label}
            </option>
          ))}
        </select>

        <DateRangeFilter
          startDate={fromDate}
          endDate={toDate}
          onStartDateChange={setFromDate}
          onEndDateChange={setToDate}
        />

        {hasActiveFilters && (
          <button
            type="button"
            onClick={() => {
              setOrderIdFilter('')
              setStatusFilter('')
              setFromDate('')
              setToDate('')
              setPage(1)
            }}
            className="h-10 rounded-lg border border-gray-200 bg-white px-3 text-sm text-gray-600 hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-400 dark:hover:bg-gray-800"
          >
            پاک کردن فیلترها
          </button>
        )}
      </div>

      {/* Bulk Actions Bar */}
      {someSelected && (
        <div className="mb-4 flex flex-wrap items-center justify-between gap-3 rounded-xl border border-purple-200 bg-purple-50 p-4 dark:border-purple-800 dark:bg-purple-900/20">
          <div className="flex items-center gap-3">
            <span className="text-sm font-medium text-purple-700 dark:text-purple-300">
              {selectedIds.size.toLocaleString('fa-IR')} تراکنش فلز انتخاب شده
            </span>
          </div>
          <div className="flex flex-wrap items-center gap-2">
            <IfPermission permission="delete_metals">
              <button
                onClick={handleBulkDelete}
                disabled={bulkDeleting}
                className="rounded-lg bg-red-500 px-4 py-2 text-sm font-medium text-white hover:bg-red-600 disabled:opacity-50"
              >
                {bulkDeleting ? 'در حال حذف...' : `حذف ${selectedIds.size} مورد`}
              </button>
            </IfPermission>
            <button
              onClick={() => setSelectedIds(new Set())}
              className="rounded-lg border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-300"
            >
              لغو انتخاب
            </button>
          </div>
        </div>
      )}

      {/* Table Card */}
      <div className="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
        {loading ? (
          <TableSkeleton rows={8} cols={9} showCheckbox />
        ) : filteredItems.length === 0 ? (
          <div className="py-12 text-center">
            <svg
              className="mx-auto h-12 w-12 text-gray-400"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={1.5}
                d="M20 7l-8 4-8-4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"
              />
            </svg>
            <p className="mt-4 text-sm text-gray-500 dark:text-gray-400">
              {search || hasActiveFilters
                ? 'موردی با این فیلترها یافت نشد.'
                : 'فلزی ثبت نشده است. برای ثبت فلز جدید از دکمه بالا استفاده کنید.'}
            </p>
          </div>
        ) : (
          <>
            <div className="table-mobile-cards">
              <table className="w-full min-w-[800px]">
                <thead>
                  <tr className="border-b border-gray-200 dark:border-gray-800">
                    <th className="w-12 px-5 py-4 text-right">
                      <TableCheckbox checked={allSelected} onChange={handleSelectAll} />
                    </th>
                    <SortableTh
                      sortKey="transaction_number"
                      currentSortBy={sortBy}
                      currentSortOrder={sortOrder}
                      onSort={handleSort}
                      className="px-5 py-4 text-right"
                    >
                      شماره
                    </SortableTh>
                    <th className="px-5 py-4 text-right text-sm font-medium text-gray-500 dark:text-gray-400">
                      سفارش
                    </th>
                    <th className="px-5 py-4 text-right text-sm font-medium text-gray-500 dark:text-gray-400">
                      مشتری
                    </th>
                    <th className="px-5 py-4 text-right text-sm font-medium text-gray-500 dark:text-gray-400">
                      محصول
                    </th>
                    <SortableTh
                      sortKey="grams"
                      currentSortBy={sortBy}
                      currentSortOrder={sortOrder}
                      onSort={handleSort}
                      className="px-5 py-4 text-right"
                    >
                      گرم
                    </SortableTh>
                    <SortableTh
                      sortKey="status"
                      currentSortBy={sortBy}
                      currentSortOrder={sortOrder}
                      onSort={handleSort}
                      className="px-5 py-4 text-right"
                    >
                      وضعیت
                    </SortableTh>
                    <SortableTh
                      sortKey="created_at"
                      currentSortBy={sortBy}
                      currentSortOrder={sortOrder}
                      onSort={handleSort}
                      className="px-5 py-4 text-right"
                    >
                      تاریخ ثبت
                    </SortableTh>
                    <th className="px-5 py-4 text-right text-sm font-medium text-gray-500 dark:text-gray-400">
                      عملیات
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200 dark:divide-gray-800">
                  {filteredItems.map((row) => (
                    <tr key={row.id} className="hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                      <td className="px-5 py-4 table-mobile-checkbox" data-label="انتخاب">
                        <TableCheckbox
                          checked={selectedIds.has(row.id)}
                          onChange={(checked) => handleSelectOne(row.id, checked)}
                        />
                      </td>
                      <td className="px-5 py-4 table-mobile-primary" data-label="شماره">
                        <Link
                          to={`/metals/${row.id}/edit`}
                          className="font-mono text-sm font-medium text-brand-600 hover:text-brand-700 dark:text-brand-400 dark:hover:text-brand-300"
                        >
                          {row.transaction_number}
                        </Link>
                      </td>
                      <td className="px-5 py-4" data-label="سفارش">
                        {row.order ? (
                          <Link
                            to={`/orders/${row.order_id}`}
                            className="text-sm font-medium text-gray-800 hover:text-brand-500 hover:underline dark:text-white/90"
                          >
                            {row.order.order_number}
                          </Link>
                        ) : (
                          <span className="text-sm text-gray-400">—</span>
                        )}
                      </td>
                      <td className="px-5 py-4" data-label="مشتری">
                        {row.order?.user ? (
                          <div>
                            <Link
                              to={`/customers/${row.order.user.id}`}
                              className="text-sm font-medium text-gray-800 hover:text-brand-500 hover:underline dark:text-white/90"
                            >
                              {row.order.user.name}
                            </Link>
                            {row.order.user.mobile && (
                              <p className="text-xs text-gray-500 dark:text-gray-400">
                                {row.order.user.mobile}
                              </p>
                            )}
                          </div>
                        ) : (
                          <span className="text-sm text-gray-400">—</span>
                        )}
                      </td>
                      <td className="px-5 py-4 text-sm text-gray-800 dark:text-white/90" data-label="محصول">
                        {row.product?.name ?? '—'}
                      </td>
                      <td className="px-5 py-4 tabular-nums text-sm text-gray-800 dark:text-white/90" data-label="گرم">
                        {formatNum(row.grams)}
                      </td>
                      <td className="px-5 py-4" data-label="وضعیت">{getStatusBadge(row.status)}</td>
                      <td className="px-5 py-4 text-sm text-gray-500 dark:text-gray-400" data-label="تاریخ ثبت">
                        {row.created_at
                          ? new Date(row.created_at).toLocaleString('fa-IR', {
                              year: 'numeric',
                              month: '2-digit',
                              day: '2-digit',
                              hour: '2-digit',
                              minute: '2-digit',
                            })
                          : '—'}
                      </td>
                      <td className="px-5 py-4 table-mobile-actions">
                        <div className="flex items-center gap-1">
                          <IfPermission permission="update_metals">
                            <Link
                              to={`/metals/${row.id}/edit`}
                              className="rounded-lg p-1.5 text-brand-500 hover:bg-brand-50 dark:hover:bg-brand-500/10"
                              title="مشاهده / ویرایش"
                            >
                              <svg
                                className="w-5 h-5"
                                fill="none"
                                stroke="currentColor"
                                viewBox="0 0 24 24"
                              >
                                <path
                                  strokeLinecap="round"
                                  strokeLinejoin="round"
                                  strokeWidth={1.5}
                                  d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"
                                />
                              </svg>
                            </Link>
                          </IfPermission>
                          <IfPermission permission="delete_metals">
                            <button
                              type="button"
                              onClick={() => handleDelete(row)}
                              disabled={deletingId === row.id}
                              className="rounded-lg p-1.5 text-error-500 hover:bg-error-50 dark:hover:bg-error-500/10 disabled:opacity-50"
                              title="حذف"
                            >
                            {deletingId === row.id ? (
                              <svg className="w-5 h-5 animate-spin" viewBox="0 0 24 24">
                                <circle
                                  className="opacity-25"
                                  cx="12"
                                  cy="12"
                                  r="10"
                                  stroke="currentColor"
                                  strokeWidth="4"
                                  fill="none"
                                />
                                <path
                                  className="opacity-75"
                                  fill="currentColor"
                                  d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
                                />
                              </svg>
                            ) : (
                              <svg
                                className="w-5 h-5"
                                fill="none"
                                stroke="currentColor"
                                viewBox="0 0 24 24"
                              >
                                <path
                                  strokeLinecap="round"
                                  strokeLinejoin="round"
                                  strokeWidth={1.5}
                                  d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
                                />
                              </svg>
                            )}
                            </button>
                          </IfPermission>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {pagination && (
              <Pagination
                currentPage={pagination.current_page}
                lastPage={pagination.last_page}
                perPage={pagination.per_page}
                total={pagination.total}
                onPageChange={(newPage) => setPage(newPage)}
                onPerPageChange={(newPerPage) => {
                  setPerPage(newPerPage)
                  setPage(1)
                }}
              />
            )}
          </>
        )}
      </div>
    </>
  )
}
