"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { FileText, ExternalLink, AlertCircle, Loader2, ChevronRight, CheckCircle2 } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useGetAllRejections } from "../hooks/dashboard.hooks";
import { getStatusVariant } from "@/lib/status-variant";

export function TaskRejectionsPanel() {
  const router = useRouter();
  const { data: tasks, isLoading } = useGetAllRejections();
  const [navigatingId, setNavigatingId] = useState<string | null>(null);

  const handleTaskClick = (taskId: string) => {
    setNavigatingId(taskId);
    router.push(`/client/tasks/${taskId}`);
  };

  const count = tasks?.length ?? 0;

  return (
    <Card className="border-border bg-card shadow-sm rounded-xl overflow-hidden gap-0 py-0">
      <CardHeader className="border-b border-border py-3.5 px-5 bg-muted/40 flex flex-row items-center justify-between">
        <CardTitle className="flex items-center gap-2 text-sm font-semibold text-foreground">
        Rejected Tasks
          {count > 0 && (
            <Badge variant="destructive" className="text-[5px]">{count}</Badge>
          )}
        </CardTitle>
      </CardHeader>

      <CardContent className="p-5">
        {isLoading ? (
          <div className="space-y-3">
            {[1, 2].map((i) => (
              <Skeleton key={i} className="h-24 w-full rounded-lg" />
            ))}
          </div>
        ) : count === 0 ? (
          <div className="flex flex-col items-center justify-center py-8 text-center gap-1.5">
            <CheckCircle2 className="h-5 w-5 text-green-600" />
            <p className="text-xs text-muted-foreground">No rejected tasks right now.</p>
          </div>
        ) : (
          <div className="space-y-3">
            {tasks!.map((task) => {
              const isNavigating = navigatingId === task.id;

              return (
                <div
                  key={task.id}
                  className="rounded-lg border border-red-200 bg-red-50/50 overflow-hidden"
                >
                  {/* Task header — clickable, redirects to task detail */}
                  <button
                    type="button"
                    onClick={() => handleTaskClick(task.id)}
                    disabled={navigatingId !== null}
                    className="w-full flex items-center justify-between gap-3 px-4 py-2.5 border-b border-red-200 bg-red-100/40 hover:bg-red-100/70 transition-colors text-left disabled:cursor-not-allowed"
                  >
                    <div className="min-w-0">
                      <p className="text-sm font-semibold text-red-900 truncate">{task.title}</p>
                      <p className="text-[11px] text-red-700">{task.service?.name ?? "—"}</p>
                    </div>
                    <div className="flex items-center gap-2 shrink-0">
                      <Badge
                        variant={getStatusVariant(task.status)}
                        className="text-[10px] whitespace-nowrap"
                      >
                        {task.status.replace(/_/g, " ")}
                      </Badge>
                      {isNavigating ? (
                        <Loader2 className="h-3.5 w-3.5 animate-spin text-red-500" />
                      ) : (
                        <ChevronRight className="h-3.5 w-3.5 text-red-400" />
                      )}
                    </div>
                  </button>

                  {/* Documents with their individual status */}
                  {(task.documents ?? []).length > 0 ? (
                    <ul className="divide-y divide-red-100">
                      {(task.documents ?? []).map((doc) => (
                        <li key={doc.id} className="flex items-start justify-between gap-3 px-4 py-2.5">
                          <div className="flex items-start gap-2 min-w-0">
                            <FileText className="h-3.5 w-3.5 shrink-0 text-red-500 mt-0.5" />
                            <div className="min-w-0">
                              <p className="text-xs font-medium text-red-900 truncate">
                                {doc.serviceDocument?.name ?? doc.fileName}
                              </p>
                              {doc.aiVerificationNotes && (
                                <p className="text-[11px] text-red-700 mt-0.5">
                                  {doc.aiVerificationNotes}
                                </p>
                              )}
                            </div>
                          </div>
                          <div className="flex items-center gap-2 shrink-0">
                            <Badge
                              variant={getStatusVariant(doc.status)}
                              className="text-[10px] whitespace-nowrap"
                            >
                              {doc.status.replace(/_/g, " ")}
                            </Badge>
                            <a
                              href={doc.fileUrl}
                              target="_blank"
                              rel="noopener noreferrer"
                              onClick={(e) => e.stopPropagation()}
                              className="inline-flex items-center gap-1 text-[10px] text-blue-600 hover:underline"
                            >
                              View <ExternalLink className="h-3 w-3" />
                            </a>
                          </div>
                        </li>
                      ))}
                    </ul>
                  ) : (
                    <p className="px-4 py-2.5 text-xs text-red-700">No documents attached.</p>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </CardContent>
    </Card>
  );
}