"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/lib/auth-context";
import UploadArea from "@/components/UploadArea";

export default function UploadPage() {
  const { isAuthenticated, user } = useAuth();
  const router = useRouter();
  const [userSubscription, setUserSubscription] = useState<any>(null);
  const [authInitialized, setAuthInitialized] = useState(false);
  const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
  const [uploading, setUploading] = useState(false);
  const [uploadMessage, setUploadMessage] = useState<string | null>(null);

  function handleFilesSelected(newFiles: File[]) {
    setSelectedFiles((prev) => {
      const merged = [...prev];
      for (const file of newFiles) {
        if (
          !merged.some(
            (f) =>
              f.name === file.name &&
              f.size === file.size &&
              f.lastModified === file.lastModified
          )
        ) {
          merged.push(file);
        }
      }
      return merged;
    });
  }

  // Wait for auth to initialize from localStorage
  useEffect(() => {
    const timer = setTimeout(() => {
      setAuthInitialized(true);
    }, 100);
    return () => clearTimeout(timer);
  }, []);

  // Check authentication and fetch subscription
  useEffect(() => {
    if (!authInitialized) return;

    if (!isAuthenticated || !user) {
      router.push("/login?redirect=/upload");
      return;
    }

    // Fetch user subscription
    const fetchSubscription = async () => {
      if (!user?.id) return;

      try {
        const response = await fetch("/api/subscriptions/me", {
          headers: {
            "user-id": user.id,
          },
        });

        if (response.ok) {
          const data = await response.json();
          setUserSubscription(data.subscription);
        }
      } catch (error) {
        console.error("Error fetching subscription:", error);
      }
    };

    fetchSubscription();
  }, [authInitialized, isAuthenticated, user, router]);

  // Show loading while auth initializes
  if (!authInitialized || !isAuthenticated) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        Loading...
      </div>
    );
  }

  // If no subscription found after loading, treat it as no subscription
  // Don't block the page from showing
  const hasActiveSubscription =
    userSubscription && userSubscription.status === "ACTIVE";

  async function handleStartUpload() {
    if (!selectedFiles.length || !hasActiveSubscription || !user) return;

    setUploading(true);
    setUploadMessage(null);
    try {
      for (const file of selectedFiles) {
        const formData = new FormData();
        formData.append("file", file);
        const res = await fetch("/api/upload", {
          method: "POST",
          headers: {
            "user-id": user.id,
          },
          body: formData,
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data?.error || "Upload failed");
      }
      setUploadMessage("Upload successful!");
      setSelectedFiles([]); // Reset picker
      // Optionally: also refresh renders dashboard, etc
    } catch (err: any) {
      setUploadMessage(err.message || "Upload failed");
    } finally {
      setUploading(false);
    }
  }

  return (
    <div className="min-h-screen bg-gray-50 py-12">
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-4xl font-bold text-gray-900 mb-2">
            Upload Files
          </h1>
          {/* <p className="text-gray-600">
            Upload your .blend files to start rendering
          </p> */}
        </div>

        {/* Subscription Warning */}
        {!hasActiveSubscription && (
          <div className="bg-red-50 border-2 border-red-500 rounded-lg p-6 mb-8">
            <p className="text-red-800 font-semibold text-lg">
              Subscribe to use our services
            </p>
            <p className="text-red-700 text-sm mt-2">
              You need an active subscription to upload files. Subscribe to a
              plan to continue.
            </p>
            <button
              onClick={() => router.push("/")}
              className="mt-4 bg-red-600 hover:bg-red-700 text-white px-6 py-2 rounded-md text-sm font-medium"
            >
              Browse Plans
            </button>
          </div>
        )}

        {/* Upload Area */}
        <div className="bg-white rounded-lg shadow-lg p-8">
          <h2 className="text-2xl font-bold text-gray-900 mb-6">
            Start by uploading at least one .blend file
          </h2>
          <div
            className={
              !hasActiveSubscription ? "pointer-events-none opacity-50" : ""
            }
          >
            <UploadArea
              className="w-full shadow-sm"
              onFilesSelected={handleFilesSelected}
            />
          </div>

          {/* Selected files indicator */}
          {selectedFiles.length > 0 && (
            <div className="mt-6 border rounded-md p-4 bg-gray-50">
              <div className="font-semibold text-gray-800 mb-2">
                Selected files ({selectedFiles.length}):
              </div>
              <ul className="list-disc list-inside text-sm text-gray-700 space-y-1 max-h-40 overflow-auto">
                {selectedFiles.map((f, idx) => (
                  <li key={idx}>
                    {f.name}{" "}
                    <span className="text-gray-500">
                      ({(f.size / 1024).toFixed(1)} KB)
                    </span>
                  </li>
                ))}
              </ul>
            </div>
          )}

          <button
            className="mt-8 px-8 py-3 rounded-md font-bold bg-orange-500 text-white hover:bg-orange-600 disabled:bg-gray-300 disabled:text-gray-500"
            disabled={
              !hasActiveSubscription || uploading || !selectedFiles.length
            }
            onClick={handleStartUpload}
          >
            {uploading ? "Uploading..." : "Start"}
          </button>
          {uploadMessage && (
            <div className="mt-4 text-center text-green-600">
              {uploadMessage}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
