'use client';

import { Suspense, useEffect, useState, useMemo } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useSelector } from 'react-redux';
import { RootState } from '@/lib/store/store';
import IndividualProfileContent from '@/components/profile/individual-profile-content';
import BusinessProfileContent from '@/components/profile/business-profile-content';
import InvestorProfileContent from '@/components/profile/investor-profile-content';
import { getFriendDetails } from '@/lib/api/client';

const routeMap: Record<string, string> = {
  innovator: "individual",
  business: "business",
  investor: "investor",
};

function ProfileContent() {
  const params = useParams();
  const router = useRouter();
  const { currentCustomer, accessToken } = useSelector((state: RootState) => state.user);
  
  const type = params?.type as string;
  const slug = params?.slug as string;
  const mappedType = routeMap[type] || "individual";
  
  const [loading, setLoading] = useState(true);
  const [profileData, setProfileData] = useState<any>(null);
  const [userType, setUserType] = useState<string>("individual");
  const [profileFetched, setProfileFetched] = useState(false);

  // ✅ Detect if viewing own profile
  const isOwnProfile = useMemo(() => {
    if (!currentCustomer || !slug) return false;
    const currentUserId = currentCustomer?.customer?._id || currentCustomer?._id;
    return currentUserId === slug;
  }, [currentCustomer, slug]);

  useEffect(() => {
    if (!accessToken && !currentCustomer) {
      router.push('/login');
      return;
    }

    const fetchProfile = async () => {
      if (!accessToken || !slug) {
        setLoading(false);
        return;
      }

      try {
        setLoading(true);

        let customerData = null;
        let actualUserType = "individual";

        // ✅ If viewing own profile, use Redux data directly (NO API CALL)
        if (isOwnProfile && currentCustomer) {
          customerData = currentCustomer?.customer || currentCustomer;
          console.log("📦 Using cached profile data (own profile)");
          
          // Determine user type from Redux
          if (customerData?.isBusinessUser) {
            actualUserType = "business";
          } else if (customerData?.isInvestor) {
            actualUserType = "investor";
          }
          
          setProfileData({ customer: customerData });
          setUserType(actualUserType);
          setProfileFetched(true);
          setLoading(false);
          return;
        }

        // ✅ For other profiles, fetch from API (but cache if needed)
        const response = await getFriendDetails(accessToken, slug, process.env.NEXT_PUBLIC_SECURITY_KEY);
        
        if (response.success && response.data) {
          setProfileData(response.data);
          const customer = response.data.customer || response.data;

          // Determine user type
          if (customer?.isBusinessUser) {
            actualUserType = "business";
          } else if (customer?.isInvestor) {
            actualUserType = "investor";
          }

          setUserType(actualUserType);
          setProfileFetched(true);
          
          // ✅ URL validation - redirect only if needed
          const expectedUrlType = actualUserType === "individual" ? "innovator" : actualUserType;
          if (type !== expectedUrlType) {
            router.replace(`/profile/${expectedUrlType}/${slug}`);
            return;
          }
        } else {
          console.error("Profile not found");
        }
      } catch (error) {
        console.error("Error fetching profile:", error);
      } finally {
        setLoading(false);
      }
    };

    // ✅ Only fetch if not already fetched or if slug changed
    if (!profileFetched) {
      fetchProfile();
    } else {
      setLoading(false);
    }
  }, [accessToken, slug, type, router, currentCustomer, isOwnProfile, profileFetched]);

  // Show loading only while fetching
  if (loading) {
    return (
      <div className="min-h-screen flex justify-center items-center bg-background">
        <div className="animate-pulse space-y-4 w-full max-w-5xl mx-auto p-4">
          <div className="bg-muted h-40 rounded-2xl"></div>
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
            <div className="lg:col-span-2">
              <div className="bg-muted h-96 rounded-xl"></div>
            </div>
            <div className="lg:col-span-1">
              <div className="bg-muted h-64 rounded-xl mb-4"></div>
              <div className="bg-muted h-48 rounded-xl"></div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ✅ Pre-load the components to avoid blank screen
  const Components = {
    business: BusinessProfileContent,
    investor: InvestorProfileContent,
    individual: IndividualProfileContent,
  };

  const SelectedComponent = Components[mappedType as keyof typeof Components] || IndividualProfileContent;

  return <SelectedComponent />;
}

export default function DynamicProfilePage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen flex justify-center items-center bg-background">
        <div className="animate-pulse">
          <div className="bg-muted h-8 w-32 rounded mb-4 mx-auto"></div>
          <div className="bg-muted h-40 w-80 rounded"></div>
        </div>
      </div>
    }>
      <ProfileContent />
    </Suspense>
  );
}