// frontend/src/pages/Upload.tsx
import { useState } from "react";
import { useNavigate } from "react-router-dom";

interface UploadedFile {
  url: string;
  filename: string;
  size: number;
  uploaded_at: string;
}

function Upload() {
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [uploadedFiles, setUploadedFiles] = useState<UploadedFile[]>([]);
  const [isUploading, setIsUploading] = useState(false);
  const [dragActive, setDragActive] = useState(false);
  const navigate = useNavigate();

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      setSelectedFile(e.target.files[0]);
    }
  };

  const handleDrag = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === "dragenter" || e.type === "dragover") {
      setDragActive(true);
    } else if (e.type === "dragleave") {
      setDragActive(false);
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);

    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      setSelectedFile(e.dataTransfer.files[0]);
    }
  };

  const handleUpload = async () => {
    if (!selectedFile) {
      alert("Please select a file first");
      return;
    }

    setIsUploading(true);
    const token = localStorage.getItem("auth_token");
    const formData = new FormData();
    formData.append("file", selectedFile);

    try {
      const response = await fetch("/api/v1/upload", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${token}`,
        },
        body: formData,
      });

      if (response.ok) {
        const data = await response.json();
        const newFile: UploadedFile = {
          url: data.data?.url || data.url,
          filename: selectedFile.name,
          size: selectedFile.size,
          uploaded_at: new Date().toISOString(),
        };
        setUploadedFiles([newFile, ...uploadedFiles]);
        setSelectedFile(null);
        alert("File uploaded successfully!");
      } else {
        const error = await response.text();
        alert("Upload failed: " + error);
      }
    } catch (error) {
      console.error("Upload error:", error);
      alert("Network error");
    } finally {
      setIsUploading(false);
    }
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    alert("Copied to clipboard!");
  };

  const formatFileSize = (bytes: number) => {
    if (bytes < 1024) return bytes + " B";
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + " KB";
    return (bytes / (1024 * 1024)).toFixed(2) + " MB";
  };

  return (
    <div className="min-h-screen bg-black text-white font-['Commit_Mono',monospace]">
      <div className="max-w-[1400px] mx-auto px-2 sm:px-4">
        {/* Header */}
        <div className="pt-6 pb-4 border-b border-gray-800">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-xl sm:text-2xl font-bold text-[hsl(270,73%,63%)]">
                File Upload
              </h1>
              <p className="text-gray-500 text-xs sm:text-sm mt-1">
                Upload images and files
              </p>
            </div>
            <div className="flex gap-2 sm:gap-3">
              <button
                onClick={() => navigate("/admin")}
                className="px-3 py-1.5 sm:px-4 sm:py-2 border border-gray-700 rounded hover:border-[hsl(270,73%,63%)] transition-colors text-xs sm:text-sm"
              >
                Editor
              </button>
              <button
                onClick={() => {
                  localStorage.removeItem("auth_token");
                  navigate("/");
                }}
                className="px-3 py-1.5 sm:px-4 sm:py-2 border border-gray-700 rounded hover:border-red-500 hover:text-red-500 transition-colors text-xs sm:text-sm"
              >
                Logout
              </button>
            </div>
          </div>
        </div>

        <div className="mt-6 grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Upload Section */}
          <div>
            <h2 className="text-lg font-semibold mb-4">Upload New File</h2>
            <div
              className={`border-2 border-dashed rounded-lg p-8 text-center transition-all ${
                dragActive
                  ? "border-[hsl(270,73%,63%)] bg-[hsl(270,73%,63%)]/10"
                  : "border-gray-700 hover:border-gray-600"
              }`}
              onDragEnter={handleDrag}
              onDragLeave={handleDrag}
              onDragOver={handleDrag}
              onDrop={handleDrop}
            >
              <div className="mb-4">
                <svg
                  className="mx-auto h-12 w-12 text-gray-600"
                  stroke="currentColor"
                  fill="none"
                  viewBox="0 0 48 48"
                >
                  <path
                    d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  />
                </svg>
              </div>

              <div className="mb-4">
                {selectedFile ? (
                  <div className="text-sm">
                    <p className="font-medium text-[hsl(270,73%,63%)]">
                      {selectedFile.name}
                    </p>
                    <p className="text-gray-500 mt-1">
                      {formatFileSize(selectedFile.size)}
                    </p>
                  </div>
                ) : (
                  <>
                    <p className="text-sm text-gray-400 mb-2">
                      Drag and drop a file here, or click to select
                    </p>
                    <p className="text-xs text-gray-600">
                      Supported: Images, Documents, Archives
                    </p>
                  </>
                )}
              </div>

              <input
                type="file"
                onChange={handleFileSelect}
                className="hidden"
                id="file-input"
              />
              <label
                htmlFor="file-input"
                className="inline-block px-4 py-2 border border-gray-700 rounded hover:border-gray-600 transition-colors cursor-pointer text-sm"
              >
                Select File
              </label>
            </div>

            {selectedFile && (
              <div className="mt-4 flex gap-3">
                <button
                  onClick={handleUpload}
                  disabled={isUploading}
                  className="flex-1 px-6 py-3 bg-[hsl(270,73%,63%)] text-white rounded hover:bg-[hsl(270,73%,70%)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed font-medium"
                >
                  {isUploading ? "Uploading..." : "Upload File"}
                </button>
                <button
                  onClick={() => setSelectedFile(null)}
                  className="px-4 py-3 border border-gray-700 rounded hover:border-gray-600 transition-colors"
                >
                  Clear
                </button>
              </div>
            )}
          </div>

          {/* Uploaded Files Section */}
          <div>
            <h2 className="text-lg font-semibold mb-4">
              Uploaded Files ({uploadedFiles.length})
            </h2>
            <div className="space-y-3 max-h-[600px] overflow-y-auto custom-scrollbar">
              {uploadedFiles.length === 0 ? (
                <div className="text-center py-12 text-gray-600">
                  <p>No files uploaded yet</p>
                  <p className="text-sm mt-2">Upload files to see them here</p>
                </div>
              ) : (
                uploadedFiles.map((file, index) => (
                  <div
                    key={index}
                    className="border border-gray-800 rounded-lg p-4 hover:border-gray-700 transition-colors"
                  >
                    <div className="flex items-start justify-between mb-2">
                      <div className="flex-1 min-w-0">
                        <p className="font-medium text-sm truncate">
                          {file.filename}
                        </p>
                        <p className="text-xs text-gray-500 mt-1">
                          {formatFileSize(file.size)} •{" "}
                          {new Date(file.uploaded_at).toLocaleDateString()}
                        </p>
                      </div>
                    </div>

                    {/* Preview if image */}
                    {file.filename.match(/\.(jpg|jpeg|png|gif|webp)$/i) && (
                      <img
                        src={file.url}
                        alt={file.filename}
                        className="w-full h-32 object-cover rounded mt-3 mb-3 border border-gray-800"
                      />
                    )}

                    <div className="space-y-2">
                      {/* URL */}
                      <div className="flex items-center gap-2">
                        <input
                          type="text"
                          value={file.url}
                          readOnly
                          className="flex-1 bg-gray-900 border border-gray-800 rounded px-3 py-2 text-xs font-mono"
                        />
                        <button
                          onClick={() => copyToClipboard(file.url)}
                          className="px-3 py-2 border border-gray-700 rounded hover:border-gray-600 transition-colors text-xs"
                        >
                          Copy
                        </button>
                      </div>

                      {/* Markdown */}
                      {file.filename.match(/\.(jpg|jpeg|png|gif|webp)$/i) && (
                        <div className="flex items-center gap-2">
                          <input
                            type="text"
                            value={`![${file.filename}](${file.url})`}
                            readOnly
                            className="flex-1 bg-gray-900 border border-gray-800 rounded px-3 py-2 text-xs font-mono"
                          />
                          <button
                            onClick={() =>
                              copyToClipboard(
                                `![${file.filename}](${file.url})`,
                              )
                            }
                            className="px-3 py-2 border border-gray-700 rounded hover:border-gray-600 transition-colors text-xs"
                          >
                            MD
                          </button>
                        </div>
                      )}
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>
        </div>
      </div>

      <style>{`
        .custom-scrollbar::-webkit-scrollbar {
          width: 6px;
        }
        .custom-scrollbar::-webkit-scrollbar-track {
          background: #111;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb {
          background: #333;
          border-radius: 4px;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover {
          background: #444;
        }
      `}</style>
    </div>
  );
}

export default Upload;
