"use client";
import React from "react";
import {
  Table,
  TableBody,
  TableRow,
  TableCell,
} from "@/app/shadcn_components/ui/table";
import { DocumentSection } from "./DocumentSection";
import {
  type ReportType,
  REPORT_TYPES,
  dbLabelToReportType,
} from "@/app/db/surveyDB/schema/documents";
import type { getUploadedFile } from "@/app/db/surveyDB/schema/surveyDB";

type Props = {
  uprn: string;
  uploadedFilesData: getUploadedFile[];
};

export const DocumentsTable: React.FC<Props> = ({
  uprn,
  uploadedFilesData,
}) => {
  const filesByType = React.useMemo(() => {
    const map: Partial<Record<ReportType, getUploadedFile[]>> = {};

    for (const file of uploadedFilesData ?? []) {
      const uiKey = dbLabelToReportType[file.docType]; // map DB → UI. We may not have a docType for surveyor files
      if (!uiKey) continue; // unknown/legacy type? skip safely

      (map[uiKey] ??= []).push(file);
    }

    // newest first within each group
    Object.values(map).forEach((arr) =>
      arr!.sort(
        (a, b) =>
          new Date(b.s3FileUploadTimestamp as any).getTime() -
          new Date(a.s3FileUploadTimestamp as any).getTime()
      )
    );

    return map;
  }, [uploadedFilesData]);

  return (
    <Table className="min-w-full table-fixed divide-y divide-gray-200 shadow overflow-hidden border-b border-gray-200 sm:rounded-lg">
      <TableBody className="bg-white divide-y divide-gray-200">
        {REPORT_TYPES.map((reportType) => {
          const filesForType = filesByType[reportType] ?? [];
          return (
            <React.Fragment key={reportType}>
              <DocumentSection
                reportType={reportType}
                uprn={uprn}
                files={filesForType} // array of rows
              />
              <TableRow className="hover:bg-transparent">
                <TableCell colSpan={3} className="h-3 p-0" />
              </TableRow>
            </React.Fragment>
          );
        })}
      </TableBody>
    </Table>
  );
};
