"use client";

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { ChevronLeft, ChevronRight, RefreshCw } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
import { Table, TableHead, TableBody, TableRow, Th, Td, EmptyState } from "@/components/ui/Table";
import { Badge } from "@/components/ui/Badge";
import { Button } from "@/components/ui/Button";
import { formatDate } from "@/lib/utils";
import api from "@/lib/api";
import type { Task, PaginatedResponse } from "@/types";

const statusVariant: Record<string, "success" | "warning" | "default" | "muted"> = {
  done: "success",
  DONE: "success",
  completed: "success",
  COMPLETED: "success",
  in_progress: "default",
  IN_PROGRESS: "default",
  pending: "warning",
  PENDING: "warning",
  cancelled: "muted",
  CANCELLED: "muted",
};

export default function TasksPage() {
  const [page, setPage] = useState(1);

  const { data, isLoading, refetch } = useQuery<PaginatedResponse<Task>>({
    queryKey: ["tasks", page],
    queryFn: async () => {
      const res = await api.get<PaginatedResponse<Task>>(`/api/v1/tasks?page=${page}&limit=20`);
      return res.data;
    },
  });

  const tasks = data?.data ?? [];
  const meta = data?.meta;

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Tasks</h1>
          <p className="text-sm text-gray-500">{meta?.total ?? 0} total tasks</p>
        </div>
        <Button size="sm" variant="outline" onClick={() => refetch()}>
          <RefreshCw className="h-4 w-4" />
          Refresh
        </Button>
      </div>

      <Card>
        <CardHeader><CardTitle>All Tasks</CardTitle></CardHeader>
        <CardContent className="p-0">
          <Table>
            <TableHead>
              <TableRow>
                <Th>Title</Th>
                <Th>Type</Th>
                <Th>Status</Th>
                <Th>Assigned To</Th>
                <Th>Due Date</Th>
                <Th>Linked Ticket</Th>
              </TableRow>
            </TableHead>
            <TableBody>
              {isLoading ? (
                Array.from({ length: 5 }).map((_, i) => (
                  <TableRow key={i}>
                    {Array.from({ length: 6 }).map((_, j) => (
                      <Td key={j}><div className="h-4 w-24 animate-pulse bg-gray-100 rounded" /></Td>
                    ))}
                  </TableRow>
                ))
              ) : tasks.length === 0 ? (
                <EmptyState message="No tasks yet" />
              ) : (
                tasks.map((task) => (
                  <TableRow key={task.id} className="hover:bg-gray-50 transition-colors">
                    <Td className="font-medium">{task.title}</Td>
                    <Td><Badge variant="muted">{task.type}</Badge></Td>
                    <Td>
                      <Badge variant={statusVariant[task.status] ?? "muted"}>
                        {task.status}
                      </Badge>
                    </Td>
                    <Td className="text-gray-500">
                      {task.assignedUser
                        ? `${task.assignedUser.firstName} ${task.assignedUser.lastName}`
                        : task.assignedTo ?? "—"}
                    </Td>
                    <Td className="text-gray-500">
                      {task.dueDate ? formatDate(task.dueDate) : "—"}
                    </Td>
                    <Td className="text-gray-400 text-xs font-mono">
                      {task.ticket?.subject ?? (task.ticketId ? task.ticketId.slice(0, 8) : "—")}
                    </Td>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>

          {meta && meta.totalPages > 1 && (
            <div className="flex items-center justify-between px-4 py-3 border-t border-gray-100">
              <p className="text-sm text-gray-500">Page {meta.page} of {meta.totalPages}</p>
              <div className="flex gap-2">
                <Button size="sm" variant="outline" disabled={page <= 1} onClick={() => setPage(page - 1)}>
                  <ChevronLeft className="h-4 w-4" />
                </Button>
                <Button size="sm" variant="outline" disabled={page >= meta.totalPages} onClick={() => setPage(page + 1)}>
                  <ChevronRight className="h-4 w-4" />
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
