import { notFound } from 'next/navigation';

async function getTrainee(id) {
  try {
    const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/items/trainees/${id}`, {
      headers: {
        Authorization: `Bearer ${process.env.NEXT_PUBLIC_API_TOKEN}`,
      },
    });
    const json = await res.json();
    return json.data;
  } catch (error) {
    console.error('Error fetching trainee:', error);
    return null;
  }
}

async function getAssignmentsByTrainee(traineeId) {
  try {
    const res = await fetch(
      `${process.env.NEXT_PUBLIC_API_URL}/items/assignment?filter[sub_by][_eq]=${traineeId}`,
      {
        headers: {
          Authorization: `Bearer ${process.env.NEXT_PUBLIC_API_TOKEN}`,
        },
      }
    );
    const json = await res.json();
    return json.data || [];
  } catch (error) {
    console.error('Error fetching assignments:', error);
    return [];
  }
}

export default async function TraineeDetailPage({ params: { id } }) {
  const trainee = await getTrainee(id);
  const assignments = await getAssignmentsByTrainee(id);

  if (!trainee) return notFound();

  return (
    <main className="p-6">
      <h1 className="text-2xl font-bold mb-4">{trainee.Name}</h1>
      
      <div className="mb-8">
        <h2 className="text-xl font-semibold mb-2">Trainee Details</h2>
        <ul className="space-y-1">
          <li><strong>Feedback:</strong> {trainee.overall_feedback}</li>
          <li><strong>Attendance:</strong> {trainee.overall_attendance}</li>
          <li><strong>Batch:</strong> {trainee.batch_name}</li>
          <li><strong>Speed:</strong> {trainee.speed}</li>
          <li><strong>Accuracy:</strong> {trainee.accuracy}</li>
          <li><strong>Precision:</strong> {trainee.precision}</li>
          <li><strong>DOJ:</strong> {trainee.doj}</li>
        </ul>
      </div>

      <div>
        <h2 className="text-xl font-semibold mb-2">Assignments</h2>
        {assignments.length === 0 ? (
          <div className="bg-yellow-50 border-l-4 border-yellow-400 p-4">
            <div className="flex">
              <div className="ml-3">
                <p className="text-sm text-yellow-700">
                  No assignments found for this trainee. This could mean:
                </p>
                <ul className="list-disc pl-5 mt-1 text-sm text-yellow-700">
                  <li>The trainee hasn't submitted any assignments yet</li>
                  <li>Assignments exist but are associated with a different ID</li>
                  <li>There might be a data connection issue</li>
                </ul>
                <div className="mt-2 text-xs text-yellow-600">
                  <p>Debug info:</p>
                  <p>Trainee ID: {id}</p>
                  <p>Total assignments in system: {assignments.length}</p>
                </div>
              </div>
            </div>
          </div>
        ) : (
          <div className="space-y-4">
            {assignments.map((assignment, index) => (
              <div key={index} className="border p-4 rounded-md shadow">
                <h3 className="font-medium mb-2">Assignment {index + 1}</h3>
                <p><strong>Format:</strong> {assignment.format || 'Not specified'}</p>
                {assignment.link && (
                  <p>
                    <strong>Main Link:</strong>{" "}
                    <a 
                      href={assignment.link.includes('://') ? assignment.link : `https://${assignment.link}`} 
                      target="_blank" 
                      rel="noopener noreferrer"
                      className="text-blue-600 hover:underline"
                    >
                      {assignment.link}
                    </a>
                  </p>
                )}
                
                <div className="mt-3">
                  <h4 className="font-medium">Submissions:</h4>
                  {assignment.assignments && assignment.assignments.length > 0 ? (
                    <ul className="space-y-2 mt-2">
                      {assignment.assignments.map((submission, subIndex) => (
                        <li key={subIndex} className="border-l-2 pl-3 py-1">
                          <p>
                            <strong>Submission {subIndex + 1}:</strong>{" "}
                            {submission.link_or_zip?.includes('://') ? (
                              <a
                                href={submission.link_or_zip}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="text-blue-600 hover:underline"
                              >
                                {submission.link_or_zip}
                              </a>
                            ) : (
                              submission.link_or_zip || 'No link provided'
                            )}
                          </p>
                          {submission.info && (
                            <p className="mt-1"><strong>Feedback:</strong> {submission.info}</p>
                          )}
                        </li>
                      ))}
                    </ul>
                  ) : (
                    <p className="text-sm text-gray-500">No submissions yet</p>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </main>
  );
}