"use client"

import * as React from "react"
import { Plus, Pencil, Trash2, CheckCircle2, Circle, Clock, XCircle, AlertCircle, FilterX, Search, Bell } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { ReactSelect } from "@/components/ui/react-select"
import { Input } from "@/components/ui/input"
import { useSearchParams } from "next/navigation"
import { useUrlPagination } from "@/hooks/use-url-pagination"
import {
  Pagination,
  PaginationContent,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination"
import { useGetTasksQuery, useDeleteTaskMutation, useGetTaskStatusesQuery } from "@/api/rtk"
import { useGetProfileQuery } from "@/api/rtk/auth-api"
import {
  TASK_MODULE_TYPE_BADGE_CLASS,
  TASK_MODULE_TYPE_LABELS,
  TASK_MODULE_TYPES,
  TASK_STATUS_FALLBACK_LABELS,
  taskStatusCatalogLabel,
  type Task,
  type TaskModuleType,
  type TaskStatus,
} from "@/api/rtk/tasks-api"
import { TaskFormModal } from "./task-form-modal"
import { TaskViewModal } from "./task-view-modal"
import { format } from "date-fns"
import { toast } from "sonner"
import { cn } from "@/lib/utils"
import { Can } from "@/components/providers/ability-provider"
import { useAuthToken } from "@/hooks/use-auth-token"
import { hasPermission, isAdminUser } from "@/lib/permissions"
import { useSession } from "next-auth/react"
import { APILoader } from "@/components/shadix-ui/components/loader"

const STATUS_VISUAL: Record<
  TaskStatus,
  { icon: React.ElementType; className: string }
> = {
  RECEIVED: { icon: Clock, className: "bg-slate-100 text-slate-700" },
  IN_PROGRESS: { icon: Clock, className: "bg-blue-100 text-blue-700" },
  TECHNICAL_REVIEW: { icon: AlertCircle, className: "bg-orange-100 text-orange-700" },
  APPROVED: { icon: CheckCircle2, className: "bg-green-100 text-green-700" },
  HANDED_TO_AE: { icon: CheckCircle2, className: "bg-emerald-100 text-emerald-700" },
  TODO: { icon: Circle, className: "bg-slate-100 text-slate-700" },
  DONE: { icon: CheckCircle2, className: "bg-green-100 text-green-700" },
  CANCELLED: { icon: XCircle, className: "bg-red-100 text-red-700" },
}

const PRIORITY_CONFIG = {
  LOW: { label: "Low", className: "bg-slate-100 text-slate-600" },
  MEDIUM: { label: "Medium", className: "bg-yellow-100 text-yellow-700" },
  HIGH: { label: "High", className: "bg-orange-100 text-orange-700" },
  URGENT: { label: "Urgent", className: "bg-red-100 text-red-700" },
}

export default function TasksPage() {
  const { token } = useAuthToken()
  const { data: session } = useSession()
  const searchParams = useSearchParams()
  const { page, setPage, limit, setLimit } = useUrlPagination(10)

  const [search, setSearch] = React.useState(searchParams.get("q") || "")
  const [statusFilter, setStatusFilter] = React.useState(searchParams.get("status") || "all")
  const [priorityFilter, setPriorityFilter] = React.useState(searchParams.get("priority") || "all")
  const [moduleTypeFilter, setModuleTypeFilter] = React.useState(searchParams.get("module") || "all")

  const [modalOpen, setModalOpen] = React.useState(false)
  const [viewOpen, setViewOpen] = React.useState(false)
  const [editingTask, setEditingTask] = React.useState<Task | null>(null)
  const [viewTask, setViewTask] = React.useState<Task | null>(null)
  const { data: profile } = useGetProfileQuery(undefined, { skip: !token })
  const permissionSource = (session as { backendUser?: unknown } | null)?.backendUser ?? profile
  const canListAllTasks = React.useMemo(
    () =>
      isAdminUser(permissionSource) ||
      hasPermission(permissionSource, "READ", "TASK"),
    [permissionSource],
  )

  const filterTriggerClass =
    "h-10 px-3.5 rounded-xl w-full text-[13px] font-bold font-['Lexend_Deca'] border-border/80 bg-white shadow-sm hover:border-accent transition-all ring-0 focus:ring-0"
  const filterContentClass = "rounded-2xl border-border/40 shadow-premium"

  const statusFilterOptions = React.useMemo(
    () => [
      { value: "all", label: "All Status" },
      { value: "RECEIVED", label: "1 Received" },
      { value: "IN_PROGRESS", label: "2 In Progress" },
      { value: "TECHNICAL_REVIEW", label: "3 Head of Technical Review" },
      { value: "APPROVED", label: "4 Approved" },
      { value: "HANDED_TO_AE", label: "EXIT → AE" },
      { value: "TODO", label: "To Do" },
      { value: "DONE", label: "Done" },
      { value: "CANCELLED", label: "Cancelled" },
    ],
    [],
  )

  const priorityFilterOptions = React.useMemo(
    () => [
      { value: "all", label: "All Priorities" },
      { value: "LOW", label: "Low" },
      { value: "MEDIUM", label: "Medium" },
      { value: "HIGH", label: "High" },
      { value: "URGENT", label: "Urgent" },
    ],
    [],
  )

  const moduleTypeFilterOptions = React.useMemo(
    () => [
      { value: "all", label: "All modules" },
      ...TASK_MODULE_TYPES.map((m) => ({
        value: m,
        label: TASK_MODULE_TYPE_LABELS[m],
      })),
    ],
    [],
  )

  const limitOptions = React.useMemo(
    () =>
      ["10", "25", "50", "100"].map((v) => ({
        value: v,
        label: v,
      })),
    [],
  )

  const currentUserId = profile?.id ?? (session as { backendUser?: { id?: string } } | null)?.backendUser?.id

  const { data: taskStatuses = [] } = useGetTaskStatusesQuery()
  const { data: response, isLoading } = useGetTasksQuery({
    assignedToId: canListAllTasks ? undefined : currentUserId,
    status: statusFilter !== "all" ? statusFilter : undefined,
    priority: priorityFilter !== "all" ? priorityFilter : undefined,
    moduleType:
      moduleTypeFilter !== "all" && TASK_MODULE_TYPES.includes(moduleTypeFilter as TaskModuleType)
        ? (moduleTypeFilter as TaskModuleType)
        : undefined,
    search: search || undefined,
    page,
    limit,
  })
  const tasks = response?.data ?? []
  const [deleteTask] = useDeleteTaskMutation()

  const clearFilters = async () => {
    setSearch("")
    setStatusFilter("all")
    setPriorityFilter("all")
    setModuleTypeFilter("all")
    setPage(1)
  }

  const handleDelete = async (id: string) => {
    if (!confirm("Delete this task?")) return
    try {
      await deleteTask(id).unwrap()
      toast.success("Task deleted")
    } catch {
      toast.error("Failed to delete task")
    }
  }

  const handleEdit = (task: Task) => {
    setEditingTask(task)
    setModalOpen(true)
  }

  const handleView = (task: Task) => {
    setViewTask(task)
    setViewOpen(true)
  }

  const handleClose = () => {
    setModalOpen(false)
    setEditingTask(null)
  }

  const handleCloseView = () => {
    setViewOpen(false)
    setViewTask(null)
  }
  return (
    <div className="flex h-full min-h-0 flex-1 flex-col gap-4.5 overflow-hidden p-1 pb-20 animate-in fade-in duration-500 scrollbar-themed sm:p-2 md:p-4 md:pb-6">
      {/* Header - Glassmorphism */}
      <div className="flex flex-col gap-4 rounded-2xl border border-white/40 bg-white/50 dark:bg-white/10 backdrop-blur-[15px] shadow-[0px_2px_20px_0px_rgba(0,0,0,0.06)] p-4 md:p-6">
        <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
          <div className="flex flex-col shrink-0">
            <h1 className="text-[25px] md:text-[28px] font-extrabold text-text font-['Lexend'] tracking-tight leading-none">
              Tasks
            </h1>
            <div className="flex items-center gap-2 mt-2">
              <span className="text-[12px] font-bold text-text/80 bg-accent/5 px-2 py-0.5 rounded-md border border-accent/10">
                {response?.total ?? 0}{" "}
                {canListAllTasks ? "Team Tasks" : "My Tasks"}
              </span>
              <span className="text-[12px] font-bold text-accent/90 bg-accent/5 px-2 py-0.5 rounded-md border border-accent/10">
                Page {page} of {response?.totalPages ?? 1}
              </span>
            </div>
          </div>

          <div className="flex items-center gap-3 w-full md:w-auto">
            <Can action="create" subject="task">
              <Button
                  variant="tasksHeaderCta"
                  onClick={() => setModalOpen(true)}
              >
                  <Plus size={18} className="stroke-[2px]" /> New Task
              </Button>
            </Can>
          </div>
        </div>

        <div className="grid grid-cols-2 lg:flex lg:flex-row items-stretch lg:items-center gap-3 w-full pt-1 border-t border-border/10">
          <div className="relative col-span-2 lg:flex-1 group">
            <Search size={14} className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-accent transition-colors duration-300 pointer-events-none" />
            <Input
              type="search"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Search tasks..."
              className="pl-10 pr-4 h-10 text-[13px] font-bold bg-white border-border/80 rounded-xl w-full font-['Lexend_Deca'] shadow-sm focus:ring-accent/20 focus:border-accent hover:border-accent/40 transition-all placeholder:text-gray-400"
            />
          </div>

          <div className="col-span-1">
            <ReactSelect
              value={statusFilter ?? "all"}
              onValueChange={(v) => setStatusFilter(v === "all" ? null : v)}
              options={statusFilterOptions}
              placeholder="All Status"
              triggerClassName={filterTriggerClass}
              contentClassName={filterContentClass}
            />
          </div>

          <div className="col-span-1">
            <ReactSelect
              value={priorityFilter ?? "all"}
              onValueChange={(v) => setPriorityFilter(v === "all" ? null : v)}
              options={priorityFilterOptions}
              placeholder="Priority"
              triggerClassName={filterTriggerClass}
              contentClassName={filterContentClass}
            />
          </div>

          <div className="col-span-2 sm:col-span-1">
            <ReactSelect
              value={moduleTypeFilter ?? "all"}
              onValueChange={(v) => setModuleTypeFilter(v === "all" ? null : v)}
              options={moduleTypeFilterOptions}
              placeholder="All modules"
              triggerClassName={filterTriggerClass}
              contentClassName={filterContentClass}
            />
          </div>

          {(statusFilter !== "all" || priorityFilter !== "all" || moduleTypeFilter !== "all" || search) && (
            <div className="col-span-2 lg:col-span-auto">
              <Button variant="outlineFilterReset" onClick={clearFilters}>
                <FilterX className="size-4" />
                Clear
              </Button>
            </div>
          )}
        </div>
      </div>

      {/* Table Container - Compact & Glassmorphism */}
      <div className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-2xl border border-white/40 bg-white/50 shadow-sm backdrop-blur-md">
        {isLoading || tasks.length > 0 ? (
          <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
            <div className="min-h-0 flex-1 overflow-auto scrollbar-themed">
              <Table variant="transparent" className="">
                <TableHeader>
                  <TableRow className="bg-slate-50/50 hover:bg-slate-50/50">
                    <TableHead className="w-12 text-center font-extrabold text-text font-['Lexend'] py-4">#</TableHead>
                    <TableHead className="font-extrabold text-text font-['Lexend'] py-4">Title</TableHead>
                    <TableHead className="font-extrabold text-text font-['Lexend'] py-4">Status</TableHead>
                    <TableHead className="hidden sm:table-cell font-extrabold text-text font-['Lexend'] py-4">Priority</TableHead>
                    <TableHead className="hidden sm:table-cell font-extrabold text-text font-['Lexend'] py-4">Module</TableHead>
                    <TableHead className="hidden md:table-cell font-extrabold text-text font-['Lexend'] py-4">Assigned To</TableHead>
                    <TableHead className="hidden lg:table-cell font-extrabold text-text font-['Lexend'] py-4">Deal</TableHead>
                    <TableHead className="hidden xl:table-cell font-extrabold text-text font-['Lexend'] py-4">Due Date</TableHead>
                    <TableHead className="w-20" />
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {isLoading ? (
                    <TableRow>
                      <TableCell colSpan={9} className="py-20">
                        <APILoader />
                      </TableCell>
                    </TableRow>
                  ) : (
                    tasks.map((task, index) => {
                      const statusVis = STATUS_VISUAL[task.status]
                      const statusText = taskStatusCatalogLabel(
                        task.status,
                        taskStatuses,
                        TASK_STATUS_FALLBACK_LABELS,
                      )
                      const priorityCfg = PRIORITY_CONFIG[task.priority]
                      const StatusIcon = statusVis.icon
                      return (
                  <TableRow key={task.id} className="group hover:bg-slate-50/50 cursor-pointer" onClick={() => handleView(task)}>
                    <TableCell className="w-12 text-center text-[12px] text-gray-500 font-semibold py-3.5">
                      {index + 1}
                    </TableCell>
                    <TableCell className="py-3.5">
                      <div className="flex flex-col gap-0.5">
                        <span className="font-bold text-[13px] text-text font-['Lexend'] group-hover:text-accent transition-colors">{task.title}</span>
                        {task.description && (
                          <span className="text-[11px] text-muted-foreground line-clamp-1 font-medium">
                            {task.description}
                          </span>
                        )}
                      </div>
                    </TableCell>
                    <TableCell className="py-3.5">
                      <Badge
                        variant="secondary"
                        className={cn("gap-1 text-[10px] font-extrabold uppercase px-2 py-0.5 rounded-full", statusVis.className)}
                      >
                        <StatusIcon className="size-3" />
                        {statusText}
                      </Badge>
                    </TableCell>
                    <TableCell className="hidden sm:table-cell py-3.5">
                      <Badge
                        variant="secondary"
                        className={cn("text-[10px] font-extrabold uppercase px-2 py-0.5 rounded-full", priorityCfg.className)}
                      >
                        {priorityCfg.label}
                      </Badge>
                    </TableCell>
                    <TableCell className="hidden sm:table-cell py-3.5">
                      {task.moduleType ? (
                        <Badge
                          variant="outline"
                          className={cn(
                            "text-[10px] font-extrabold px-2 py-0.5 rounded-full border",
                            TASK_MODULE_TYPE_BADGE_CLASS[task.moduleType],
                          )}
                        >
                          {TASK_MODULE_TYPE_LABELS[task.moduleType]}
                        </Badge>
                      ) : (
                        <span className="text-[12px] text-muted-foreground font-medium">—</span>
                      )}
                    </TableCell>
                    <TableCell className="hidden md:table-cell py-3.5">
                      <span className="text-[12px] font-semibold text-text/80">{task.assignedTo?.name ?? "—"}</span>
                    </TableCell>
                    <TableCell className="hidden lg:table-cell py-3.5">
                      <span className="text-[12px] font-bold text-accent italic">{task.deal?.customerName ?? task.deal?.leadId ?? "—"}</span>
                    </TableCell>
                    <TableCell className="hidden xl:table-cell py-3.5">
                      <div className="flex flex-col gap-0.5">
                        <span className="text-[12px] text-gray-500 font-bold">
                          {task.dueDate
                            ? format(new Date(task.dueDate), "MMM d, yyyy h:mm a")
                            : "-"}
                        </span>
                        {task.reminderAt && (
                          <span className="text-[10px] text-gray-400 font-semibold flex items-center gap-1 mt-0.5">
                            <Bell size={10} className="shrink-0" />
                            {format(new Date(task.reminderAt), "MMM d, yyyy h:mm a")}
                          </span>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-1">
                        <Can action="update" subject="task">
                          <Button
                            variant="ghostTableIcon"
                            onClick={(e) => { e.stopPropagation(); handleEdit(task); }}
                          >
                            <Pencil className="size-3.5" />
                          </Button>
                        </Can>
                        <Can action="delete" subject="task">
                          <Button
                            variant="ghostTableDanger"
                            onClick={(e) => { e.stopPropagation(); handleDelete(task.id); }}
                          >
                            <Trash2 className="size-3.5" />
                          </Button>
                        </Can>
                      </div>
                    </TableCell>
                  </TableRow>
                      )
                    })
                  )}
                </TableBody>
              </Table>
            </div>
          </div>
        ) : (
          <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
            <Table variant="transparent">
              <TableHeader>
                <TableRow className="bg-slate-50/50 hover:bg-slate-50/50">
                  <TableHead className="w-12 text-center font-extrabold text-text font-['Lexend'] py-4">#</TableHead>
                  <TableHead className="font-extrabold text-text font-['Lexend'] py-4">Title</TableHead>
                  <TableHead className="font-extrabold text-text font-['Lexend'] py-4">Status</TableHead>
                  <TableHead className="hidden sm:table-cell font-extrabold text-text font-['Lexend'] py-4">Priority</TableHead>
                  <TableHead className="hidden sm:table-cell font-extrabold text-text font-['Lexend'] py-4">Module</TableHead>
                  <TableHead className="hidden md:table-cell font-extrabold text-text font-['Lexend'] py-4">Assigned To</TableHead>
                  <TableHead className="hidden lg:table-cell font-extrabold text-text font-['Lexend'] py-4">Deal</TableHead>
                  <TableHead className="hidden xl:table-cell font-extrabold text-text font-['Lexend'] py-4">Due Date</TableHead>
                  <TableHead className="w-20" />
                </TableRow>
              </TableHeader>
            </Table>
            <div className="flex min-h-0 flex-1 flex-col items-center justify-center px-4 py-12 text-center text-muted-foreground">
              <p className="max-w-sm text-[13px] font-medium font-['Lexend_Deca']">
                {canListAllTasks
                  ? "No tasks found. Create one to get started."
                  : "No tasks assigned to you yet."}
              </p>
            </div>
          </div>
        )}
      </div>

      {/* Pagination & Rows Selector - Compact */}
      {response && (
        <div className="flex flex-col lg:flex-row items-stretch lg:items-center justify-between gap-4 py-4 px-2 border-t border-border/40 mt-auto bg-white/30">
          <div className="flex items-center gap-4">
            <p className="text-[12px] text-gray-600 font-['Lexend_Deca'] font-medium">
              Showing <span className="font-bold text-text">{(page - 1) * limit + 1}</span>–<span className="font-bold text-text">{Math.min(page * limit, response.total)}</span> of <span className="font-bold text-text">{response.total}</span>
            </p>
            <div className="flex items-center gap-2">
              <span className="text-[11px] text-gray-500 font-['Lexend_Deca'] font-bold">Rows:</span>
              <ReactSelect
                value={String(limit)}
                onValueChange={(v) => {
                  setLimit(Number(v))
                  setPage(1)
                }}
                options={limitOptions}
                triggerClassName="h-8 w-[70px] text-[12px] font-bold border-gray-200 bg-white rounded-lg"
                contentClassName="rounded-xl"
              />
            </div>
          </div>
          
          <div className="flex items-center gap-2">
            <Button variant="outline" size="pagination" onClick={() => setPage(Math.max(1, page - 1))} disabled={page <= 1}>
              Previous
            </Button>
            <div className="flex items-center gap-1.5 px-2">
              <span className="text-[12px] font-black text-accent">{page}</span>
              <span className="text-[12px] text-gray-400">/</span>
              <span className="text-[12px] font-bold text-gray-600">{response.totalPages}</span>
            </div>
            <Button variant="outline" size="pagination" onClick={() => setPage(Math.min(response.totalPages, page + 1))} disabled={page >= response.totalPages}>
              Next
            </Button>
          </div>
        </div>
      )}

      <TaskFormModal
        open={modalOpen}
        onClose={handleClose}
        task={editingTask}
      />

      <TaskViewModal
        open={viewOpen}
        onClose={handleCloseView}
        task={viewTask}
      />
    </div>
  )
}
