import { useState, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import { apiClient } from '../../api/client'
import PageMeta from '../../components/common/PageMeta'
import PageBreadcrumb from '../../components/common/PageBreadCrumb'
import { TableSkeleton } from '../../components/ui/skeleton'
import Badge from '../../components/ui/badge/Badge'
import { SortableTh, type SortOrder } from '../../components/ui/table'
import { useToast } from '../../context/ToastContext'
import { IfPermission } from '../../components/auth/RequirePermission'

interface Plan {
  id: number
  name: string
  slug: string
  description?: string
  features?: string[]
  max_users?: number | null
  max_customers?: number | null
  max_orders_per_month?: number | null
  price_monthly?: string | number | null
  price_yearly?: string | number | null
  is_active: boolean
  sort_order: number
  vendors_count?: number
  created_at?: string
}

const formatNumber = (n: number) => new Intl.NumberFormat('fa-IR').format(n)

export const PlansListPage = () => {
  const navigate = useNavigate()
  const [searchParams, setSearchParams] = useSearchParams()
  const queryClient = useQueryClient()
  const toast = useToast()
  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') || 'sort_order')
  const [sortOrder, setSortOrder] = useState<SortOrder>((searchParams.get('order') as SortOrder) || 'asc')
  const [search, setSearch] = useState(searchParams.get('search') || '')

  useEffect(() => {
    const params = new URLSearchParams()
    if (page > 1) params.set('page', String(page))
    if (perPage !== 20) params.set('per_page', String(perPage))
    if (sortBy && sortBy !== 'sort_order') params.set('sort', sortBy)
    if (sortOrder !== 'asc') params.set('order', sortOrder)
    if (search) params.set('search', search)
    setSearchParams(params, { replace: true })
  }, [page, perPage, sortBy, sortOrder, search, setSearchParams])

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

  const { data: response, isLoading, error } = useQuery({
    queryKey: ['plans', page, perPage, sortBy, sortOrder, search],
    queryFn: async () => {
      const res = await apiClient.get('/plans', {
        params: { page, per_page: perPage, sort: sortBy || 'sort_order', order: sortOrder, search: search || undefined },
      })
      return res.data
    },
  })

  const paginated = response?.data
  const plans: Plan[] = paginated?.data ?? []
  const totalCount = paginated?.total ?? 0

  const deleteMutation = useMutation({
    mutationFn: async (id: number) => apiClient.delete(`/plans/${id}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['plans'] })
      queryClient.invalidateQueries({ queryKey: ['plans-list'] })
      toast.success('پلن با موفقیت حذف شد')
    },
    onError: (err: any) => {
      toast.error(err.response?.data?.message || 'خطا در حذف پلن')
    },
  })

  const handleDelete = (id: number) => {
    if (confirm('آیا از حذف این پلن اطمینان دارید؟ وندورهای دارای این پلن باید ابتدا به پلن دیگری منتقل شوند.')) {
      deleteMutation.mutate(id)
    }
  }

  const onPageChange = (newPage: number) => setPage(newPage)
  const onPerPageChange = (newPerPage: number) => {
    setPerPage(newPerPage)
    setPage(1)
  }

  return (
    <>
      <PageMeta title="پلن‌ها | آیرون" description="مدیریت پلن‌ها و اشتراک وندورها" />
      <PageBreadcrumb pageTitle="پلن‌ها" />

      <div className="mb-6 flex flex-wrap items-center justify-between gap-3">
        <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">
              ({formatNumber(totalCount)} مورد)
            </span>
          </h2>
          <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">اشتراک و محدودیت وندورها</p>
        </div>
        <IfPermission permission="create_plans">
          <button
            onClick={() => navigate('/plans/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>
            افزودن پلن
          </button>
        </IfPermission>
      </div>

      {error && (
        <div className="mb-4 rounded-lg border border-error-200 bg-error-50 p-4 dark:border-error-500/20 dark:bg-error-500/10">
          <p className="text-sm text-error-600 dark:text-error-400">خطا در بارگذاری پلن‌ها: {String(error)}</p>
        </div>
      )}

      <div className="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
        <div className="p-4 border-b border-gray-200 dark:border-gray-800">
          <input
            type="search"
            placeholder="جستجو در نام یا اسلاگ..."
            value={search}
            onChange={(e) => {
              setSearch(e.target.value)
              setPage(1)
            }}
            className="w-full max-w-xs rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800 dark:text-white"
          />
        </div>

        {isLoading ? (
          <TableSkeleton rows={8} cols={6} />
        ) : plans.length === 0 ? (
          <div className="py-12 text-center">
            <p className="text-sm text-gray-500 dark:text-gray-400">پلنی ثبت نشده است.</p>
            <IfPermission permission="create_plans">
              <button
                onClick={() => navigate('/plans/new')}
                className="mt-3 inline-flex items-center gap-2 rounded-xl bg-brand-500 px-4 py-2 text-sm font-medium text-white hover:bg-brand-600"
              >
                افزودن اولین پلن
              </button>
            </IfPermission>
          </div>
        ) : (
          <>
            <div className="table-mobile-cards">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-gray-200 dark:border-gray-800">
                    <SortableTh sortKey="sort_order" currentSortBy={sortBy} currentSortOrder={sortOrder} onSort={handleSort} className="px-5 py-4 text-right">
                      ترتیب
                    </SortableTh>
                    <SortableTh sortKey="name" 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>
                    <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>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200 dark:divide-gray-800">
                  {plans.map((p) => (
                    <tr key={p.id} className="hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                      <td className="px-5 py-4 text-sm text-gray-500 dark:text-gray-400" data-label="ترتیب">{p.sort_order}</td>
                      <td className="px-5 py-4 table-mobile-primary" data-label="نام">
                        <Link
                          to={`/plans/${p.id}/edit`}
                          className="text-sm font-medium text-gray-800 hover:text-brand-500 hover:underline dark:text-white/90 dark:hover:text-brand-400"
                        >
                          {p.name}
                        </Link>
                        <span className="mr-2 font-mono text-xs text-gray-400">({p.slug})</span>
                      </td>
                      <td className="px-5 py-4 text-sm text-gray-600 dark:text-gray-400" data-label="محدودیت‌ها">
                        کاربر: {p.max_users == null ? '—' : formatNumber(p.max_users)} · مشتری: {p.max_customers == null ? '—' : formatNumber(p.max_customers)}
                      </td>
                      <td className="px-5 py-4 text-sm text-gray-600 dark:text-gray-400" data-label="قیمت">
                        {p.price_monthly != null ? `${formatNumber(Number(p.price_monthly))} / ماه` : '—'}
                        {p.price_yearly != null && ` · ${formatNumber(Number(p.price_yearly))} / سال`}
                      </td>
                      <td className="px-5 py-4 text-sm text-gray-600 dark:text-gray-400" data-label="وندورها">
                        {typeof p.vendors_count === 'number' ? formatNumber(p.vendors_count) : '—'}
                      </td>
                      <td className="px-5 py-4" data-label="وضعیت">
                        {p.is_active ? (
                          <Badge color="success" variant="light" size="sm">فعال</Badge>
                        ) : (
                          <Badge color="light" variant="light" size="sm">غیرفعال</Badge>
                        )}
                      </td>
                      <td className="px-5 py-4 table-mobile-actions">
                        <div className="flex items-center gap-2">
                          <IfPermission permission="update_plans">
                            <button
                              onClick={() => navigate(`/plans/${p.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>
                            </button>
                          </IfPermission>
                          <IfPermission permission="delete_plans">
                            <button
                              onClick={() => handleDelete(p.id)}
                              disabled={deleteMutation.isPending || (p.vendors_count ?? 0) > 0}
                              className="rounded-lg p-1.5 text-error-500 hover:bg-error-50 disabled:opacity-50 dark:hover:bg-error-500/10"
                              title={(p.vendors_count ?? 0) > 0 ? 'پلن دارای وندور است' : 'حذف'}
                            >
                              <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>
            {paginated?.last_page > 1 && (
              <div className="border-t border-gray-200 dark:border-gray-800 p-4">
                <div className="flex items-center justify-between">
                  <span className="text-sm text-gray-500 dark:text-gray-400">
                    صفحه {paginated.current_page} از {paginated.last_page}
                  </span>
                  <div className="flex gap-2">
                    <button
                      type="button"
                      disabled={paginated.current_page <= 1}
                      onClick={() => onPageChange(paginated.current_page - 1)}
                      className="rounded-lg border border-gray-300 px-3 py-1.5 text-sm disabled:opacity-50 dark:border-gray-600"
                    >
                      قبلی
                    </button>
                    <button
                      type="button"
                      disabled={paginated.current_page >= paginated.last_page}
                      onClick={() => onPageChange(paginated.current_page + 1)}
                      className="rounded-lg border border-gray-300 px-3 py-1.5 text-sm disabled:opacity-50 dark:border-gray-600"
                    >
                      بعدی
                    </button>
                  </div>
                </div>
              </div>
            )}
          </>
        )}
      </div>
    </>
  )
}
