import React from "react";

interface PolicyData {
  zh: string;
  en: string;
  link: {
    zh: string;
    en: string;
  };
  releaseDate: string;
}

interface AIPoliciesTableProps {
  policies: PolicyData[];
}

const AIPoliciesTable: React.FC<AIPoliciesTableProps> = ({ policies }) => {
  const groupedPolicies = policies.reduce((acc, policy) => {
    const year = new Date(policy.releaseDate).getFullYear();
    if (!acc[year]) {
      acc[year] = [];
    }
    acc[year].push(policy);
    return acc;
  }, {} as { [key: number]: PolicyData[] });

  const sortedYears = Object.keys(groupedPolicies)
    .map(Number)
    .sort((a, b) => b - a);

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const options: Intl.DateTimeFormatOptions = { month: 'short', day: 'numeric', year: 'numeric' };
    return date.toLocaleDateString('en-US', options);
  };

  return (
    <div>
      {sortedYears.map((year) => (
        <div key={year} className="mb-8">
          <button className="text-xl font-bold mb-2 focus:outline-none">
            {year} ▼
          </button>
          <table className="w-full border-collapse table-auto">
            <tbody>
              {groupedPolicies[year].map((policy, index) => (
                <tr
                  key={`${year}-${index}`}
                  className={`${
                    index % 2 === 0 ? "bg-white" : "bg-gray-50"
                  } dark:bg-gray-${index % 2 === 0 ? "700" : "800"}`}
                >
                  <td className="py-2 px-4 dark:text-white">
                    <div>{policy.zh}</div>
                    <div className="text-sm text-gray-500 dark:text-gray-400">
                      {policy.en}
                    </div>
                    <div className="text-xs text-gray-400 dark:text-gray-500">
                      {formatDate(policy.releaseDate)}
                    </div>
                  </td>
                  <td className="py-2 px-4">
                    {policy.link.zh && (
                      <a
                        href={policy.link.zh}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-blue-500 hover:underline dark:text-blue-400 mr-4"
                      >
                        中文
                      </a>
                    )}
                    {policy.link.en && (
                      <a
                        href={policy.link.en}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-blue-500 hover:underline dark:text-blue-400 mr-4"
                      >
                        English
                      </a>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ))}
    </div>
  );
};

export default AIPoliciesTable;
