import DashboardLayout from "@/components/DashboardLayout"
import { auth } from "@/lib/auth"
import { prisma } from "@/lib/prisma"

export default async function ArchivePage() {
  const session = await auth()
  const worker = await prisma.worker.findFirst({
    where: { email: session?.user?.email || "" }
  })

  if (!worker) return <div>Worker not found</div>

  const closedShifts = await prisma.shiftTeamMember.findMany({
    where: {
      workerId: worker.id,
      shift: { status: "closed" }
    },
    include: {
      shift: true,
      team: true,
      machine: true,
    },
    orderBy: { shift: { shiftDate: "desc" } }
  })

  return (
    <DashboardLayout requiredRole="operator">
      <div>
        <h1 className="text-3xl font-bold text-gray-800 mb-6">Shifts Archive</h1>

        <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
          <table className="w-full">
            <thead className="bg-gray-50 border-b border-gray-200">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Date</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Shift</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Team</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Machine</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {closedShifts.map((member) => (
                <tr key={member.id}>
                  <td className="px-6 py-4 text-sm text-gray-900">
                    {new Date(member.shift.shiftDate).toLocaleDateString()}
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-900">{member.shift.name}</td>
                  <td className="px-6 py-4 text-sm text-gray-600">{member.team.name}</td>
                  <td className="px-6 py-4 text-sm text-gray-600">{member.machine?.name || "N/A"}</td>
                  <td className="px-6 py-4 text-sm">
                    <span className="bg-gray-100 text-gray-800 px-3 py-1 rounded-full text-xs font-medium">
                      Closed
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </DashboardLayout>
  )
}
