import prisma from "@/lib/prisma";
import { auth } from "@/lib/auth";
import { redirect } from "next/navigation";
import { AnnouncementActions, AnnouncementForm } from "./AnnouncementActions";

interface AnnouncementRow {
  id: number;
  title: string;
  content: string;
  type: string;
  target: string;
  active: boolean;
  expires_at: Date | null;
  created_at: Date;
}

export default async function AdminAnnouncementsPage() {
  const session = await auth();
  if (!session?.user || session.user.userType !== "admin") {
    redirect("/login");
  }

  let announcements: AnnouncementRow[] = [];
  try {
    announcements = await prisma.$queryRawUnsafe(
      `SELECT * FROM announcements ORDER BY created_at DESC`
    );
  } catch (e) {
    console.error("Failed to load announcements:", e);
  }

  const typeColors: Record<string, string> = {
    info: "bg-blue-500/20 text-blue-400",
    warning: "bg-yellow-500/20 text-yellow-400",
    urgent: "bg-red-500/20 text-red-400",
    success: "bg-green-500/20 text-green-400",
  };

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold">Announcements</h1>

      {/* Create Form */}
      <div className="bg-surface rounded-lg p-6">
        <h2 className="text-lg font-semibold mb-4">Create Announcement</h2>
        <AnnouncementForm />
      </div>

      {/* Announcements Table */}
      <div className="bg-surface rounded-lg overflow-x-auto">
        <table className="w-full text-left">
          <thead>
            <tr className="border-b border-surface-light text-text-muted text-sm">
              <th className="p-4 font-medium">Title</th>
              <th className="p-4 font-medium">Type</th>
              <th className="p-4 font-medium">Target</th>
              <th className="p-4 font-medium">Active</th>
              <th className="p-4 font-medium">Expires</th>
              <th className="p-4 font-medium">Created</th>
              <th className="p-4 font-medium">Actions</th>
            </tr>
          </thead>
          <tbody>
            {announcements.length === 0 ? (
              <tr>
                <td colSpan={7} className="p-4 text-center text-text-muted">
                  No announcements.
                </td>
              </tr>
            ) : (
              announcements.map((ann) => (
                <tr
                  key={ann.id}
                  className="border-b border-surface-light last:border-0"
                >
                  <td className="p-4 font-medium max-w-[200px] truncate">
                    {ann.title}
                  </td>
                  <td className="p-4">
                    <span
                      className={`inline-block px-2 py-0.5 rounded text-xs font-medium ${
                        typeColors[ann.type] || "bg-surface-light"
                      }`}
                    >
                      {ann.type}
                    </span>
                  </td>
                  <td className="p-4 text-text-muted text-sm">{ann.target}</td>
                  <td className="p-4">
                    {ann.active ? (
                      <span className="text-green-400">Active</span>
                    ) : (
                      <span className="text-red-400">Inactive</span>
                    )}
                  </td>
                  <td className="p-4 text-text-muted text-sm">
                    {ann.expires_at
                      ? new Date(ann.expires_at).toLocaleString()
                      : "Never"}
                  </td>
                  <td className="p-4 text-text-muted text-sm">
                    {new Date(ann.created_at).toLocaleDateString()}
                  </td>
                  <td className="p-4">
                    <AnnouncementActions
                      announcementId={ann.id}
                      isActive={ann.active}
                    />
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
