'use client';

import React from 'react';
import { Eye, ExternalLink } from 'lucide-react';
import { Modal } from '@/components/ui/modal';
import { Button } from '@/components/ui/button';

interface DocumentPreviewModalProps {
  documentName: string;
  fileUrl: string;
  onClose: () => void;
}

export default function DocumentPreviewModal({
  documentName,
  fileUrl,
  onClose,
}: DocumentPreviewModalProps) {
  // Construct full URL if local uploads path is relative
  const fullUrl = fileUrl.startsWith('http')
    ? fileUrl
    : `${process.env.NEXT_PUBLIC_API_URL || ''}${fileUrl}`;

  const isImage = Boolean(fullUrl.match(/\.(jpg|jpeg|png|webp|gif|svg)$/i));

  return (
    <Modal
      onClose={onClose}
      title={`Document Preview: ${documentName.replace(/_/g, ' ')}`}
      icon={Eye}
    >
      <div className="p-4 space-y-3 text-left">
        {/* Document Display Canvas */}
        <div className="w-full h-[65vh] border border-border/40 rounded-xl overflow-hidden bg-muted/10 flex items-center justify-center relative">
          {isImage ? (
            /* eslint-disable-next-line @next/next/no-img-element */
            <img
              src={fullUrl}
              alt={documentName}
              className="max-h-full max-w-full object-contain p-2"
            />
          ) : (
            <iframe
              src={fullUrl}
              className="w-full h-full border-none"
              title={documentName}
            />
          )}
        </div>

        {/* Action Controls Footer */}
        <div className="flex items-center justify-between border-t border-border/10 pt-3">
          <a
            href={fullUrl}
            target="_blank"
            rel="noreferrer"
            className="inline-flex items-center gap-1.5 text-xs text-primary hover:underline font-bold cursor-pointer"
          >
            <span>Open Original File</span>
            <ExternalLink className="h-3.5 w-3.5" />
          </a>

          <Button
            variant="outline"
            size="sm"
            onClick={onClose}
            className="h-8 text-xs font-semibold rounded-lg cursor-pointer"
          >
            Close Preview
          </Button>
        </div>
      </div>
    </Modal>
  );
}