import React from 'react';
import { getPayload } from 'payload';
import configPromise from '@payload-config';
import { Container, Card, Heading } from '@/components/ui';

export const AgbHistoryBlock: React.FC<{ title: string }> = async ({ title }) => {
  const payload = await getPayload({ config: configPromise });

  const agbs = await payload.find({
    collection: 'agbs-collection',
    sort: '-versionDate',
    limit: 100,
  });

  if (agbs.totalDocs === 0) {
    return null;
  }

  return (
    <div className="my-16 p-8 md:p-12 bg-neutral-light rounded-3xl shadow-sm border border-neutral-medium">
      <Heading level={3} className="mb-8 text-saturated">
        {title || 'Vorherige Versionen'}
      </Heading>
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {agbs.docs.map((agb: any) => {
          const date = new Date(agb.versionDate).toLocaleDateString('de-DE', {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
          });

          const fileUrl = typeof agb.file === 'object' ? agb.file.url : '';
          const filename = typeof agb.file === 'object' ? agb.file.filename : 'agb.pdf';

          return (
            <div
              key={agb.id}
              className="flex items-center justify-between p-6 bg-white rounded-2xl shadow-sm border border-neutral-medium hover:border-primary transition-all group"
            >
              <div>
                <h4 className="font-bold text-saturated group-hover:text-primary transition-colors">
                  {agb.title}
                </h4>
                <p className="text-sm text-text-secondary mt-1">Gültig ab {date}</p>
              </div>
              {fileUrl && (
                <a
                  href={fileUrl}
                  download={filename}
                  className="p-3 bg-neutral-light text-primary rounded-full hover:bg-primary hover:text-white transition-all shadow-sm"
                  title="PDF herunterladen"
                >
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="24"
                    height="24"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  >
                    <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
                    <polyline points="7 10 12 15 17 10" />
                    <line x1="12" x2="12" y1="15" y2="3" />
                  </svg>
                </a>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
};
