"use client";

import Link from "next/link";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { cn, getInitials } from "@/lib/utils";
import {
  CalendarDays,
  Eye,
  ListTodo,
  AlertCircle,
  CheckCircle2,
} from "lucide-react";
import { formatDistanceToNow } from "date-fns";
import { TASK_STATUS_CONFIG, TASK_TYPE_LABELS } from "@/components/tasks/TaskCard";
import { TaskStatus, TaskType } from "@prisma/client";

const PRIORITY_DOT: Record<string, string> = {
  LOW: "bg-zinc-500",
  NORMAL: "bg-blue-500",
  HIGH: "bg-amber-500",
  URGENT: "bg-red-500",
};

interface TaskRow {
  id: string;
  title: string;
  type: TaskType;
  status: TaskStatus;
  priority: string;
  dueDate: Date | null;
  shot?: { shotCode: string } | null;
  asset?: { assetCode: string } | null;
  project: { id: string; name: string; code: string };
  assignedArtist?: { id: string; name: string | null; email: string; image: string | null } | null;
}

function TaskRow({ task }: { task: TaskRow }) {
  const cfg = TASK_STATUS_CONFIG[task.status];
  const Icon = cfg.icon;
  const contextCode = task.shot?.shotCode ?? task.asset?.assetCode;
  const isOverdue =
    task.dueDate &&
    new Date(task.dueDate) < new Date() &&
    task.status !== "DONE";

  return (
    <Link
      href={`/tasks/${task.id}`}
      className="flex items-center gap-3 px-3 py-2.5 rounded-lg hover:bg-zinc-800/60 transition-colors group"
    >
      <span
        className={cn(
          "w-1.5 h-1.5 rounded-full shrink-0",
          PRIORITY_DOT[task.priority] ?? "bg-zinc-500"
        )}
      />
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2">
          <span className="text-sm font-medium text-zinc-200 group-hover:text-amber-400 transition-colors truncate">
            {task.title}
          </span>
          {contextCode && (
            <span className="text-[10px] font-mono text-zinc-500 bg-zinc-800 px-1.5 py-0.5 rounded shrink-0">
              {contextCode}
            </span>
          )}
        </div>
        <div className="flex items-center gap-2 mt-0.5">
          <span className="text-[11px] text-zinc-500">{TASK_TYPE_LABELS[task.type]}</span>
          <span className="text-[11px] text-zinc-700">·</span>
          <span className="text-[11px] text-zinc-500">{task.project.code}</span>
        </div>
      </div>

      <div className="flex items-center gap-2 shrink-0">
        {task.assignedArtist && (
          <Avatar className="h-5 w-5">
            <AvatarFallback className="text-[8px] bg-zinc-700 text-zinc-300">
              {getInitials(task.assignedArtist.name ?? task.assignedArtist.email)}
            </AvatarFallback>
          </Avatar>
        )}
        {task.dueDate && (
          <span
            className={cn(
              "flex items-center gap-1 text-[10px]",
              isOverdue ? "text-red-400" : "text-zinc-500"
            )}
          >
            <CalendarDays className="h-3 w-3" />
            {formatDistanceToNow(new Date(task.dueDate), { addSuffix: true })}
          </span>
        )}
        <Badge
          className={cn("text-[10px] border px-1.5 py-0 h-4 gap-1 shrink-0", cfg.color)}
        >
          <Icon className="h-2.5 w-2.5" />
          {cfg.label}
        </Badge>
      </div>
    </Link>
  );
}

interface TaskWidgetsProps {
  myTasks: TaskRow[];
  reviewTasks: TaskRow[];
  role: string;
}

export function TaskWidgets({ myTasks, reviewTasks, role }: TaskWidgetsProps) {
  const isArtist = role === "ARTIST";
  const showReview = !isArtist && reviewTasks.length > 0;

  if (myTasks.length === 0 && reviewTasks.length === 0) return null;

  return (
    <div className={cn("grid gap-4", showReview ? "grid-cols-1 xl:grid-cols-2" : "grid-cols-1")}>
      {/* My Tasks */}
      {myTasks.length > 0 && (
        <div className="rounded-xl border border-zinc-800 bg-zinc-900/60">
          <div className="flex items-center justify-between px-4 py-3 border-b border-zinc-800">
            <div className="flex items-center gap-2">
              <ListTodo className="h-4 w-4 text-amber-400" />
              <span className="text-sm font-semibold text-zinc-200">My Tasks</span>
              <span className="text-xs text-zinc-600 bg-zinc-800 rounded-full px-2 py-0.5 font-mono">
                {myTasks.length}
              </span>
            </div>
            <Link
              href="/tasks"
              className="text-xs text-zinc-500 hover:text-amber-400 transition-colors"
            >
              View all →
            </Link>
          </div>
          <div className="divide-y divide-zinc-800/50">
            {myTasks.map((task) => (
              <TaskRow key={task.id} task={task} />
            ))}
          </div>
        </div>
      )}

      {/* Tasks In Review (supervisors/producers) */}
      {showReview && (
        <div className="rounded-xl border border-zinc-800 bg-zinc-900/60">
          <div className="flex items-center justify-between px-4 py-3 border-b border-zinc-800">
            <div className="flex items-center gap-2">
              <Eye className="h-4 w-4 text-purple-400" />
              <span className="text-sm font-semibold text-zinc-200">Needs Review</span>
              <span className="text-xs text-zinc-600 bg-zinc-800 rounded-full px-2 py-0.5 font-mono">
                {reviewTasks.length}
              </span>
            </div>
            <Link
              href="/tasks?status=INTERNAL_REVIEW"
              className="text-xs text-zinc-500 hover:text-amber-400 transition-colors"
            >
              View all →
            </Link>
          </div>
          <div className="divide-y divide-zinc-800/50">
            {reviewTasks.map((task) => (
              <TaskRow key={task.id} task={task} />
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
