'use client';
import React, { useState, useEffect, useCallback } from 'react';
import {
  Dialog,
  DialogTrigger,
  DialogContent,
  DialogTitle,
  DialogDescription,
  DialogHeader,
} from '@/components/ui/dialog';
import CommonImage from '@/components/common/CommonImage';
import { Text } from '@/components/ui/text';
import * as XLSX from 'xlsx';
import * as mammoth from 'mammoth';

type FileLike = File | { file_url: string; name?: string; type?: string };

type CommonViewMediaDialogProps = {
  files: FileLike[];
  initialIndex?: number;
};

const CommonViewMediaDialog: React.FC<CommonViewMediaDialogProps> = ({
  files,
  initialIndex = 0,
}) => {
  const [currentIndex, setCurrentIndex] = useState(initialIndex);
  const [open, setOpen] = useState(false);
  const [excelData, setExcelData] = useState<string[][] | null>(null);
  const [wordHtml, setWordHtml] = useState<string | null>(null);

  const currentFile = files[currentIndex];

  /** ---------- Helpers ---------- **/
  const getFileUrl = (file?: FileLike) =>
    !file
      ? ''
      : file instanceof File
        ? URL.createObjectURL(file)
        : file.file_url;

  const getFileName = (file?: FileLike) =>
    !file ? '' : file instanceof File ? file.name : file.name || file.file_url;

  const getExtension = useCallback((file?: FileLike): string => {
    if (!file) return '';
    const match = getFileName(file)
      .toLowerCase()
      .match(/\.(\w+)(?:\?|#|$)/);
    return match ? match[1] : '';
  }, []);

  const isImageFile = (file?: FileLike) =>
    file instanceof File
      ? file.type.startsWith('image/')
      : /\.(jpe?g|png|gif|webp)$/i.test(getFileName(file));

  const isPdfFile = (file?: FileLike) =>
    file instanceof File
      ? file.type === 'application/pdf'
      : getExtension(file) === 'pdf';

  /** ---------- Navigation ---------- **/
  const handlePrev = () =>
    setCurrentIndex((prev) => (prev - 1 + files.length) % files.length);

  const handleNext = () => setCurrentIndex((prev) => (prev + 1) % files.length);

  /** ---------- Preview Local Files ---------- **/
  /** ---------- Preview Local + Remote Files ---------- **/
  const previewFile = useCallback(
    async (file: FileLike) => {
      setExcelData(null);
      setWordHtml(null);

      const ext = getExtension(file);

      try {
        // Local file
        if (file instanceof File) {
          if (['xls', 'xlsx', 'csv'].includes(ext)) {
            const data = await file.arrayBuffer();
            const workbook = XLSX.read(data);
            const sheet = workbook.Sheets[workbook.SheetNames[0]];
            const json = XLSX.utils.sheet_to_json(sheet, {
              header: 1,
            }) as string[][];
            setExcelData(json);
          } else if (ext === 'docx') {
            const arrayBuffer = await file.arrayBuffer();
            const result = await mammoth.convertToHtml({ arrayBuffer });
            setWordHtml(result.value);
          }
        }
        // Remote file (URL)
        else if (file.file_url) {
          if (['xls', 'xlsx', 'csv'].includes(ext)) {
            const res = await fetch(file.file_url, {
              method: 'GET',
              credentials: 'include', // ✅ important
            });
            const data = await res.arrayBuffer();
            const workbook = XLSX.read(data);
            const sheet = workbook.Sheets[workbook.SheetNames[0]];
            const json = XLSX.utils.sheet_to_json(sheet, {
              header: 1,
            }) as string[][];
            setExcelData(json);
          } else if (ext === 'docx') {
            const res = await fetch(file.file_url, {
              method: 'GET',
              credentials: 'include', // ✅ important
            });
            const arrayBuffer = await res.arrayBuffer();
            const result = await mammoth.convertToHtml({ arrayBuffer });
            setWordHtml(result.value);
          }
        }
      } catch (err) {
        console.error('File preview error:', err);
      }
    },
    [getExtension],
  );

  useEffect(() => {
    if (currentFile) previewFile(currentFile);

    // If it's a local File, create an object URL and revoke it on cleanup
    let objectUrl: string | null = null;
    if (currentFile instanceof File) {
      objectUrl = URL.createObjectURL(currentFile);
    }

    return () => {
      if (objectUrl) URL.revokeObjectURL(objectUrl);
    };
  }, [currentFile, previewFile]);

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <button
          className="attach-view"
          onClick={(e) => {
            e.stopPropagation();
            setOpen(true);
            setCurrentIndex(initialIndex);
          }}
          title="View Modal"
        >
          <CommonImage
            src="/main/zoom-in.webp"
            width={18}
            height={18}
            alt="Zoom-in"
            classname="zoom-icon"
          />
        </button>
      </DialogTrigger>

      <DialogContent className="z-50 w-full max-w-7xl p-0 m-0 view-dialog-media modal-common-widget g-0">
        <DialogHeader>
          <DialogTitle className="p-5 modal-header">View Media</DialogTitle>
          <DialogDescription>{''}</DialogDescription>
        </DialogHeader>

        <Text className="overflow-y-auto DialogMiddle flex flex-col items-center justify-center relative w-full">
          <div className="media-img-cont flex items-center justify-center relative w-full h-[80vh] overflow-auto">
            {currentFile ? (
              isImageFile(currentFile) ? (
                <CommonImage
                  src={getFileUrl(currentFile)}
                  width={600}
                  height={600}
                  alt="media"
                  classname="view-media rounded-lg shadow-md"
                />
              ) : isPdfFile(currentFile) ? (
                <iframe
                  src={getFileUrl(currentFile)}
                  className="w-full h-full rounded-lg shadow-md"
                  title="PDF Preview"
                />
              ) : excelData ? (
                <table className="table-auto border-collapse border border-gray-300">
                  <tbody>
                    {excelData.map((row, i) => (
                      <tr key={i}>
                        {row.map((cell, j) => (
                          <td
                            key={j}
                            className="border px-2 py-1 text-sm whitespace-nowrap"
                          >
                            {cell}
                          </td>
                        ))}
                      </tr>
                    ))}
                  </tbody>
                </table>
              ) : wordHtml ? (
                <div
                  className="p-4 border rounded bg-gray-100 w-full h-full overflow-auto text-sm"
                  dangerouslySetInnerHTML={{ __html: wordHtml }}
                />
              ) : currentFile instanceof File ? (
                <div className="p-4 border rounded bg-gray-100 text-center">
                  <p> {getFileName(currentFile)}</p>
                  <p className="text-sm text-gray-500">
                    Preview not available for this file
                  </p>
                </div>
              ) : (
                <iframe
                  src={`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(
                    getFileUrl(currentFile),
                  )}`}
                  className="w-full h-full rounded-lg shadow-md"
                  title="Office Preview"
                />
              )
            ) : (
              <p className="text-gray-500">No file available</p>
            )}
          </div>

          {/* Navigation */}
          {files.length > 1 && (
            <div className="absolute flex items-center justify-between px-4 controller-slider-widget">
              <button
                onClick={handlePrev}
                className="p-2 bg-gray-700/50 rounded-full hover:bg-gray-700 transition"
              >
                <CommonImage
                  src="/main/right_arrow_icon.webp"
                  width={7}
                  height={7}
                  alt="left arrow"
                  classname="left-arrow"
                />
              </button>
              <button
                onClick={handleNext}
                className="p-2 bg-gray-700/50 rounded-full hover:bg-gray-700 transition"
              >
                <CommonImage
                  src="/main/right_arrow_icon.webp"
                  width={7}
                  height={7}
                  alt="right arrow"
                  classname="right-arrow"
                />
              </button>
            </div>
          )}
        </Text>
      </DialogContent>
    </Dialog>
  );
};

export default CommonViewMediaDialog;
