import type { Employee, Initiative, MarketingRole, Task } from "@/lib/marketing";
import { formatDate, MARKETING_ROLE_LABELS } from "@/lib/marketing/labels";

type EmployeePerformanceTableProps = {
  employees: Employee[];
  initiatives: Initiative[];
  tasks: Task[];
  role: MarketingRole;
  currentEmployeeId?: string;
};

type PerformanceRow = {
  employee: Employee;
  completionRate: number;
  initiativesCount: number;
  averageExecutionRating: number;
  lastUpdate: string | null;
};

function calculatePerformanceRows(employees: Employee[], initiatives: Initiative[], tasks: Task[]): PerformanceRow[] {
  return employees.map((employee) => {
    const employeeTasks = tasks.filter((task) => task.assigneeId === employee.id);
    const completedTasks = employeeTasks.filter((task) => task.status === "done").length;
    const completionRate = employeeTasks.length > 0 ? (completedTasks / employeeTasks.length) * 100 : 0;

    const contributedInitiatives = initiatives.filter(
      (initiative) => initiative.ownerId === employee.id || initiative.contributorIds.includes(employee.id)
    );

    const averageExecutionRating =
      contributedInitiatives.length > 0
        ? contributedInitiatives.reduce((acc, initiative) => acc + initiative.leadRating1to5, 0) / contributedInitiatives.length
        : 0;

    const lastUpdate = employeeTasks
      .map((task) => task.updatedAt)
      .sort((a, b) => new Date(b).getTime() - new Date(a).getTime())[0] ?? null;

    return {
      employee,
      completionRate,
      initiativesCount: contributedInitiatives.length,
      averageExecutionRating,
      lastUpdate,
    };
  });
}

export default function EmployeePerformanceTable({
  employees,
  initiatives,
  tasks,
  role,
  currentEmployeeId,
}: EmployeePerformanceTableProps) {
  const allRows = calculatePerformanceRows(employees, initiatives, tasks).sort((a, b) => b.completionRate - a.completionRate);
  const visibleRows = role === "employee" && currentEmployeeId ? allRows.filter((row) => row.employee.id === currentEmployeeId) : allRows;

  return (
    <section className="rounded-benell border border-benell-stroke bg-benell-surface p-5 shadow-benell">
      <h2 className="text-h2 font-semibold">Employee Performance</h2>
      <p className="text-label mt-1 text-benell-text-soft">Vista {MARKETING_ROLE_LABELS[role]} · desempeño por tareas e iniciativas.</p>

      <div className="mt-4 overflow-x-auto">
        <table className="min-w-[760px] w-full border-separate border-spacing-y-2">
          <thead>
            <tr className="text-left text-label text-benell-text-soft">
              <th className="px-3 py-1">Empleado</th>
              <th className="px-3 py-1">Tareas completadas %</th>
              <th className="px-3 py-1">Iniciativas</th>
              <th className="px-3 py-1">Execution rating prom.</th>
              <th className="px-3 py-1">Última actualización</th>
            </tr>
          </thead>
          <tbody>
            {visibleRows.map((row) => (
              <tr key={row.employee.id} className="rounded-xl bg-white">
                <td className="rounded-l-xl px-3 py-3">
                  <p className="text-body font-semibold">{row.employee.name}</p>
                  <p className="text-label text-benell-text-soft">{row.employee.roleTitle}</p>
                </td>
                <td className="px-3 py-3 text-body text-tabular">{row.completionRate.toFixed(1)}%</td>
                <td className="px-3 py-3 text-body text-tabular">{row.initiativesCount}</td>
                <td className="px-3 py-3 text-body text-tabular">{row.averageExecutionRating.toFixed(2)} / 5</td>
                <td className="rounded-r-xl px-3 py-3 text-body text-tabular">{formatDate(row.lastUpdate)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </section>
  );
}
