"use client";
import { BASE_URL } from "@/Constant";

export default function GLATable({ table }: any) {
  const handleDownload = (fileName: string) => {
    const fileUrl = `${BASE_URL}${fileName}`;
    window.open(fileUrl, "_blank");
  };

  // ✅ Sort table alphabetically by postTitle
  const sortedTable = table
    ? [...table].sort((a, b) =>
        a.postTitle?.toLowerCase().localeCompare(b.postTitle?.toLowerCase())
      )
    : [];

  return (
    <div className="container m-auto mt-20">
      <div className="flex items-start justify-between md:flex-row flex-col m-auto max-w-7xl md:w-[87%] mx-auto px-4 w-full">
        <h2>Download the documents</h2>
      </div>

      <div className="md:w-[87%] m-auto px-4 py-5">
        <div className="max-w-6xl mx-auto bg-white/25 rounded-xl shadow-lg overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="bg-gray-25 border-b">
                  <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700">
                    Format (Application Form)
                  </th>
                  <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700">
                    Download
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200">
                {sortedTable.map((event: any, index: number) => (
                  <tr
                    key={index}
                    className="hover:bg-gray-50 transition-colors duration-150 ease-in-out"
                  >
                    <td className="px-6 py-4 text-sm text-gray-600">
                      {event.postTitle}
                    </td>
                    <td className="px-6 py-4">
                      <button
                        onClick={() => handleDownload(event.file)}
                        className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800"
                      >
                        Download PDF
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
}
