"use client";

import Link from "next/link";
import { format, addDays, startOfWeek, differenceInDays, parseISO } from "date-fns";
import { CalendarDays, AlertTriangle, Clock, Users, ExternalLink } from "lucide-react";
import { cn } from "@/lib/utils";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { getInitials } from "@/lib/utils";
import { TASK_STATUS_CONFIG, TASK_TYPE_LABELS } from "@/components/tasks/TaskCard";
import { TaskStatus, TaskType } from "@prisma/client";

function toDate(val: string | null | undefined): Date | null {
  if (!val) return null;
  try {
    return parseISO(val);
  } catch {
    return new Date(val);
  }
}

interface ScheduleTask {
  id: string;
  title: string;
  type: string;
  status: string;
  priority: string;
  dueDate: string | null;
  estimatedHours: number | null;
  scheduledStartDate: string | null;
  scheduledEndDate: string | null;
  assignedArtistId: string | null;
  assignedArtist: {
    id: string;
    name: string | null;
    email: string;
    image: string | null;
  } | null;
  shot: { shotCode: string } | null;
  asset: { assetCode: string } | null;
  project: { id: string; name: string; code: string };
}

interface ScheduleWidgetsProps {
  scheduledTasks: ScheduleTask[];
  artists: {
    id: string;
    name: string | null;
    email: string;
    image: string | null;
    role: string;
  }[];
}

function calcArtistLoad(
  tasks: ScheduleTask[],
  artistId: string,
  weekStart: Date
): number {
  const weekEnd = addDays(weekStart, 6);
  const artistTasks = tasks.filter((t) => t.assignedArtistId === artistId);
  let totalHours = 0;

  for (const task of artistTasks) {
    const start = toDate(task.scheduledStartDate);
    const end = toDate(task.scheduledEndDate) ?? start;
    if (!start || !end) continue;

    // Check overlap with week
    if (start > weekEnd || end < weekStart) continue;

    const dur = Math.max(1, differenceInDays(end, start) + 1);
    const hoursPerDay = (task.estimatedHours ?? 8) / dur;

    // Count days in this week
    let daysInWeek = 0;
    for (let i = 0; i < 7; i++) {
      const day = addDays(weekStart, i);
      if (day >= start && day <= end) daysInWeek++;
    }

    totalHours += hoursPerDay * daysInWeek;
  }

  return totalHours;
}

export function ScheduleWidgets({
  scheduledTasks,
  artists,
}: ScheduleWidgetsProps) {
  const today = new Date();
  const weekStart = startOfWeek(today, { weekStartsOn: 1 });
  const weekEnd = addDays(weekStart, 6);

  // Tasks due this week
  const dueThisWeek = scheduledTasks.filter((t) => {
    const due = toDate(t.dueDate);
    return due && due >= today && due <= weekEnd && t.status !== "DONE";
  });

  // Overloaded artists (> 40h this week = > 8h/day avg)
  const artistLoads = artists.map((a) => ({
    artist: a,
    hours: calcArtistLoad(scheduledTasks, a.id, weekStart),
  }));

  const overloaded = artistLoads.filter((al) => al.hours > 40);

  // Upcoming reviews
  const upcomingReviews = scheduledTasks.filter(
    (t) =>
      t.status === "INTERNAL_REVIEW" || t.status === "CLIENT_REVIEW"
  );

  return (
    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
      {/* Due This Week */}
      <div className="rounded-lg border border-zinc-800 bg-zinc-900 overflow-hidden">
        <div className="flex items-center justify-between px-4 py-3 border-b border-zinc-800">
          <div className="flex items-center gap-2">
            <CalendarDays className="h-4 w-4 text-amber-400" />
            <span className="text-sm font-medium text-zinc-200">
              Due This Week
            </span>
          </div>
          <span className="text-xs bg-zinc-800 text-zinc-400 px-2 py-0.5 rounded-full">
            {dueThisWeek.length}
          </span>
        </div>
        <div className="divide-y divide-zinc-800/60 max-h-52 overflow-y-auto">
          {dueThisWeek.length === 0 ? (
            <div className="px-4 py-6 text-center text-xs text-zinc-600">
              No tasks due this week
            </div>
          ) : (
            dueThisWeek.slice(0, 6).map((task) => {
              const code = task.shot?.shotCode ?? task.asset?.assetCode;
              const cfg = TASK_STATUS_CONFIG[task.status as TaskStatus];
              const StatusIcon = cfg.icon;
              return (
                <Link
                  key={task.id}
                  href={`/tasks/${task.id}`}
                  className="flex items-center gap-2.5 px-4 py-2.5 hover:bg-zinc-800/50 transition-colors"
                >
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-1.5">
                      {code && (
                        <span className="text-[10px] font-mono text-zinc-500">
                          {code}
                        </span>
                      )}
                      <span className="text-xs text-zinc-300 truncate">
                        {task.title}
                      </span>
                    </div>
                    <div className="flex items-center gap-1.5 mt-0.5">
                      <span
                        className={cn(
                          "text-[10px]",
                          cfg.color.split(" ").find((c) => c.startsWith("text-"))
                        )}
                      >
                        {cfg.label}
                      </span>
                      {task.dueDate && (
                        <span className="text-[10px] text-zinc-600">
                          {format(toDate(task.dueDate)!, "EEE, MMM d")}
                        </span>
                      )}
                    </div>
                  </div>
                  {task.assignedArtist && (
                    <Avatar className="h-5 w-5 shrink-0">
                      <AvatarImage src={task.assignedArtist.image ?? undefined} />
                      <AvatarFallback className="text-[8px] bg-zinc-700">
                        {getInitials(
                          task.assignedArtist.name ?? task.assignedArtist.email
                        )}
                      </AvatarFallback>
                    </Avatar>
                  )}
                </Link>
              );
            })
          )}
        </div>
      </div>

      {/* Artist Utilization */}
      <div className="rounded-lg border border-zinc-800 bg-zinc-900 overflow-hidden">
        <div className="flex items-center justify-between px-4 py-3 border-b border-zinc-800">
          <div className="flex items-center gap-2">
            <Users className="h-4 w-4 text-blue-400" />
            <span className="text-sm font-medium text-zinc-200">
              This Week
            </span>
          </div>
          <Link
            href="/schedule"
            className="text-[10px] text-zinc-500 hover:text-amber-400 flex items-center gap-0.5 transition-colors"
          >
            Schedule <ExternalLink className="h-2.5 w-2.5" />
          </Link>
        </div>
        <div className="divide-y divide-zinc-800/60 max-h-52 overflow-y-auto">
          {artistLoads.length === 0 ? (
            <div className="px-4 py-6 text-center text-xs text-zinc-600">
              No scheduled work this week
            </div>
          ) : (
            artistLoads
              .filter((al) => al.hours > 0)
              .sort((a, b) => b.hours - a.hours)
              .slice(0, 6)
              .map(({ artist, hours }) => {
                const pct = Math.min(100, (hours / 40) * 100);
                const isOver = hours > 40;
                return (
                  <div key={artist.id} className="px-4 py-2.5">
                    <div className="flex items-center gap-2 mb-1.5">
                      <Avatar className="h-5 w-5 shrink-0">
                        <AvatarImage src={artist.image ?? undefined} />
                        <AvatarFallback className="text-[8px] bg-zinc-700">
                          {getInitials(artist.name ?? artist.email)}
                        </AvatarFallback>
                      </Avatar>
                      <span className="text-xs text-zinc-300 flex-1 truncate">
                        {artist.name ?? artist.email.split("@")[0]}
                      </span>
                      <span
                        className={cn(
                          "text-[10px] font-medium",
                          isOver ? "text-orange-400" : "text-zinc-500"
                        )}
                      >
                        {Math.round(hours)}h
                        {isOver && " ⚠"}
                      </span>
                    </div>
                    <div className="h-1 bg-zinc-800 rounded-full overflow-hidden">
                      <div
                        className={cn(
                          "h-full rounded-full transition-all",
                          isOver ? "bg-orange-500" : "bg-blue-500"
                        )}
                        style={{ width: `${pct}%` }}
                      />
                    </div>
                  </div>
                );
              })
          )}
        </div>
      </div>

      {/* Upcoming Reviews */}
      <div className="rounded-lg border border-zinc-800 bg-zinc-900 overflow-hidden">
        <div className="flex items-center justify-between px-4 py-3 border-b border-zinc-800">
          <div className="flex items-center gap-2">
            <Clock className="h-4 w-4 text-purple-400" />
            <span className="text-sm font-medium text-zinc-200">
              In Review
            </span>
          </div>
          <span className="text-xs bg-zinc-800 text-zinc-400 px-2 py-0.5 rounded-full">
            {upcomingReviews.length}
          </span>
        </div>
        <div className="divide-y divide-zinc-800/60 max-h-52 overflow-y-auto">
          {upcomingReviews.length === 0 ? (
            <div className="px-4 py-6 text-center text-xs text-zinc-600">
              Nothing in review
            </div>
          ) : (
            upcomingReviews.slice(0, 6).map((task) => {
              const code = task.shot?.shotCode ?? task.asset?.assetCode;
              const isClient = task.status === "CLIENT_REVIEW";
              return (
                <Link
                  key={task.id}
                  href={`/tasks/${task.id}`}
                  className="flex items-center gap-2.5 px-4 py-2.5 hover:bg-zinc-800/50 transition-colors"
                >
                  <div
                    className={cn(
                      "w-1.5 h-1.5 rounded-full shrink-0",
                      isClient ? "bg-amber-400" : "bg-purple-400"
                    )}
                  />
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-1.5">
                      {code && (
                        <span className="text-[10px] font-mono text-zinc-500">
                          {code}
                        </span>
                      )}
                      <span className="text-xs text-zinc-300 truncate">
                        {task.title}
                      </span>
                    </div>
                    <span
                      className={cn(
                        "text-[10px]",
                        isClient ? "text-amber-500" : "text-purple-500"
                      )}
                    >
                      {isClient ? "Client Review" : "Internal Review"}
                    </span>
                  </div>
                </Link>
              );
            })
          )}
        </div>
      </div>
    </div>
  );
}
