"use client";

import { useState, useMemo } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { formatCents, formatDate, formatMoney } from "~/lib/format.js";
import { InfoTooltip } from "~/components/ui/InfoTooltip.js";
import { ALLOCATION_STATUS_BADGE } from "~/lib/status-styles.js";
import { usePermissions } from "~/hooks/usePermissions.js";
import { trpc } from "~/lib/trpc/client.js";

function countWorkingDays(start: Date | string, end: Date | string): number {
  const s = new Date(start);
  const e = new Date(end);
  let days = 0;
  const cur = new Date(s);
  while (cur <= e) {
    if (cur.getDay() !== 0 && cur.getDay() !== 6) days++;
    cur.setDate(cur.getDate() + 1);
  }
  return days;
}

interface AssignmentRow {
  id: string;
  role: string | null;
  startDate: Date | string;
  endDate: Date | string;
  hoursPerDay: number;
  dailyCostCents: number;
  status: string;
  resource?: { id: string; displayName: string; eid: string } | null;
}

interface ProjectAssignmentsTableProps {
  assignments: AssignmentRow[];
}

export function ProjectAssignmentsTable({ assignments }: ProjectAssignmentsTableProps) {
  const { canEdit } = usePermissions();
  const router = useRouter();
  const utils = trpc.useUtils();
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [confirmId, setConfirmId] = useState<string | null>(null);

  const deleteMutation = trpc.allocation.deleteAssignment.useMutation({
    onSuccess: () => {
      void utils.allocation.list.invalidate();
      void utils.allocation.listView.invalidate();
      void utils.timeline.getEntries.invalidate();
      void utils.timeline.getEntriesView.invalidate();
      void utils.timeline.getBudgetStatus.invalidate();
      router.refresh();
    },
  });

  async function handleDelete(id: string) {
    setDeletingId(id);
    try {
      await deleteMutation.mutateAsync({ id });
    } finally {
      setDeletingId(null);
      setConfirmId(null);
    }
  }

  return (
    <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
      <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
        <h2 className="text-sm font-semibold text-gray-700 dark:text-gray-300 uppercase tracking-wider">
          Assignments ({assignments.length})
        </h2>
      </div>
      <table className="w-full">
        <thead className="bg-gray-50 dark:bg-gray-800/50 border-b border-gray-200 dark:border-gray-700">
          <tr>
            <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
              Resource <InfoTooltip content="The person assigned to this project for the given period and role." />
            </th>
            <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
              Role <InfoTooltip content="Role this allocation was created for." />
            </th>
            <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
              Period <InfoTooltip content="Start and end date of the allocation." />
            </th>
            <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
              <span className="inline-flex items-center justify-end gap-0.5">
                Hours/Day <InfoTooltip content="Planned working hours per calendar day." />
              </span>
            </th>
            <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
              <span className="inline-flex items-center justify-end gap-0.5">
                Daily Cost <InfoTooltip content="Resource LCR x hours per day." />
              </span>
            </th>
            <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
              <span className="inline-flex items-center justify-end gap-0.5">
                Total Hours <InfoTooltip content="Working days in period x hours per day." />
              </span>
            </th>
            <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
              <span className="inline-flex items-center justify-end gap-0.5">
                Total Cost <InfoTooltip content="Working days x daily cost." />
              </span>
            </th>
            <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
              Status <InfoTooltip content="PROPOSED = requested, CONFIRMED = approved, ACTIVE = ongoing, COMPLETED = finished, CANCELLED = removed." />
            </th>
            {canEdit && (
              <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                Actions
              </th>
            )}
          </tr>
        </thead>
        <tbody className="divide-y divide-gray-100 dark:divide-gray-800">
          {assignments.map((assignment) => (
            <tr key={assignment.id} className="hover:bg-gray-50 dark:hover:bg-gray-800/30 transition-colors">
              <td className="px-4 py-3 text-sm font-medium text-gray-900 dark:text-gray-100">
                {assignment.resource?.displayName ?? "\u2014"}
                {assignment.resource?.eid && (
                  <span className="ml-1.5 text-xs text-gray-400 font-mono">{assignment.resource.eid}</span>
                )}
              </td>
              <td className="px-4 py-3 text-sm text-gray-600 dark:text-gray-400">{assignment.role || "\u2014"}</td>
              <td className="px-4 py-3 text-xs text-gray-500 dark:text-gray-400">
                {formatDate(assignment.startDate)} {"\u2192"} {formatDate(assignment.endDate)}
              </td>
              <td className="px-4 py-3 text-sm text-right text-gray-900 dark:text-gray-100">{assignment.hoursPerDay}h</td>
              <td className="px-4 py-3 text-sm text-right text-gray-900 dark:text-gray-100">
                {formatCents(assignment.dailyCostCents)} €
              </td>
              <td className="px-4 py-3 text-sm text-right text-gray-900 dark:text-gray-100">
                {(countWorkingDays(assignment.startDate, assignment.endDate) * assignment.hoursPerDay).toLocaleString("de-DE", { minimumFractionDigits: 1 })}h
              </td>
              <td className="px-4 py-3 text-sm text-right text-gray-900 dark:text-gray-100">
                {formatMoney(countWorkingDays(assignment.startDate, assignment.endDate) * assignment.dailyCostCents, "EUR", 2)}
              </td>
              <td className="px-4 py-3">
                <span
                  className={`inline-block px-2 py-0.5 text-xs rounded-full ${ALLOCATION_STATUS_BADGE[assignment.status] ?? "bg-gray-100 text-gray-600"}`}
                >
                  {assignment.status}
                </span>
              </td>
              {canEdit && (
                <td className="px-4 py-3 text-right">
                  {confirmId === assignment.id ? (
                    <div className="flex items-center justify-end gap-1.5">
                      <button
                        type="button"
                        onClick={() => void handleDelete(assignment.id)}
                        disabled={deletingId === assignment.id}
                        className="text-xs font-medium text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-200 disabled:opacity-50"
                      >
                        {deletingId === assignment.id ? "Deleting..." : "Confirm"}
                      </button>
                      <button
                        type="button"
                        onClick={() => setConfirmId(null)}
                        disabled={deletingId === assignment.id}
                        className="text-xs text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
                      >
                        Cancel
                      </button>
                    </div>
                  ) : (
                    <button
                      type="button"
                      onClick={() => setConfirmId(assignment.id)}
                      className="text-xs font-medium text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-200"
                    >
                      Delete
                    </button>
                  )}
                </td>
              )}
            </tr>
          ))}
        </tbody>
        {assignments.length > 0 && (() => {
          const totalHours = assignments.reduce((sum, a) => sum + countWorkingDays(a.startDate, a.endDate) * a.hoursPerDay, 0);
          const totalCostCents = assignments.reduce((sum, a) => sum + countWorkingDays(a.startDate, a.endDate) * a.dailyCostCents, 0);
          return (
            <tfoot className="border-t-2 border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-800/50">
              <tr>
                <td colSpan={4} className="px-4 py-3 text-sm font-semibold text-gray-700 dark:text-gray-300 text-right">Totals</td>
                <td className="px-4 py-3 text-sm text-right text-gray-900 dark:text-gray-100">{"\u2014"}</td>
                <td className="px-4 py-3 text-sm font-semibold text-right text-gray-900 dark:text-gray-100">
                  {totalHours.toLocaleString("de-DE", { minimumFractionDigits: 1 })}h
                </td>
                <td className="px-4 py-3 text-sm font-semibold text-right text-gray-900 dark:text-gray-100">
                  {formatMoney(totalCostCents, "EUR", 2)}
                </td>
                <td className="px-4 py-3">{"\u2014"}</td>
                {canEdit && <td />}
              </tr>
            </tfoot>
          );
        })()}
      </table>
      {assignments.length === 0 && (
        <div className="text-center py-12 text-sm text-gray-500 dark:text-gray-400 space-y-2">
          <p>No assignments for this project.</p>
          {canEdit && (
            <p>
              Create staffing entries via{" "}
              <Link href="/allocations" className="text-brand-600 hover:underline dark:text-brand-400">
                Allocations → New Planning Entry
              </Link>
              .
            </p>
          )}
        </div>
      )}
    </div>
  );
}
