import React from 'react';
import Link from 'next/link';

interface PolicyData {
  title: string;
  slug: string;
  fileName: string;
  originalLink?: string;
  releaseDate: string;
}

interface AIPoliciesTableProps {
  policies: PolicyData[];
}

const AIPoliciesTable: React.FC<AIPoliciesTableProps> = ({ policies }) => {
  const groupedPolicies: { [slug: string]: PolicyData[] } = {};

  policies.forEach((policy) => {
    if (!groupedPolicies[policy.slug]) {
      groupedPolicies[policy.slug] = [];
    }
    groupedPolicies[policy.slug].push(policy);
  });

  // Sort the policies within each group based on releaseDate in descending order
  Object.values(groupedPolicies).forEach((group) => {
    group.sort((a, b) => new Date(b.releaseDate).getTime() - new Date(a.releaseDate).getTime());
  });

  return (
    <div className="my-8">
      {/* <h2 className="text-2xl font-bold mb-4 dark:text-white">AI Policies from the Chinese government</h2> */}
      <div className="overflow-x-auto">
        <table className="w-full border-collapse table-auto">
          <tbody>
            {Object.entries(groupedPolicies).map(([slug, policies], index) => {
              const zhPolicy = policies.find((policy) => policy.fileName === 'zh.md');
              const enPolicy = policies.find((policy) => policy.fileName === 'en.md');

              return (
                <tr key={slug} className={`${index % 2 === 0 ? 'bg-white dark:bg-gray-700' : 'bg-gray-50 dark:bg-gray-800'}`}>
                  <td className="py-2 px-4 dark:text-white">
                    <div>{zhPolicy?.title}</div>
                    <div className="text-sm text-gray-500 dark:text-gray-400">{enPolicy?.title}</div>
                    <div className="text-xs text-gray-400 dark:text-gray-500">{zhPolicy?.releaseDate}</div>
                  </td>
                  <td className="py-2 px-4">
                    {policies.map((policy) => (
                      policy.originalLink ? (
                        <a key={policy.fileName} href={policy.originalLink} target="_blank" rel="noopener noreferrer" className="text-blue-500 hover:underline dark:text-blue-400 mr-4">
                          {policy.fileName === 'zh.md' ? '中文' : 'English'}
                        </a>
                      ) : (
                        <Link key={policy.fileName} href={`/policies/${slug}/${policy.fileName}`}>
                          <span className="text-blue-500 hover:underline dark:text-blue-400 mr-4 cursor-pointer">
                            {policy.fileName === 'zh.md' ? '中文' : 'English'}
                          </span>
                        </Link>
                      )
                    ))}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default AIPoliciesTable;
