import { useState, useEffect } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { apiClient } from '../../api/client'
import PageMeta from '../../components/common/PageMeta'
import PageBreadcrumb from '../../components/common/PageBreadCrumb'
import { TableSkeleton } from '../../components/ui/skeleton'
import TableCheckbox from '../../components/form/input/TableCheckbox'
import { Pagination } from '../../components/Pagination'
import { SortableTh, type SortOrder } from '../../components/ui/table'
import { formatPurity } from '../../utils/numberUtils'
import { IfPermission } from '../../components/auth/RequirePermission'

export interface ProductItem {
  id: number
  name: string
  code: string | null
  metal_type: string
  purity: number
  current_stock_grams: number
  notes: string | null
}

const metalTypeLabel: Record<string, string> = {
  GOLD: 'طلا',
  SILVER: 'نقره',
  PLATINUM: 'پلاتین',
}

export const ProductsPage = () => {
  const queryClient = useQueryClient()
  const [searchParams, setSearchParams] = useSearchParams()
  const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set())
  const [bulkDeleting, setBulkDeleting] = useState(false)

  const [search, setSearch] = useState(searchParams.get('search') || '')
  const [metalTypeFilter, setMetalTypeFilter] = useState(searchParams.get('metal_type') || '')
  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) || 'asc')

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

  useEffect(() => {
    const params = new URLSearchParams()
    if (search) params.set('search', search)
    if (metalTypeFilter) params.set('metal_type', metalTypeFilter)
    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 !== 'asc') params.set('order', sortOrder)
    setSearchParams(params, { replace: true })
  }, [search, metalTypeFilter, page, perPage, sortBy, sortOrder, setSearchParams])

  const { data, isLoading, error } = useQuery({
    queryKey: ['products'],
    queryFn: async () => {
      const res = await apiClient.get('/products')
      return (res?.data ?? res) as ProductItem[]
    },
  })

  const products: ProductItem[] = Array.isArray(data) ? data : []

  const filteredProducts = products.filter((p) => {
    if (search) {
      const q = search.toLowerCase()
      if (
        !p.name?.toLowerCase().includes(q) &&
        !p.code?.toLowerCase().includes(q) &&
        !String(p.purity ?? '').includes(search) &&
        !(metalTypeLabel[p.metal_type] ?? p.metal_type)?.toLowerCase().includes(q)
      ) {
        return false
      }
    }
    if (metalTypeFilter && p.metal_type !== metalTypeFilter) return false
    return true
  })

  const total = filteredProducts.length
  const lastPage = Math.max(1, Math.ceil(total / perPage))
  const effectivePage = total === 0 ? 1 : Math.min(page, lastPage)
  const from = (effectivePage - 1) * perPage

  const sortedProducts = [...filteredProducts].sort((a, b) => {
    const key = sortBy || 'id'
    const aVal = key in a ? (a as unknown as Record<string, unknown>)[key] : ''
    const bVal = key in b ? (b as unknown as Record<string, unknown>)[key] : ''
    const aNum = typeof aVal === 'number' ? aVal : Number.NaN
    const bNum = typeof bVal === 'number' ? bVal : Number.NaN
    if (!Number.isNaN(aNum) && !Number.isNaN(bNum)) {
      return sortOrder === 'asc' ? aNum - bNum : bNum - aNum
    }
    const aStr = String(aVal ?? '')
    const bStr = String(bVal ?? '')
    const cmp = aStr.localeCompare(bStr, 'fa')
    return sortOrder === 'asc' ? cmp : -cmp
  })
  const paginatedProducts = sortedProducts.slice(from, from + perPage)

  useEffect(() => {
    if (total > 0 && page > lastPage) setPage(lastPage)
  }, [total, lastPage, page])

  const deleteMutation = useMutation({
    mutationFn: async (id: number) => apiClient.delete(`/products/${id}`),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['products'] }),
  })

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

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

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

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

  const handleBulkDelete = async () => {
    if (selectedIds.size === 0) return
    if (!confirm(`آیا از حذف ${selectedIds.size} محصول انتخاب شده اطمینان دارید؟`)) return
    setBulkDeleting(true)
    try {
      const results = await Promise.allSettled(
        Array.from(selectedIds).map((id) => apiClient.delete(`/products/${id}`))
      )
      const failed = results.filter((r) => r.status === 'rejected')
      queryClient.invalidateQueries({ queryKey: ['products'] })
      setSelectedIds(new Set())
      if (failed.length > 0) {
        alert(`${failed.length} مورد حذف نشد.`)
      }
    } finally {
      setBulkDeleting(false)
    }
  }

  const handleDeleteOne = (id: number) => {
    if (confirm('آیا از حذف این محصول اطمینان دارید؟')) {
      deleteMutation.mutate(id)
    }
  }

  return (
    <div className="space-y-6">
      <PageMeta title="محصولات و موجودی انبار" description="مدیریت محصولات و موجودی انبار" />
      <PageBreadcrumb pageTitle="محصولات" />

      {/* Header */}
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 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">
              ({isLoading ? '…' : new Intl.NumberFormat('fa-IR').format(total)}
              {' '}مورد)
            </span>
          </h1>
          <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
            هر محصول با نوع و عیار تعریف می‌شود. با تایید سفارش خرید به موجودی اضافه و با تایید سفارش فروش از موجودی کم می‌شود.
          </p>
        </div>
        <IfPermission permission="create_products">
          <Link
            to="/products/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 4v16m8-8H4" />
            </svg>
            محصول جدید
          </Link>
        </IfPermission>
      </div>

      {/* Search and Filters */}
      <div className="flex flex-wrap items-center gap-3">
        <div className="relative flex-1 min-w-[200px] max-w-md">
          <svg
            className="absolute right-3 top-1/2 h-4 w-4 -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); setPage(1) }}
            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-hidden focus:ring-3 focus:ring-brand-500/10 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
          />
        </div>
        <select
          value={metalTypeFilter}
          onChange={(e) => { setMetalTypeFilter(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-hidden focus:ring-3 focus:ring-brand-500/10 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
        >
          <option value="">همه نوع فلز</option>
          <option value="GOLD">طلا</option>
          <option value="SILVER">نقره</option>
          <option value="PLATINUM">پلاتین</option>
        </select>
        {(search || metalTypeFilter) && (
          <button
            type="button"
            onClick={() => { setSearch(''); setMetalTypeFilter(''); 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 && (
        <IfPermission permission="delete_products">
          <div className="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">
            <span className="text-sm font-medium text-purple-700 dark:text-purple-300">
              {selectedIds.size.toLocaleString('fa-IR')} محصول انتخاب شده
            </span>
            <div className="flex items-center gap-2">
              <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 ? 'در حال حذف...' : 'حذف'}
              </button>
              <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>
        </IfPermission>
      )}

      {/* Main Card */}
      <div className="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
        {isLoading ? (
          <TableSkeleton rows={8} cols={7} showCheckbox />
        ) : error ? (
          <div className="px-6 py-12 text-center text-sm text-red-600 dark:text-red-400">
            خطا در بارگذاری محصولات
          </div>
        ) : paginatedProducts.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 || metalTypeFilter ? 'محصولی با این فیلترها یافت نشد.' : 'هنوز محصولی تعریف نشده.'}
            </p>
            {!search && !metalTypeFilter && (
              <IfPermission permission="create_products">
                <Link to="/products/new" className="mt-3 inline-block text-sm text-brand-500 hover:text-brand-600">
                  افزودن اولین محصول
                </Link>
              </IfPermission>
            )}
          </div>
        ) : (
          <>
            <div className="table-mobile-cards">
              <table className="w-full">
                <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="name" currentSortBy={sortBy} currentSortOrder={sortOrder} onSort={handleSort} className="px-5 py-4 text-right">
                      نام
                    </SortableTh>
                    <SortableTh sortKey="metal_type" currentSortBy={sortBy} currentSortOrder={sortOrder} onSort={handleSort} className="px-5 py-4 text-right">
                      نوع فلز
                    </SortableTh>
                    <SortableTh sortKey="purity" currentSortBy={sortBy} currentSortOrder={sortOrder} onSort={handleSort} className="px-5 py-4 text-right">
                      عیار
                    </SortableTh>
                    <SortableTh sortKey="current_stock_grams" 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">
                  {paginatedProducts.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={`/products/${row.id}/edit`} className="font-medium text-gray-800 hover:text-brand-500 hover:underline dark:text-white/90 dark:hover:text-brand-400">
                          {row.name}
                        </Link>
                        {row.code && <div className="text-xs text-gray-500 dark:text-gray-400">{row.code}</div>}
                      </td>
                      <td className="px-5 py-4 text-sm text-gray-600 dark:text-gray-300" data-label="نوع فلز">
                        {metalTypeLabel[row.metal_type] ?? row.metal_type}
                      </td>
                      <td className="px-5 py-4 text-sm text-gray-600 dark:text-gray-300" data-label="عیار">{formatPurity(row.purity)}</td>
                      <td className="px-5 py-4 text-sm tabular-nums text-gray-800 dark:text-white/90" data-label="موجودی (گرم)">
                        {formatNum(row.current_stock_grams)}
                      </td>
                      <td className="px-5 py-4 table-mobile-actions">
                        <div className="flex flex-wrap items-center gap-2">
                          <IfPermission permission="update_products">
                            <Link
                              to={`/products/${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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                              </svg>
                            </Link>
                          </IfPermission>
                          <IfPermission permission="delete_products">
                            <button
                              type="button"
                              onClick={() => handleDeleteOne(row.id)}
                              disabled={deleteMutation.isPending}
                              className="rounded-lg p-1.5 text-error-500 hover:bg-error-50 disabled:opacity-50 dark:hover:bg-error-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="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
              currentPage={effectivePage}
              lastPage={lastPage}
              perPage={perPage}
              total={total}
              onPageChange={(newPage) => {
                setPage(newPage)
                setSelectedIds(new Set())
              }}
              onPerPageChange={(newPerPage) => {
                setPerPage(newPerPage)
                setPage(1)
                setSelectedIds(new Set())
              }}
            />
          </>
        )}
      </div>
    </div>
  )
}
