"use client";

import * as React from "react";
import { X, Download, File, Image, FileText, Eye } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";

export interface FileAttachmentsProps {
  files: string[];
  onRemove?: (fileUrl: string) => void;
  showRemove?: boolean;
  className?: string;
  compact?: boolean;
}

const FileAttachments = React.forwardRef<HTMLDivElement, FileAttachmentsProps>(
  ({ files, onRemove, showRemove = false, className, compact = false }, ref) => {
    if (!files || files.length === 0) {
      return null;
    }

    const getFileIcon = (url: string) => {
      const fileName = getFileName(url);
      const extension = fileName.split('.').pop()?.toLowerCase();
      
      if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg'].includes(extension || '')) {
        return <Image className="h-4 w-4 text-blue-500" />;
      } else if (extension === 'pdf') {
        return <FileText className="h-4 w-4 text-red-500" />;
      } else if (['doc', 'docx'].includes(extension || '')) {
        return <FileText className="h-4 w-4 text-blue-600" />;
      } else if (['txt', 'md'].includes(extension || '')) {
        return <File className="h-4 w-4 text-gray-500" />;
      }
      return <File className="h-4 w-4 text-gray-500" />;
    };

    const getFileName = (url: string) => {
      return url.split('/').pop() || 'Unknown file';
    };

    const getFileSize = (url: string) => {
      // Mock file size - in real implementation, this would come from your API
      return "1.2 MB";
    };

    const handleDownload = async (url: string) => {
      try {
        // Try to fetch the file first (handles CORS better)
        const response = await fetch(url);
        if (!response.ok) {
          throw new Error('Failed to fetch file');
        }
        
        const blob = await response.blob();
        const downloadUrl = window.URL.createObjectURL(blob);
        
        // Create a temporary link to trigger download
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = getFileName(url);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        // Clean up the object URL
        window.URL.revokeObjectURL(downloadUrl);
      } catch (error) {
        console.error('Download failed:', error);
        // Fallback to direct link method
        try {
          const link = document.createElement('a');
          link.href = url;
          link.download = getFileName(url);
          link.target = '_blank';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        } catch (fallbackError) {
          console.error('Fallback download also failed:', fallbackError);
          // Last resort: open in new tab
          window.open(url, '_blank');
        }
      }
    };

    const isImage = (url: string) => {
      const fileName = getFileName(url);
      const extension = fileName.split('.').pop()?.toLowerCase();
      return ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg'].includes(extension || '');
    };

    if (compact) {
      return (
        <div ref={ref} className={cn("space-y-1", className)}>
          {files.map((file, index) => (
            <div
              key={index}
              className="flex items-center gap-2 p-2 bg-gray-50 rounded-lg border text-xs"
            >
              <div className="flex-shrink-0">
                {getFileIcon(file)}
              </div>
              
              <div className="flex-1 min-w-0">
                <p className="text-xs font-medium text-gray-900 truncate">
                  {getFileName(file)}
                </p>
              </div>

              <div className="flex items-center gap-1">
                {isImage(file) && (
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => window.open(file, '_blank')}
                    className="h-6 w-6 p-0"
                    title="Preview"
                  >
                    <Eye className="h-3 w-3" />
                  </Button>
                )}
                
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  onClick={() => handleDownload(file)}
                  className="h-6 w-6 p-0"
                  title="Download"
                >
                  <Download className="h-3 w-3" />
                </Button>

                {showRemove && onRemove && (
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => onRemove(file)}
                    className="h-6 w-6 p-0 hover:bg-destructive hover:text-destructive-foreground"
                    title="Remove"
                  >
                    <X className="h-3 w-3" />
                  </Button>
                )}
              </div>
            </div>
          ))}
        </div>
      );
    }

    return (
      <div ref={ref} className={cn("space-y-2", className)}>
        {files.map((file, index) => (
          <div
            key={index}
            className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg border"
          >
            <div className="flex-shrink-0">
              {getFileIcon(file)}
            </div>
            
            <div className="flex-1 min-w-0">
              <p className="text-sm font-medium text-gray-900 truncate">
                {getFileName(file)}
              </p>
              <p className="text-xs text-gray-500">
                {getFileSize(file)}
              </p>
            </div>

            <div className="flex items-center gap-1">
              {isImage(file) && (
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  onClick={() => window.open(file, '_blank')}
                  className="h-8 w-8 p-0"
                  title="Preview"
                >
                  <Eye className="h-4 w-4" />
                </Button>
              )}
              
              <Button
                type="button"
                variant="ghost"
                size="sm"
                onClick={() => handleDownload(file)}
                className="h-8 w-8 p-0"
                title="Download"
              >
                <Download className="h-4 w-4" />
              </Button>

              {showRemove && onRemove && (
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  onClick={() => onRemove(file)}
                  className="h-8 w-8 p-0 hover:bg-destructive hover:text-destructive-foreground"
                  title="Remove"
                >
                  <X className="h-4 w-4" />
                </Button>
              )}
            </div>
          </div>
        ))}
      </div>
    );
  }
);

FileAttachments.displayName = "FileAttachments";

export { FileAttachments }; 