'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import {
  Table,
  TableBody,
  TableCell,
  TableHeader,
  TableRow
} from '../../ui/Table';

export default function TraineesDataPage() {
  const [trainees, setTrainees] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(`${process.env.NEXT_PUBLIC_API_URL}/items/trainees`, {
      headers: {
        Authorization: `Bearer ${process.env.NEXT_PUBLIC_API_TOKEN}`,
      },
    })
      .then((res) => res.json())
      .then((data) => {
        setTrainees(data.data || []);
        setLoading(false);
      })
      .catch((err) => {
        console.error('Error fetching trainees:', err);
        setLoading(false);
      });
  }, []);

  return (
    <main className="p-6">
      <h1 className="text-2xl font-bold mb-4">Trainees List</h1>
      {loading ? (
        <p>Loading...</p>
      ) : (
        <div className="overflow-auto rounded-lg border border-gray-200 bg-white">
          <Table>
            <TableHeader className="border-b border-gray-100">
              <TableRow>
                <TableCell isHeader className="px-5 py-3 font-medium text-gray-500">Name</TableCell>
                <TableCell isHeader className="px-5 py-3 font-medium text-gray-500">Batch</TableCell>
                <TableCell isHeader className="px-5 py-3 font-medium text-gray-500">DOJ</TableCell>
                <TableCell isHeader className="px-5 py-3 font-medium text-gray-500">Speed</TableCell>
                <TableCell isHeader className="px-5 py-3 font-medium text-gray-500">Accuracy</TableCell>
              </TableRow>
            </TableHeader>
            <TableBody className="divide-y divide-gray-100">
              {trainees.map((trainee) => (
                <TableRow key={trainee.id}>
                  <TableCell className="px-5 py-4 text-blue-600 hover:underline">
                    <Link href={`/pages/TraineesData/trainee/${trainee.id}`}>
                      {trainee.Name}
                    </Link>
                  </TableCell>
                  <TableCell className="px-5 py-4">{trainee.batch_name}</TableCell>
                  <TableCell className="px-5 py-4">{trainee.doj}</TableCell>
                  <TableCell className="px-5 py-4">{trainee.speed}</TableCell>
                  <TableCell className="px-5 py-4">{trainee.accuracy}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}
    </main>
  );
}

export const dynamic = 'force-dynamic';
