import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { DetailTicket } from "./info-lainnya-types";
import { useState } from "react";

interface InfoLainnyaModalProps {
  open: boolean;
  onClose: () => void;
  data: DetailTicket["emergencyIssue"];
}

export default function InfoLainnyaModal({
  open,
  onClose,
  data,
}: InfoLainnyaModalProps) {
  const files = data?.uploadFiles || [];
  const [currentIndex, setCurrentIndex] = useState(0);

  const handlePrev = () => {
    setCurrentIndex((prev) => (prev > 0 ? prev - 1 : prev));
  };

  const handleNext = () => {
    setCurrentIndex((prev) => (prev < files.length - 1 ? prev + 1 : prev));
  };

  const currentFile = files[currentIndex];
  const isImage = (fileUrl: string) =>
    /\.(jpeg|jpg|png|gif|bmp|webp)$/i.test(fileUrl.toLowerCase());

  const getIframeUrl = (fileUrl: string): string => {
    const lower = fileUrl.toLowerCase();

    // Dokumen ditampilkan melalui Google Docs Viewer
    if (/\.(pdf|doc|docx|xls|xlsx|ppt|pptx)$/i.test(lower)) {
      return `https://docs.google.com/viewer?url=${encodeURIComponent(
        fileUrl
      )}&embedded=true`;
    }

    return fileUrl;
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent size="md">
        <DialogHeader>
          <DialogTitle>Info Lainnya</DialogTitle>
        </DialogHeader>
        <div className="grid grid-cols-2 gap-4 text-sm">
          <div className="font-medium">Tanggal</div>
          <div>:{data?.date}</div>

          <div className="font-medium">Lokasi Kejadian</div>
          <div>:{data?.location}</div>

          <div className="font-medium">Isu Menonjol</div>
          <div>:{data?.title}</div>

          <div className="font-medium">Urgensi</div>
          <div>:{data?.urgencyName}</div>

          <div className="font-medium">Rekomendasi Tindak Lanjut</div>
          <div>:{data?.recommendationName}</div>

          <div className="font-medium">Link Pendukung</div>
          <div className="flex">
            :
            <a
              href={data?.link}
              className="text-blue-600 flex w-[100px]"
              target="_blank"
              rel="noopener noreferrer"
            >
              {data?.link}
            </a>
          </div>

          {files.length > 0 && (
            <>
              <div className="font-medium col-span-2">Lampiran</div>
              <div className="col-span-2 flex flex-col items-center space-y-2 w-full">
                {isImage(currentFile?.fileUrl || "") ? (
                  <img
                    src={currentFile?.fileUrl}
                    alt={`Lampiran ${currentIndex + 1}`}
                    className="max-h-[300px] w-auto object-contain border rounded"
                  />
                ) : (
                  // <iframe
                  //   src={getIframeUrl(currentFile?.fileUrl || "")}
                  //   title={`Lampiran ${currentIndex + 1}`}
                  //   className="w-full max-w-2xl h-[300px] border rounded"
                  //   onError={(e) => {
                  //     (e.target as HTMLIFrameElement).style.display = "none";
                  //   }}
                  // />
                  <iframe
                    src={getIframeUrl(currentFile?.fileUrl || "")}
                    title={`Lampiran ${currentIndex + 1}`}
                    className="w-full max-w-2xl h-[500px] rounded overflow-hidden"
                    scrolling="no"
                    onError={(e) => {
                      (e.target as HTMLIFrameElement).style.display = "none";
                    }}
                  />
                )}

                <div className="flex gap-2">
                  <button
                    onClick={handlePrev}
                    disabled={currentIndex === 0}
                    className="px-2 py-1 border rounded disabled:opacity-50"
                  >
                    &lt;
                  </button>
                  <button
                    onClick={handleNext}
                    disabled={currentIndex === files.length - 1}
                    className="px-2 py-1 border rounded disabled:opacity-50"
                  >
                    &gt;
                  </button>
                </div>
              </div>
            </>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}
