import React, { useState } 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 groupedPoliciesByYear: { [year: string]: { [slug: string]: PolicyData[] } } = {};

  policies.forEach((policy) => {
    const year = new Date(policy.releaseDate).getFullYear().toString();
    if (!groupedPoliciesByYear[year]) {
      groupedPoliciesByYear[year] = {};
    }
    if (!groupedPoliciesByYear[year][policy.slug]) {
      groupedPoliciesByYear[year][policy.slug] = [];
    }
    groupedPoliciesByYear[year][policy.slug].push(policy);
  });

  const sortedYears = Object.keys(groupedPoliciesByYear).sort((a, b) => parseInt(b) - parseInt(a));

  return (
    <div className="my-8">
      {sortedYears.map((year) => (
        <YearSection key={year} year={year} groupedPolicies={groupedPoliciesByYear[year]} />
      ))}
    </div>
  );
};

interface YearSectionProps {
  year: string;
  groupedPolicies: { [slug: string]: PolicyData[] };
}

const YearSection: React.FC<YearSectionProps> = ({ year, groupedPolicies }) => {
  const [isOpen, setIsOpen] = useState(true);

  return (
    <div className="mb-8">
      <button
        className="text-xl font-bold mb-2 focus:outline-none"
        onClick={() => setIsOpen(!isOpen)}
      >
        {year} {isOpen ? '▼' : '▶'}
      </button>
      {isOpen && (
        <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">{new Date(zhPolicy?.releaseDate || '').toLocaleDateString()}</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>
  );
};

export default AIPoliciesTable;
