"use client";

import React, { useRef, useState } from "react";
import { MdFolder } from "react-icons/md";
import ConfirmationModal from "./ConfirmationModal";
import FileViewerModal from "./FileViewerModal";
import { getUploadFileIcon } from "../../utils/fileIcons";
import { UploadedFile, UploadProgress } from "../../hooks/useFileUpload";
import { formatDateTime } from "../../utils/dateUtils";

interface FileUploadProps {
  onFileSelect: (files: FileList | File[]) => void;
  uploadedFiles: UploadedFile[];
  uploadProgress: UploadProgress;
  isUploading: boolean;
  onRemoveFile: (fileId: string) => Promise<void>;
  onCancelUpload?: (fileName: string) => void;
  accept?: string;
  multiple?: boolean;
  maxSize?: number; // in bytes
  className?: string;
  isReadOnly?: boolean;
}

const FileUpload: React.FC<FileUploadProps> = ({
  onFileSelect,
  uploadedFiles,
  uploadProgress,
  isUploading,
  onRemoveFile,
  onCancelUpload,
  accept = "*/*",
  multiple = true,
  maxSize = 100000000, // 100MB default
  className = "",
  isReadOnly = false,
}) => {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [isDragOver, setIsDragOver] = useState(false);
  const [deletingFiles, setDeletingFiles] = useState<Set<string>>(new Set()); // Track files being deleted

  // Confirmation modal state
  const [showRemoveConfirm, setShowRemoveConfirm] = useState(false);
  const [fileToRemove, setFileToRemove] = useState<UploadedFile | null>(null);

  // File viewer modal state
  const [showFileViewer, setShowFileViewer] = useState(false);
  const [fileToView, setFileToView] = useState<UploadedFile | null>(null);

  const handleFileInputChange = (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const files = event.target.files;
    if (files && files.length > 0) {
      onFileSelect(files);
    }
    // Reset input value to allow selecting the same file again
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

  const handleDragOver = (event: React.DragEvent) => {
    event.preventDefault();
    setIsDragOver(true);
  };

  const handleDragLeave = (event: React.DragEvent) => {
    event.preventDefault();
    setIsDragOver(false);
  };

  const handleDrop = (event: React.DragEvent) => {
    event.preventDefault();
    setIsDragOver(false);

    const files = event.dataTransfer.files;
    if (files && files.length > 0) {
      onFileSelect(files);
    }
  };

  const handleClick = () => {
    fileInputRef.current?.click();
  };

  const handleRemoveFile = async (fileId: string) => {
    try {
      setDeletingFiles((prev) => new Set(prev).add(fileId));
      await onRemoveFile(fileId);
    } catch (error) {
      console.error("Error removing file:", error);
      // You might want to show an error message to the user here
    } finally {
      setDeletingFiles((prev) => {
        const newSet = new Set(prev);
        newSet.delete(fileId);
        return newSet;
      });
    }
  };

  const confirmRemoveFile = (file: UploadedFile) => {
    setFileToRemove(file);
    setShowRemoveConfirm(true);
  };

  const handleCloseRemoveModal = () => {
    setShowRemoveConfirm(false);
    setFileToRemove(null);
  };

  const handleConfirmRemove = async () => {
    if (!fileToRemove) return;

    try {
      setDeletingFiles((prev) => new Set(prev).add(fileToRemove.id));
      await onRemoveFile(fileToRemove.id);
    } catch (error) {
      console.error("Error removing file:", error);
      // You might want to show an error message to the user here
    } finally {
      setDeletingFiles((prev) => {
        const newSet = new Set(prev);
        newSet.delete(fileToRemove.id);
        return newSet;
      });
      setShowRemoveConfirm(false);
      setFileToRemove(null);
    }
  };

  const handleViewFile = (file: UploadedFile) => {
    setFileToView(file);
    setShowFileViewer(true);
  };

  const handleCloseFileViewer = () => {
    setShowFileViewer(false);
    setFileToView(null);
  };

  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return "0 Bytes";
    const k = 1024;
    const sizes = ["Bytes", "KB", "MB", "GB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
  };

  return (
    <div className={`flex flex-col h-full ${className}`}>
      {/* Upload Area */}
      {!isReadOnly && (
        <div className="flex-shrink-0 mb-4">
          <div
            className={`
              flex flex-col items-center justify-center 
              border-2 border-dashed rounded-lg p-4 text-center 
              transition-colors cursor-pointer min-h-[100px]
              ${
                isDragOver
                  ? "border-blue-500 bg-blue-50"
                  : "border-gray-300 hover:border-blue-400"
              }
              ${isUploading ? "opacity-50 cursor-not-allowed" : ""}
            `}
            onDragOver={handleDragOver}
            onDragLeave={handleDragLeave}
            onDrop={handleDrop}
            onClick={!isUploading ? handleClick : undefined}
          >
            <MdFolder className="h-8 w-8 text-gray-400 mb-2" />
            <p className="text-sm text-blue-500 font-medium">
              {isUploading ? "Uploading..." : "Upload Files"}
            </p>
            <p className="text-xs text-gray-500 mt-1">
              Drag & drop files here or click to browse
            </p>
            <p className="text-xs text-gray-400 mt-1">
              Max size: {formatFileSize(maxSize)}
            </p>
          </div>

          <input
            ref={fileInputRef}
            type="file"
            accept={accept}
            multiple={multiple}
            onChange={handleFileInputChange}
            className="hidden"
            disabled={isUploading}
          />
        </div>
      )}

      {/* Upload Progress */}
      {Object.keys(uploadProgress).length > 0 && (
        <div className="flex-shrink-0 mb-4 space-y-2">
          <h3 className="text-sm font-medium text-gray-700">Uploading...</h3>
          {Object.entries(uploadProgress).map(([fileName, progress]) => (
            <div
              key={fileName}
              className="bg-white p-3 rounded-lg shadow-sm border"
            >
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm font-medium text-gray-700 truncate">
                  {fileName}
                </span>
                {onCancelUpload && (
                  <button
                    onClick={() => onCancelUpload(fileName)}
                    className="text-red-500 hover:text-red-700 text-xs"
                  >
                    Cancel
                  </button>
                )}
              </div>
              <div className="w-full bg-gray-200 rounded-full h-2">
                <div
                  className="bg-blue-500 h-2 rounded-full transition-all duration-300"
                  style={{ width: `${progress}%` }}
                />
              </div>
              <div className="text-xs text-gray-500 mt-1">{progress}%</div>
            </div>
          ))}
        </div>
      )}

      {/* Uploaded Files List */}
      <div className="h-auto lg:h-[calc(60vh-200px)] overflow-visible lg:overflow-y-auto space-y-2 no-scrollbar">
        {uploadedFiles.length === 0 &&
        Object.keys(uploadProgress).length === 0 ? (
          <div className="text-center text-gray-500 py-4">
            <p className="text-sm">No files uploaded yet</p>
          </div>
        ) : (
          uploadedFiles.map((file) => (
            <div
              key={file.id}
              className="flex items-center justify-between p-3 bg-white rounded-lg shadow-sm border"
            >
              <div className="flex items-center flex-grow min-w-0">
                {getUploadFileIcon(file.type)}
                <div className="ml-3 flex-grow min-w-0">
                  <h3 className="font-semibold text-xs text-gray-700 truncate">
                    {file.name}
                  </h3>
                  <p className="text-xs text-gray-500">
                    {formatDateTime(file.uploadDate)}
                    {file.size > 0 && ` • ${formatFileSize(file.size)}`}
                  </p>
                </div>
              </div>
              <div className="flex items-center space-x-2 flex-shrink-0">
                {file.webViewLink && (
                  <button
                    onClick={() => handleViewFile(file)}
                    className="text-blue-500 hover:text-blue-700 text-xs"
                  >
                    View
                  </button>
                )}
                {!isReadOnly && (
                  <button
                    onClick={() => confirmRemoveFile(file)}
                    disabled={deletingFiles.has(file.id)}
                    className={`text-xs font-semibold ${
                      deletingFiles.has(file.id)
                        ? "text-gray-400 cursor-not-allowed"
                        : "text-red-500 hover:text-red-700"
                    }`}
                  >
                    {deletingFiles.has(file.id) ? "Deleting..." : "Remove"}
                  </button>
                )}
              </div>
            </div>
          ))
        )}
      </div>

      {/* File Removal Confirmation Dialog */}
      {showRemoveConfirm && fileToRemove && (
        <ConfirmationModal
          isOpen={showRemoveConfirm}
          onClose={handleCloseRemoveModal}
          onConfirm={handleConfirmRemove}
          title="Remove File"
          description={`Are you sure you want to remove "${fileToRemove.name}"? This will permanently delete the file from Google Drive and cannot be undone.`}
          iconContainerColor="#FFE5E5"
          iconColor="#DC2626"
          confirmText="Remove"
          cancelText="Cancel"
        />
      )}

      {/* File Viewer Modal */}
      {showFileViewer && fileToView && (
        <FileViewerModal
          isOpen={showFileViewer}
          onClose={handleCloseFileViewer}
          file={{
            name: fileToView.name,
            type: fileToView.type,
            webViewLink: fileToView.webViewLink,
            webContentLink: fileToView.webContentLink,
            driveFileId: fileToView.driveFileId,
          }}
        />
      )}

      {/* Custom CSS to hide scrollbar */}
      <style jsx>{`
        .no-scrollbar::-webkit-scrollbar {
          display: none;
        }
        .no-scrollbar {
          -ms-overflow-style: none; /* IE and Edge */
          scrollbar-width: none; /* Firefox */
        }
      `}</style>
    </div>
  );
};

export default FileUpload;
