"use client";

import React from "react";
import {
  Table,
  TableBody,
  TableCell,
  TableRow,
} from "@/app/shadcn_components/ui/table";
import { BrandButton } from "@/app/components/Buttons";
import { useMutation } from "@tanstack/react-query";
import { DocumentType } from "@/app/db/schema/energy_assessments";

// Use the type directly from the array
type Document = {
  id: bigint;
  documentType: (typeof DocumentType)[number]; // Create a union type from the array
  documentLocation: string; // S3 file key
  uploadedAt: Date;
};

type Props = {
  documents: Document[];
  allowedTypes: (typeof DocumentType)[number][]; // Use the union type for allowedTypes as well
};

// Descriptions based on the document types
const descriptions: { [key in (typeof DocumentType)[number]]: string } = {
  EPR: "Contains current energy performance of your home, and recommendations for improvement",
  "Condition Report":
    "Detailed report on property condition, including photographs",
  "Evidence Report": "Additional photographic evidence from the survey",
  "Summary Information": "Summarized survey outputs and site notes",
  "Floor Plan": "Layout of the property and room/window dimensions",
  "Scenario Draft EPC": "Draft EPC based on a given scenario",
  "Scenario Site Notes": "Site notes from the scenario analysis",
};

// Fetch the presigned URL from the API
async function generatePresignedUrl(fileKey: string) {
  const response = await fetch("/api/energy-assessment-documents", {
    method: "POST",
    body: JSON.stringify({ fileKey }),
  });

  if (!response.ok) {
    throw new Error("Failed to generate presigned URL");
  }

  const data = await response.json();
  return data.url;
}

export const DocumentsTable: React.FC<Props> = ({
  documents,
  allowedTypes,
}) => {
  // Filter the documents based on the allowed types
  const relevantDocuments = documents.filter((doc) =>
    allowedTypes.includes(doc.documentType)
  );

  // Mutation to handle the presigned URL generation
  const { mutate: fetchPresignedUrl } = useMutation(
    // Use the file key as the argument to generate the URL
    async (fileKey: string) => await generatePresignedUrl(fileKey),
    {
      onSuccess: (url) => {
        window.open(url, "_blank"); // Open the file in a new tab
      },
      onError: (error) => {
        console.error("Error generating presigned URL:", error);
      },
    }
  );

  const handleDownload = (documentLocation: string) => {
    // Generate URL and open in new tab
    fetchPresignedUrl(documentLocation);
  };

  return (
    <Table className="min-w-full 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">
        {relevantDocuments.map((doc) => (
          <TableRow key={doc.id.toString()}>
            <TableCell className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
              {doc.documentType}
            </TableCell>
            <TableCell className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
              {descriptions[doc.documentType] || ""}
            </TableCell>
            <TableCell className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
              <BrandButton
                label="Download"
                onClick={() => handleDownload(doc.documentLocation)} // Call the download handler
                backgroundColor="brandgold"
              />
            </TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  );
};
