"use client";

import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/app/shadcn_components/ui/dialog";
import { Button } from "@/app/shadcn_components/ui/button";
import { Input } from "@/app/shadcn_components/ui/input";
import { useState } from "react";
import { uploadFileToS3 } from "@/app/utils/s3";
import { documentTypeFileTypes, documentTypeTitles, ReportType } from "@/app/db/surveyDB/schema/documents";

type UploadModalProps = {
  open: boolean;
  onClose: () => void;
  documentType: ReportType; // <- strongly typed
  uprn: string;
};

// Fetch presigned URL from API
async function generatePresignedUrls({
  path,
  contentType,
  expiresInSeconds,
}: {
  path: string;
  contentType: string;
  expiresInSeconds: number;
}) {
  const body = JSON.stringify({ path, expiresInSeconds, contentType });
  const res = await fetch("/api/upload/retrofit-energy-assessments", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body,
  });
  if (!res.ok) throw new Error("Failed to get presigned URL");
  return res.json() as Promise<{ url: string }>;
}

// fetch sqs quess and show it in logs for testing purposes
export async function fetchQueuesAndLog() {
  try {
    const res = await fetch("/db/surveyDB/api/show_all_sqs_available");
    if (!res.ok) throw new Error("Failed to fetch queues");
    const data = await res.json();
    console.log("✅ Available SQS queues:", data.queues);
  } catch (err) {
    console.error("❌ Error fetching queues:", err);
  }
}

// Decide content-type from file extension
function contentTypeFor(ext: string): string {
  const e = ext.toLowerCase();
  if (e === "pdf") return "application/pdf";
  if (e === "xml") return "application/xml";
  return "application/octet-stream";
}

export const UploadModal = ({ open, onClose, documentType, uprn }: UploadModalProps) => {
  const [uploadFiles, setUploadFiles] = useState<File[]>([]);
  const [submitting, setSubmitting] = useState(false);

  const accepted = documentTypeFileTypes[documentType]; // ".pdf" | ".xml" | ".xml,.pdf"
  const title = documentTypeTitles[documentType];

  function handleInputOnChange(e: React.ChangeEvent<HTMLInputElement>) {
    if (!e.target.files?.length) {
      setUploadFiles([]);
      return;
    }
    const file = e.target.files[0];

    // Validate by extension against accepted
    const ext = (file.name.split(".").pop() || "").toLowerCase();
    const validExtensions = accepted.split(",").map((x) => x.replace(".", ""));
    const isValid = validExtensions.includes(ext);

    if (!isValid) {
      setUploadFiles([]);
      return;
    }
    setUploadFiles([file]);
  }

  async function handleS3Upload() {
    if (!uploadFiles.length) return;
    setSubmitting(true);

    try {
      // Timestamp like YYYYMMDD_HHMMSS
      const timestamp = new Date()
        .toISOString()
        .replace(/[-:]/g, "")
        .replace("T", "_")
        .split(".")[0];

      const file = uploadFiles[0];
      const ext = (file.name.split(".").pop() || "").toLowerCase();
      const ct = contentTypeFor(ext);

      const s3Key = `documents/${uprn}/${documentType}/${timestamp}.${ext}`;

      // 1) Get presigned URL
      const { url } = await generatePresignedUrls({
        path: s3Key,
        contentType: ct,
        expiresInSeconds: 5 * 60,
      });

      // 2) Upload to S3 via presigned URL
      await uploadFileToS3({
        presignedUrl: url,
        file,
        contentType: ct,
      });

      // 3) Record in DB (store durable HTTPS URL without query params)
      const presigned = new URL(url);
      const s3FileUri = presigned.origin + presigned.pathname;

      const res = await fetch("/db/surveyDB/api/insert_data_to_uploaded_files", {
        // If you move your route to the conventional path, change to "/api/uploaded-files"
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          s3FileUri,
          docType: documentType, // ReportType value
          uprn,
          s3FileUploadTimestamp: new Date().toISOString(),
        }),
      });

      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        console.error("DB insert failed:", err);
        throw new Error("Failed to insert uploaded file record");
      }
      const { id: db_id } = await res.json()
      console.log("db_id is ", db_id);
      // SQS list
      console.log("Sending request to sqs")

      // enqueue only the id
      await fetch("/db/surveyDB/api/send_to_extractor_loader", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id: db_id }),  // 👈 only id
      });
      console.log(`sent request with ${db_id} check with aws sqs queue`);
      // Success — close the dialog and let parent refresh UI
      onClose();
    } catch (err) {
      console.error(err);
      // You can show a toast here if you have one
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Upload Document</DialogTitle>
          <DialogDescription>
            Upload a <strong>{title}</strong>. Once uploaded, automated extraction can begin.
          </DialogDescription>
        </DialogHeader>

        <div className="py-4">
          <Input
            type="file"
            accept={accepted}
            multiple={false}
            className="cursor-pointer"
            onChange={handleInputOnChange}
          />
        </div>

        <DialogFooter>
          <Button variant="secondary" onClick={onClose} disabled={submitting}>
            Cancel
          </Button>
          <Button onClick={handleS3Upload} disabled={!uploadFiles.length || submitting}>
            {submitting ? "Uploading…" : "Upload"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};
