"use client";

import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/lib/auth-context";
import { useState } from "react";
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);

  // 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";

  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>
        )}

        {/* Subscription Info - Only show if active */}
        {hasActiveSubscription && userSubscription && (
          <div className="bg-white rounded-lg shadow-md p-6 mb-8">
            <h2 className="text-lg font-semibold text-gray-900 mb-2">
              Your {userSubscription.tier} Plan
            </h2>
            <p className="text-sm text-gray-600">
              Storage:{" "}
              {parseFloat(userSubscription.current_usage_gb).toFixed(2)} GB /{" "}
              {userSubscription.storage_limit_gb} GB used
            </p>
            <div className="mt-3 w-full bg-gray-200 rounded-full h-2">
              <div
                className="bg-orange-500 h-2 rounded-full"
                style={{
                  width: `${Math.min(
                    (parseFloat(userSubscription.current_usage_gb) /
                      userSubscription.storage_limit_gb) *
                      100,
                    100
                  )}%`,
                }}
              ></div>
            </div>
          </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" />
          </div>
        </div>
      </div>
    </div>
  );
}
