"use client"
import { useState } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { ServiceCard } from "./ServiceCard"
import { ServiceCardSkeleton } from "./ServiceCardSkeleton"
import { Package, Edit, Trash2 } from "lucide-react"
import { useTranslations } from "next-intl"
import { useDeleteCategory, useGetCategorizedServices, useUpdateCategory, useDeleteService } from "@/lib/react-query/hooks/services"
import { AddCategoryModal } from "./AddCategoryModal"
import { useConfirm } from "@/context/ConfirmDialogContext"
import type { Service } from "@/types/services"
import {
  Pagination,
  PaginationContent,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination"

export function ServicesList() {
  const [page, setPage] = useState(1)
  const [limit] = useState(10)
  const t = useTranslations()

  const { data: categoriesData, isLoading, isError } = useGetCategorizedServices({ page, limit })
  const deleteService = useDeleteService()
  const deleteCategory = useDeleteCategory()
  const confirm = useConfirm()

  const [editingCategory, setEditingCategory] = useState<{ id: string, name: string } | null>(null)

  const confirmDeleteCategory = (categoryId: string, categoryName: string) => {
    confirm.show({
      title: `Delete category: ${categoryName}`,
      description: `Are you sure you want to delete the category "${categoryName}"? All services within this category will be uncategorized.`,
      confirmText: "Delete",
      cancelText: "Cancel",
      onConfirm: async () => {
        try {
          await deleteCategory.mutateAsync(categoryId)
        } catch (e) {
          console.error("Delete failed", e)
        }
      }
    })
  }

  const confirmDelete = (service: Service) => {
    confirm.show({
      title: `Delete service: ${service.name}`,
      description: `Are you sure you want to delete the service "${service.name}"? This action cannot be undone.`,
      confirmText: "Delete",
      cancelText: "Cancel",
      onConfirm: async () => {
        try {
          await deleteService.mutateAsync(service._id)
        } catch (e) {
          console.error("Delete failed", e)
        }
      }
    })
  }

  if (isLoading) {
    return (
      <div className="space-y-6">
        {Array.from({ length: 2 }).map((_, i) => (
          <Card key={i}>
            <CardHeader>
              <div className="h-6 w-32 bg-gray-200 animate-pulse rounded" />
            </CardHeader>
            <CardContent className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
              {Array.from({ length: 3 }).map((_, j) => (
                <ServiceCardSkeleton key={j} />
              ))}
            </CardContent>
          </Card>
        ))}
      </div>
    )
  }

  if (isError) {
    return (
      <div className="w-full flex justify-center items-center p-8 bg-white border rounded-xl">
        <div className="text-center text-red-500">
          <h3 className="text-lg font-medium">{t("services.list.error.title")}</h3>
          <p className="mt-2 text-sm">{t("services.list.error.description")}</p>
        </div>
      </div>
    )
  }

  if (!categoriesData || !categoriesData.data || categoriesData.data.length === 0) {
    return (
      <div className="w-full flex justify-center items-center p-8 bg-white border rounded-xl">
        <div className="text-center text-gray-500">
          <Package className="mx-auto mb-3 w-12 h-12 text-gray-400" />
          <h3 className="text-lg font-medium text-gray-900">{t("services.list.empty.title")}</h3>
          <p className="mt-2 text-sm">{t("services.list.empty.description")}</p>
        </div>
      </div>
    )
  }

  const { meta } = categoriesData

  return (
    <div className="space-y-8">
      <div className="space-y-8">
        {categoriesData.data.map(categoryItem => (
          <Card key={categoryItem.categoryId} className="border-none shadow-sm bg-white">
            <CardHeader className="pb-2 flex flex-row items-center justify-between space-y-0">
              <CardTitle className="text-lg font-semibold text-gray-900">{categoryItem.category}</CardTitle>
              {categoryItem.categoryId !== "Uncategorized" && (
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => setEditingCategory({ id: categoryItem.categoryId, name: categoryItem.category })}
                    className="p-1 hover:bg-gray-100 rounded-full transition-colors shadow-none border-none bg-transparent"
                  >
                    <Edit className="w-4 h-4 text-primary-blue" />
                  </button>
                  <button
                    onClick={() => confirmDeleteCategory(categoryItem.categoryId, categoryItem.category)}
                    className="p-1 hover:bg-gray-100 rounded-full transition-colors shadow-none border-none bg-transparent"
                  >
                    <Trash2 className="w-4 h-4 text-red-500" />
                  </button>
                </div>
              )}
            </CardHeader>
            <CardContent className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
              {categoryItem.services.map(service => (
                <ServiceCard key={service._id} service={service} confirmDelete={confirmDelete} />
              ))}
            </CardContent>
          </Card>
        ))}
      </div>

      {meta && meta.totalPages > 1 && (
        <Pagination>
          <PaginationContent>
            <PaginationItem>
              <PaginationPrevious
                href="#"
                onClick={(e) => {
                  e.preventDefault()
                  if (page > 1) setPage(page - 1)
                }}
                className={page === 1 ? "pointer-events-none opacity-50" : "cursor-pointer"}
              />
            </PaginationItem>

            {Array.from({ length: meta.totalPages }).map((_, i) => {
              const pageNum = i + 1
              // Simple pagination logic: show first, last, and current ± 1
              if (
                pageNum === 1 ||
                pageNum === meta.totalPages ||
                (pageNum >= page - 1 && pageNum <= page + 1)
              ) {
                return (
                  <PaginationItem key={pageNum}>
                    <PaginationLink
                      href="#"
                      isActive={page === pageNum}
                      onClick={(e) => {
                        e.preventDefault()
                        setPage(pageNum)
                      }}
                      className="cursor-pointer"
                    >
                      {pageNum}
                    </PaginationLink>
                  </PaginationItem>
                )
              } else if (
                (pageNum === page - 2 && pageNum > 1) ||
                (pageNum === page + 2 && pageNum < meta.totalPages)
              ) {
                return (
                  <PaginationItem key={pageNum}>
                    <PaginationEllipsis />
                  </PaginationItem>
                )
              }
              return null
            })}

            <PaginationItem>
              <PaginationNext
                href="#"
                onClick={(e) => {
                  e.preventDefault()
                  if (page < meta.totalPages) setPage(page + 1)
                }}
                className={page === meta.totalPages ? "pointer-events-none opacity-50" : "cursor-pointer"}
              />
            </PaginationItem>
          </PaginationContent>
        </Pagination>
      )}
      <AddCategoryModal
        open={!!editingCategory}
        onOpenChange={(open) => !open && setEditingCategory(null)}
        editData={editingCategory}
      />
    </div>
  )
}

