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 Badge from '../../components/ui/badge/Badge'
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 { useToast } from '../../context/ToastContext'
import { IfPermission } from '../../components/auth/RequirePermission'

interface Permission {
  id: number
  name: string
  label?: string
}

interface Role {
  id: number
  name: string
  label?: string
  permissions: Permission[]
}

export const RolesListPage = () => {
  const navigate = useNavigate()
  const [searchParams, setSearchParams] = useSearchParams()
  const queryClient = useQueryClient()
  const toast = useToast()
  const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set())
  const [bulkDeleting, setBulkDeleting] = useState(false)
  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')

  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 !== 'id') params.set('sort', sortBy)
    if (sortOrder !== 'desc') params.set('order', sortOrder)
    setSearchParams(params, { replace: true })
  }, [page, perPage, sortBy, sortOrder, setSearchParams])

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

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

  const paginated = rolesResponse && typeof rolesResponse === 'object' && 'data' in rolesResponse ? rolesResponse : null
  const roles: Role[] = paginated?.data ?? (Array.isArray(rolesResponse) ? rolesResponse : [])

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

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

  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedIds(new Set(roles.map((r) => r.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 onPageChange = (newPage: number) => {
    setPage(newPage)
    setSelectedIds(new Set())
  }
  const onPerPageChange = (newPerPage: number) => {
    setPerPage(newPerPage)
    setPage(1)
    setSelectedIds(new Set())
  }

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

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

    setBulkDeleting(true)
    try {
      const results = await Promise.allSettled(
        Array.from(selectedIds).map((id) => apiClient.delete(`/roles/${id}`))
      )
      
      const failed = results.filter((r) => r.status === 'rejected')
      const succeeded = results.filter((r) => r.status === 'fulfilled')
      
      if (succeeded.length > 0) {
        queryClient.invalidateQueries({ queryKey: ['roles'] })
        toast.success(`${succeeded.length} نقش با موفقیت حذف شد`)
      }
      
      if (failed.length > 0) {
        const firstError = (failed[0] as PromiseRejectedResult).reason
        toast.error(firstError?.response?.data?.message || `${failed.length} نقش حذف نشد`)
      }
      
      setSelectedIds(new Set())
    } catch (err: any) {
      toast.error(err.response?.data?.message || 'خطا در حذف نقش‌ها')
    } finally {
      setBulkDeleting(false)
    }
  }

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

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

      {/* Header */}
      <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">
              ({paginated?.total != null ? new Intl.NumberFormat('fa-IR').format(paginated.total) : isLoading ? '…' : '۰'}
              {' '}مورد)
            </span>
          </h2>
          <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">مدیریت نقش‌ها و مجوزهای سیستم</p>
        </div>
        <IfPermission permission="create_roles">
          <button
            onClick={() => navigate('/roles/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 Alert */}
      {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>
      )}

      {/* Main Card */}
      <div className="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
        {/* Bulk Actions */}
        {someSelected && (
          <IfPermission permission="delete_roles">
            <div className="flex items-center justify-between border-b border-gray-200 bg-brand-50 px-6 py-3 dark:border-gray-800 dark:bg-brand-500/10">
              <span className="text-sm text-gray-700 dark:text-gray-300">
                {selectedIds.size} مورد انتخاب شده
              </span>
              <button
                type="button"
                onClick={handleBulkDelete}
                disabled={bulkDeleting}
                className="rounded-lg bg-error-500 px-3 py-1.5 text-xs font-medium text-white hover:bg-error-600 disabled:opacity-50"
              >
                {bulkDeleting ? 'در حال حذف...' : `حذف ${selectedIds.size} مورد`}
              </button>
            </div>
          </IfPermission>
        )}

        {/* Table */}
        {isLoading ? (
          <TableSkeleton rows={8} cols={5} showCheckbox />
        ) : roles.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="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
            </svg>
            <p className="mt-4 text-sm text-gray-500 dark:text-gray-400">نقشی ثبت نشده است.</p>
          </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="label" 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>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200 dark:divide-gray-800">
                {roles.map((r) => (
                  <tr key={r.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(r.id)}
                        onChange={(checked) => handleSelectOne(r.id, checked)}
                      />
                    </td>
                    <td className="px-5 py-4 table-mobile-primary" data-label="نام نقش">
                      <Link to={`/roles/${r.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">
                        {r.name}
                      </Link>
                    </td>
                    <td className="px-5 py-4 text-sm text-gray-500 dark:text-gray-400" data-label="برچسب">{r.label || '-'}</td>
                    <td className="px-5 py-4" data-label="مجوزها">
                      <div className="flex flex-wrap gap-1">
                        {r.permissions?.slice(0, 3).map((p: Permission) => (
                          <Badge key={p.id} color="info" variant="light" size="sm">
                            {p.label || p.name}
                          </Badge>
                        ))}
                        {r.permissions?.length > 3 && (
                          <Badge color="light" variant="light" size="sm">
                            +{r.permissions.length - 3} دیگر
                          </Badge>
                        )}
                        {(!r.permissions || r.permissions.length === 0) && (
                          <span className="text-sm text-gray-400">-</span>
                        )}
                      </div>
                    </td>
                    <td className="px-5 py-4 table-mobile-actions">
                      <div className="flex items-center gap-2">
                        <IfPermission permission="update_roles">
                          <button
                            onClick={() => navigate(`/roles/${r.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_roles">
                          <button
                            onClick={() => handleDelete(r.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>
          {paginated && (
            <Pagination
              currentPage={paginated.current_page}
              lastPage={paginated.last_page}
              perPage={paginated.per_page ?? perPage}
              total={paginated.total}
              onPageChange={onPageChange}
              onPerPageChange={onPerPageChange}
            />
          )}
          </>
        )}
      </div>
    </>
  )
}
