import { prisma } from "@/lib/prisma";
import EmergencyActions from "@/components/EmergencyActions";

export const dynamic = "force-dynamic";

export default async function EmergencyPage() {
  const events = await prisma.emergencyEvent.findMany({
    include: { employee: { include: { user: { select: { name: true } } } } },
    orderBy: { createdAt: "desc" },
    take: 100,
  });

  return (
    <div className="p-8">
      <h1 className="text-2xl font-semibold mb-6">Emergency / SOS</h1>
      <div className="rounded-xl border border-slate-800 overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-slate-900 text-slate-400 text-left">
            <tr>
              <th className="px-4 py-3">Employee</th>
              <th className="px-4 py-3">Location</th>
              <th className="px-4 py-3">Status</th>
              <th className="px-4 py-3">Triggered</th>
              <th className="px-4 py-3"></th>
            </tr>
          </thead>
          <tbody>
            {events.map((e) => (
              <tr key={e.id} className="border-t border-slate-800">
                <td className="px-4 py-3">{e.employee.user.name}</td>
                <td className="px-4 py-3 text-slate-400">
                  {e.latitude != null ? `${e.latitude.toFixed(4)}, ${e.longitude?.toFixed(4)}` : "Unknown"}
                </td>
                <td className="px-4 py-3">
                  <span
                    className={
                      e.status === "ACTIVE"
                        ? "text-red-400"
                        : e.status === "ACKNOWLEDGED"
                        ? "text-amber-400"
                        : "text-emerald-400"
                    }
                  >
                    {e.status === "ACTIVE" ? "🚨 ACTIVE" : e.status}
                  </span>
                </td>
                <td className="px-4 py-3 text-slate-400">{new Date(e.createdAt).toLocaleString()}</td>
                <td className="px-4 py-3">
                  <EmergencyActions eventId={e.id} status={e.status} />
                </td>
              </tr>
            ))}
            {events.length === 0 && (
              <tr>
                <td colSpan={5} className="px-4 py-8 text-center text-slate-500">
                  No emergency events.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
