"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useSelector } from "react-redux";
import { motion } from "framer-motion";
import {
  User,
  Mail,
  Phone,
  Building2,
  Shield,
  CheckCircle,
  XCircle,
  ArrowLeft,
  MapPin,
  Camera,
  FileText,
  Banknote,
  Briefcase,
  Target,
  Edit,
  ExternalLink,
  Clock,
  AlertCircle,
  Plus,
  UserCircle,
  Check,
} from "lucide-react";
import Link from "next/link";
import Image from "next/image";
import Header from "../components/Header";
import Footer from "../components/Footer";
import Drawer from "../components/Drawer";
import BankDetailsForm from "../components/forms/BankDetailsForm";
import ShopRegistrationForm from "../components/forms/ShopRegistrationForm";
import { selectCurrentUser, selectIsAuthenticated } from "@/redux/slices/authSlice";
import { useGetProfileQuery, useUpdateProfileMutation } from "@/redux/apis/authApi";
import { useGetBankDetailsQuery } from "@/redux/apis/bankApi";
import { useGetShopRegistrationQuery } from "@/redux/apis/shopApi";
import type { UserProfile } from "@/redux/apis/authApi";

import { useGetMyPlansQuery } from "@/redux/apis/planApi";

function MembershipWidget() {
  const { data: myPlansData, isLoading } = useGetMyPlansQuery();
  const latestPlan = myPlansData?.data?.[0]; // Get the first plan (most recent)

  if (isLoading) {
    return <div className="p-6 rounded-2xl bg-theme-input border border-primary-500/20 animate-pulse h-64"></div>;
  }

  const hasActivePlan = !!latestPlan;

  return (
    <div className="grid md:grid-cols-2 gap-6">
      <div className="p-6 rounded-2xl bg-theme-input border border-primary-500/20 relative overflow-hidden group">
        <div className="relative z-10">
          <div className="flex items-center justify-between mb-4">
            <div>
              <p className="text-xs text-theme-muted mb-1">Current Status</p>
              <div className="flex items-center gap-2">
                <CheckCircle className={`w-5 h-5 ${hasActivePlan ? 'text-green-500' : 'text-theme-muted'}`} />
                <p className={`text-lg font-bold ${hasActivePlan ? 'text-green-500' : 'text-theme-primary'}`}>
                  {hasActivePlan ? 'Premium Member' : 'Basic User'}
                </p>
              </div>
            </div>
            <div className="p-3 bg-primary-500/10 rounded-xl">
              <UserCircle className="w-8 h-8 text-primary-500" />
            </div>
          </div>

          {hasActivePlan ? (
            <div className="space-y-4">
              <div>
                <p className="text-sm font-semibold text-theme-primary mb-1">{latestPlan.plan?.name}</p>
                <p className="text-xs text-theme-secondary line-clamp-2">{latestPlan.plan?.description}</p>
              </div>

              <div className="flex justify-between text-sm pt-2 border-t border-primary-500/10">
                <span className="text-theme-muted">Purchase Date:</span>
                <span className="text-theme-primary font-medium">{new Date(latestPlan.createdAt).toLocaleDateString()}</span>
              </div>

              <div className="flex gap-3 mt-4">
                <Link
                  href="/my-plans"
                  className="flex-1 flex items-center justify-center gap-2 py-2.5 bg-primary-500 text-white rounded-xl hover:bg-primary-600 transition-colors text-sm font-semibold"
                >
                  <FileText className="w-4 h-4" />
                  Show My All Plans
                </Link>
              </div>
            </div>
          ) : (
            <div className="space-y-4">
              <p className="text-sm text-theme-secondary">
                Upgrade to a premium plan to unlock exclusive features, access tenders, and grow your business.
              </p>
              <Link
                href="/plans"
                className="block w-full text-center py-3 bg-primary-500 text-white rounded-xl hover:bg-primary-600 transition-all font-semibold shadow-lg shadow-primary-500/20 active:scale-95"
              >
                Upgrade to Premium
              </Link>
            </div>
          )}
        </div>
        {/* Subtle Background Pattern */}
        <div className="absolute top-0 right-0 -mr-8 -mt-8 w-32 h-32 bg-primary-500/5 rounded-full blur-2xl" />
      </div>

      <div className="p-6 rounded-2xl bg-theme-section-alt border border-primary-500/10 flex flex-col justify-between">
        <div>
          <h3 className="text-sm font-semibold text-theme-primary mb-4 flex items-center gap-2">
            <Briefcase className="w-4 h-4 text-primary-500" />
            My Tender Activity
          </h3>
          <p className="text-sm text-theme-secondary mb-6">
            View and manage all your submitted tender applications and track their progress in real-time.
          </p>
        </div>
        <Link
          href="/tender-applieds"
          className="flex items-center justify-center gap-2 py-3 bg-white border border-primary-500/20 text-primary-600 rounded-xl hover:bg-primary-50 transition-all text-sm font-bold shadow-sm"
        >
          <CheckCircle className="w-4 h-4" />
          View Applied Tenders
        </Link>
      </div>
    </div>
  );
}

export default function ProfilePage() {
  const router = useRouter();
  const [mounted, setMounted] = useState(false);
  const [openDrawer, setOpenDrawer] = useState<string | null>(null);
  const minimalUser = useSelector(selectCurrentUser);
  const isAuthenticated = useSelector(selectIsAuthenticated);

  // Fetch full profile data using getProfile query
  const { data: profileData, isLoading: isLoadingProfile, error: profileError, refetch: refetchProfile } = useGetProfileQuery(undefined, {
    skip: !isAuthenticated || !mounted, // Skip if not authenticated or not mounted
  });

  // Fetch bank details and shop registration
  const { data: bankData } = useGetBankDetailsQuery(undefined, {
    skip: !isAuthenticated || !mounted,
  });
  const { data: shopData } = useGetShopRegistrationQuery(undefined, {
    skip: !isAuthenticated || !mounted,
  });

  const [updateProfile, { isLoading: isUpdatingProfile }] = useUpdateProfileMutation();

  // Debug: Log profile data when it changes
  useEffect(() => {
    if (profileData?.data) {
      console.log('📸 Profile Data:', {
        name: profileData.data.name,
        email: profileData.data.email,
        profileImage: profileData.data.profileImage,
        fullData: profileData.data
      });
    }
  }, [profileData]);

  const handleProfileImageChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      const file = e.target.files[0];

      // Validate file size (max 5MB)
      if (file.size > 5 * 1024 * 1024) {
        alert("Image size should be less than 5MB");
        return;
      }

      // Validate file type
      if (!file.type.startsWith('image/')) {
        alert("Please upload an image file");
        return;
      }

      const formData = new FormData();
      formData.append("profileImage", file);

      try {
        const result = await updateProfile(formData).unwrap();
        console.log('✅ Profile image updated:', result);

        // Refetch profile to get updated image
        await refetchProfile();

        alert("Profile image updated successfully!");
      } catch (err: any) {
        console.error("❌ Failed to update profile image:", err);
        alert(err.data?.message || "Failed to update profile image");
      }
    }
  };

  const handleDrawerToggle = (drawerName: string) => {
    setOpenDrawer(openDrawer === drawerName ? null : drawerName);
  };

  // Use full profile data if available, otherwise fall back to minimal user data
  // Type the user as the full profile type from the API
  const user: UserProfile | null = profileData?.data || (minimalUser ? {
    id: minimalUser.id,
    name: minimalUser.name,
    email: minimalUser.email,
    phone: minimalUser.phone ?? null,
    username: minimalUser.username ?? null,
    role: minimalUser.role ?? undefined,
    isActive: minimalUser.isActive ?? undefined,
  } : null);

  // Prevent hydration mismatch by only checking auth after mount
  useEffect(() => {
    setMounted(true);
    window.scrollTo(0, 0);
  }, []);

  useEffect(() => {
    if (mounted && (!isAuthenticated || !minimalUser)) {
      router.push("/login");
    }
  }, [mounted, isAuthenticated, minimalUser, router]);

  // Show loading state during hydration
  if (!mounted) {
    return (
      <div className="min-h-screen flex flex-col bg-[var(--background)] transition-colors duration-300">
        <Header />
        <main className="flex-1 pt-32 pb-16 flex items-center justify-center">
          <div className="w-8 h-8 border-2 border-primary-500 border-t-transparent rounded-full animate-spin" />
        </main>
        <Footer />
      </div>
    );
  }

  if (!isAuthenticated || !minimalUser) {
    return null;
  }

  // Show loading state while fetching profile data
  if (isLoadingProfile) {
    return (
      <div className="min-h-screen flex flex-col bg-[var(--background)] transition-colors duration-300">
        <Header />
        <main className="flex-1 pt-32 pb-16 flex items-center justify-center">
          <div className="w-8 h-8 border-2 border-primary-500 border-t-transparent rounded-full animate-spin" />
        </main>
        <Footer />
      </div>
    );
  }

  // Show error state if profile fetch failed
  if (profileError && !user) {
    return (
      <div className="min-h-screen flex flex-col bg-[var(--background)] transition-colors duration-300">
        <Header />
        <main className="flex-1 pt-32 pb-16 flex items-center justify-center">
          <div className="text-center">
            <p className="text-red-500 mb-4">Failed to load profile data</p>
            <button
              onClick={() => window.location.reload()}
              className="px-4 py-2 bg-primary-500 text-white rounded-xl hover:bg-primary-600"
            >
              Retry
            </button>
          </div>
        </main>
        <Footer />
      </div>
    );
  }

  // Ensure user exists before rendering
  if (!user) {
    return null;
  }

  const serviceStatuses = [
    { name: "B2B", active: user.serviceB2B ?? user.b2bActive ?? false },
    { name: "B2C", active: user.serviceB2C ?? user.b2cActive ?? false },
    { name: "CRM", active: user.serviceCRM ?? user.crmActive ?? false },
    { name: "Finance", active: user.serviceFinance ?? user.financeActive ?? false },
    { name: "Daily Post", active: user.dailyPostActive ?? false },
    { name: "EV Charging", active: user.serviceEV ?? user.EvChargingActive ?? false },
    { name: "Tender", active: user.serviceTenders ?? user.tenderActive ?? false },
  ];

  const workingAs = [
    { key: "workingAsDistributor", label: "Distributor", value: user.workingAsDistributor },
    { key: "workingAsDealer", label: "Dealer", value: user.workingAsDealer },
    { key: "workingAsStockist", label: "Stockist", value: user.workingAsStockist },
    { key: "workingAsTrader", label: "Trader", value: user.workingAsTrader },
    { key: "workingAsEpcVendor", label: "EPC Vendor", value: user.workingAsEpcVendor },
    { key: "workingAsManpowerSupplier", label: "Manpower Supplier", value: user.workingAsManpowerSupplier },
    { key: "workingAsMachinerySupplier", label: "Machinery Supplier", value: user.workingAsMachinerySupplier },
  ].filter((item) => item.value);

  const interests = [
    { key: "interestedInB2B", label: "B2B", value: user.interestedInB2B },
    { key: "interestedInB2C", label: "B2C", value: user.interestedInB2C },
    { key: "interestedInEpc", label: "EPC", value: user.interestedInEpc },
    { key: "interestedInManpowerSupply", label: "Manpower Supply", value: user.interestedInManpowerSupply },
    { key: "interestedInMachinerySupply", label: "Machinery Supply", value: user.interestedInMachinerySupply },
    { key: "interestedInTenders", label: "Tenders", value: user.interestedInTenders },
  ].filter((item) => item.value);

  return (
    <div className="min-h-screen flex flex-col bg-[var(--background)] transition-colors duration-300">
      <Header />
      <main className="flex-1 pt-32 pb-16">
        <div className="w-full px-4 sm:px-6 lg:px-8 py-8">
          {/* Back Button */}
          <div className="mb-8 max-w-7xl mx-auto">
            <Link
              href="/"
              className="inline-flex items-center gap-2 text-theme-secondary hover:text-primary-500 transition-colors text-sm sm:text-base"
            >
              <ArrowLeft className="w-4 h-4" />
              <span className="hidden sm:inline">Back to Home</span>
              <span className="sm:hidden">Back</span>
            </Link>
          </div>

          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5 }}
            className="w-full max-w-7xl mx-auto"
          >
            {/* Header */}
            <div className="mb-12">
              <div className="grid grid-cols-12 gap-4 items-center">
                {/* Profile Icon - 4 columns */}
                <div className="col-span-4 flex justify-center">
                  <div className="relative group">
                    <div className="w-20 h-20 sm:w-24 sm:h-24 rounded-full bg-gradient-to-br from-primary-500 to-primary-600 flex items-center justify-center text-white text-3xl font-bold overflow-hidden border-4 border-theme-input shadow-xl">
                      {user.profileImage ? (
                        <Image
                          src={user.profileImage.startsWith('http') ? user.profileImage : `${process.env.NEXT_PUBLIC_API_URL || 'https://api.msbsgov.com'}${user.profileImage}`}
                          alt={user.name || 'Profile'}
                          width={96}
                          height={96}
                          className="w-full h-full object-cover"
                          onError={(e) => {
                            // Fallback to initials if image fails to load
                            const target = e.target as HTMLImageElement;
                            target.style.display = 'none';
                          }}
                          priority
                        />
                      ) : (
                        <UserCircle className="w-12 h-12 sm:w-16 sm:h-16" />
                      )}
                      {/* Fallback initials if image fails */}
                      {user.profileImage && (
                        <span className="absolute inset-0 flex items-center justify-center text-3xl font-bold opacity-0 group-hover:opacity-0">
                          {user.name?.charAt(0).toUpperCase()}
                        </span>
                      )}
                    </div>
                    <label className="absolute bottom-0 right-0 p-1.5 sm:p-2 bg-primary-500 text-white rounded-full cursor-pointer hover:bg-primary-600 transition-colors shadow-lg group-hover:scale-110 transform">
                      <Camera className="w-3 h-3 sm:w-4 sm:h-4" />
                      <input
                        type="file"
                        className="hidden"
                        accept="image/*"
                        onChange={handleProfileImageChange}
                        disabled={isUpdatingProfile}
                      />
                    </label>
                    {isUpdatingProfile && (
                      <div className="absolute inset-0 flex items-center justify-center bg-black/20 rounded-full">
                        <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
                      </div>
                    )}
                  </div>
                </div>
                {/* Name, Email, Phone and Status - 8 columns */}
                <div className="col-span-8">
                  <h1 className="text-2xl md:text-3xl font-bold text-theme-primary mb-1">
                    {user.name}
                  </h1>
                  <p className="text-sm text-theme-secondary mb-1">
                    {user.email}
                  </p>
                  {user.phone && (
                    <p className="text-sm text-theme-secondary mb-2">
                      {user.phone}
                    </p>
                  )}
                  {/* Profile Status Badges */}
                  <div className="flex flex-wrap items-center gap-2">
                    {user.isActive ? (
                      <div className="inline-flex items-center gap-2 px-3 py-1 bg-green-500/20 text-green-500 rounded-full text-xs font-medium">
                        <CheckCircle className="w-3 h-3" />
                        Active
                      </div>
                    ) : (
                      <div className="inline-flex items-center gap-2 px-3 py-1 bg-red-500/20 text-red-500 rounded-full text-xs font-medium">
                        <XCircle className="w-3 h-3" />
                        Inactive
                      </div>
                    )}

                    {user.profileCompleted && user.profileVerificationStatus && (
                      <>
                        {user.profileVerificationStatus === 'verified' && (
                          <div className="inline-flex items-center gap-2 px-3 py-1 bg-green-500/20 text-green-500 rounded-full text-xs font-medium">
                            <CheckCircle className="w-3 h-3" />
                            Verified
                          </div>
                        )}
                        {user.profileVerificationStatus === 'pending' && (
                          <div className="inline-flex items-center gap-2 px-3 py-1 bg-yellow-500/20 text-yellow-500 rounded-full text-xs font-medium">
                            <Clock className="w-3 h-3" />
                            Verification Pending
                          </div>
                        )}
                        {user.profileVerificationStatus === 'rejected' && (
                          <div className="inline-flex items-center gap-2 px-3 py-1 bg-red-500/20 text-red-500 rounded-full text-xs font-medium">
                            <XCircle className="w-3 h-3" />
                            Verification Rejected
                          </div>
                        )}
                      </>
                    )}
                  </div>
                </div>
              </div>
            </div>

            {/* Banking Details Drawer */}
            <Drawer
              title="Banking Details"
              icon={<Banknote className="w-5 h-5" />}
              isOpen={openDrawer === "bank"}
              onToggle={() => handleDrawerToggle("bank")}
              hasData={!!(bankData?.success && bankData.data)}
            >
              {bankData?.success && bankData.data ? (
                <div className="space-y-4">
                  <div className="grid md:grid-cols-2 gap-4">
                    <div className="p-4 rounded-xl bg-theme-input border border-primary-500/20">
                      <p className="text-xs text-theme-muted mb-1">Account Holder Name</p>
                      <p className="text-sm font-medium text-theme-primary">{bankData.data.accountHolderName}</p>
                    </div>
                    <div className="p-4 rounded-xl bg-theme-input border border-primary-500/20">
                      <p className="text-xs text-theme-muted mb-1">Bank Name</p>
                      <p className="text-sm font-medium text-theme-primary">{bankData.data.bankName}</p>
                    </div>
                    <div className="p-4 rounded-xl bg-theme-input border border-primary-500/20">
                      <p className="text-xs text-theme-muted mb-1">Account Number</p>
                      <p className="text-sm font-medium text-theme-primary">
                        {bankData.data.accountNumber.replace(/\d(?=\d{4})/g, "*")}
                      </p>
                    </div>
                    <div className="p-4 rounded-xl bg-theme-input border border-primary-500/20">
                      <p className="text-xs text-theme-muted mb-1">IFSC Code</p>
                      <p className="text-sm font-medium text-theme-primary">{bankData.data.ifscCode}</p>
                    </div>
                    <div className="p-4 rounded-xl bg-theme-input border border-primary-500/20">
                      <p className="text-xs text-theme-muted mb-1">City</p>
                      <p className="text-sm font-medium text-theme-primary">{bankData.data.city}</p>
                    </div>
                    <div className="p-4 rounded-xl bg-theme-input border border-primary-500/20">
                      <p className="text-xs text-theme-muted mb-1">Pin Code</p>
                      <p className="text-sm font-medium text-theme-primary">{bankData.data.pinCode || "N/A"}</p>
                    </div>
                  </div>
                  <div className="pt-4 border-t border-primary-500/20">
                    <BankDetailsForm onClose={() => setOpenDrawer(null)} />
                  </div>
                </div>
              ) : (
                <div className="space-y-4">
                  <p className="text-theme-secondary text-sm">No bank details added yet.</p>
                  <BankDetailsForm onClose={() => setOpenDrawer(null)} />
                </div>
              )}
            </Drawer>

            {/* Shop Registration Drawer */}
            <Drawer
              title="Shop Registration"
              icon={<Building2 className="w-5 h-5" />}
              isOpen={openDrawer === "shop"}
              onToggle={() => handleDrawerToggle("shop")}
              hasData={!!(shopData?.success && shopData.data)}
            >
              {shopData?.success && shopData.data ? (
                <div className="space-y-6">
                  {/* Shop Details */}
                  <div className="grid md:grid-cols-2 gap-4">
                    {shopData.data.ownerName && (
                      <div className="p-4 rounded-xl bg-theme-input border border-primary-500/20">
                        <p className="text-xs text-theme-muted mb-1">Owner Name</p>
                        <p className="text-sm font-medium text-theme-primary">{shopData.data.ownerName}</p>
                      </div>
                    )}
                    {shopData.data.shopName && (
                      <div className="p-4 rounded-xl bg-theme-input border border-primary-500/20">
                        <p className="text-xs text-theme-muted mb-1">Shop Name</p>
                        <p className="text-sm font-medium text-theme-primary">{shopData.data.shopName}</p>
                      </div>
                    )}
                    {shopData.data.emailId && (
                      <div className="p-4 rounded-xl bg-theme-input border border-primary-500/20">
                        <p className="text-xs text-theme-muted mb-1">Email</p>
                        <p className="text-sm font-medium text-theme-primary">{shopData.data.emailId}</p>
                      </div>
                    )}
                    {shopData.data.mobileNumber && (
                      <div className="p-4 rounded-xl bg-theme-input border border-primary-500/20">
                        <p className="text-xs text-theme-muted mb-1">Mobile Number</p>
                        <p className="text-sm font-medium text-theme-primary">{shopData.data.mobileNumber}</p>
                      </div>
                    )}
                    {shopData.data.city && (
                      <div className="p-4 rounded-xl bg-theme-input border border-primary-500/20">
                        <p className="text-xs text-theme-muted mb-1">City</p>
                        <p className="text-sm font-medium text-theme-primary">{shopData.data.city}</p>
                      </div>
                    )}
                    {shopData.data.pinCode && (
                      <div className="p-4 rounded-xl bg-theme-input border border-primary-500/20">
                        <p className="text-xs text-theme-muted mb-1">Pin Code</p>
                        <p className="text-sm font-medium text-theme-primary">{shopData.data.pinCode}</p>
                      </div>
                    )}
                    {profileData?.data?.farmType && (
                      <div className="p-4 rounded-xl bg-theme-input border border-primary-500/20">
                        <p className="text-xs text-theme-muted mb-1">Farm Type</p>
                        <p className="text-sm font-medium text-theme-primary">{profileData.data.farmType}</p>
                      </div>
                    )}
                    {profileData?.data?.joinAsA && (
                      <div className="p-4 rounded-xl bg-theme-input border border-primary-500/20">
                        <p className="text-xs text-theme-muted mb-1">Join As A</p>
                        <p className="text-sm font-medium text-theme-primary">{profileData.data.joinAsA}</p>
                      </div>
                    )}
                  </div>

                  {/* All Images and Documents - Compact Grid */}
                  {((shopData.data.shopPhotos && shopData.data.shopPhotos.length > 0) || shopData.data.selfiePhoto || shopData.data.shopactDocument || shopData.data.udyamAadharDocument || shopData.data.gstDocument || shopData.data.aadharCard || shopData.data.panCard) && (
                    <div className="pt-4 border-t border-primary-500/20">
                      <h3 className="text-base font-semibold text-theme-primary mb-3 flex items-center gap-2">
                        <Camera className="w-4 h-4" />
                        Images & Documents
                      </h3>
                      <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-2">
                        {/* Helper function to build image URL */}
                        {(() => {
                          const buildImageUrl = (path: string) => {
                            if (path.startsWith("http")) return path;
                            const apiUrl = process.env.NEXT_PUBLIC_API_URL || "https://api.msbsgov.com/api";
                            // If path already starts with /api/uploads, use it directly, otherwise add /api/uploads/
                            if (path.startsWith("/uploads/")) {
                              return `${apiUrl}${path}`;
                            }
                            return `${apiUrl}/uploads/${path}`;
                          };

                          const images: Array<{ url: string; label: string; type: string }> = [];

                          // Add shop photos
                          if (shopData.data.shopPhotos && shopData.data.shopPhotos.length > 0) {
                            shopData.data.shopPhotos.forEach((photo, index) => {
                              images.push({
                                url: buildImageUrl(photo),
                                label: `Shop Photo ${index + 1}`,
                                type: "shop"
                              });
                            });
                          }

                          // Add selfie photo
                          if (shopData.data.selfiePhoto) {
                            images.push({
                              url: buildImageUrl(shopData.data.selfiePhoto),
                              label: "Selfie",
                              type: "selfie"
                            });
                          }

                          // Add owner passport photo
                          if (shopData.data.ownerPassportPhoto) {
                            images.push({
                              url: buildImageUrl(shopData.data.ownerPassportPhoto),
                              label: "Passport Photo",
                              type: "passport"
                            });
                          }

                          // Add documents
                          if (shopData.data.shopactDocument) {
                            images.push({
                              url: buildImageUrl(shopData.data.shopactDocument),
                              label: "Shopact",
                              type: "document"
                            });
                          }
                          if (shopData.data.udyamAadharDocument) {
                            images.push({
                              url: buildImageUrl(shopData.data.udyamAadharDocument),
                              label: "Udyam",
                              type: "document"
                            });
                          }
                          if (shopData.data.gstDocument) {
                            images.push({
                              url: buildImageUrl(shopData.data.gstDocument),
                              label: "GST",
                              type: "document"
                            });
                          }
                          if (shopData.data.aadharCard) {
                            images.push({
                              url: buildImageUrl(shopData.data.aadharCard),
                              label: "Aadhar",
                              type: "document"
                            });
                          }
                          if (shopData.data.panCard) {
                            images.push({
                              url: buildImageUrl(shopData.data.panCard),
                              label: "PAN",
                              type: "document"
                            });
                          }

                          return images.map((image, index) => (
                            <div key={index} className="relative group">
                              <div className="aspect-square rounded-md overflow-hidden border border-primary-500/20 bg-theme-input">
                                <img
                                  src={image.url}
                                  alt={image.label}
                                  className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-300"
                                  onError={(e) => {
                                    // Fallback for PDFs or failed images - show document icon
                                    const target = e.target as HTMLImageElement;
                                    target.style.display = 'none';
                                    const parent = target.parentElement;
                                    if (parent) {
                                      parent.innerHTML = `<div class="w-full h-full flex items-center justify-center bg-theme-input"><svg class="w-6 h-6 text-primary-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path></svg></div>`;
                                    }
                                  }}
                                />
                              </div>
                              <div className="absolute bottom-0 left-0 right-0 bg-black/70 text-white text-[10px] px-1 py-0.5 rounded-b-md opacity-0 group-hover:opacity-100 transition-opacity truncate">
                                {image.label}
                              </div>
                              <a
                                href={image.url}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity rounded-md"
                                title={image.label}
                              >
                                <ExternalLink className="w-4 h-4 text-white" />
                              </a>
                            </div>
                          ));
                        })()}
                      </div>
                    </div>
                  )}

                  <div className="pt-4 border-t border-primary-500/20">
                    <ShopRegistrationForm onClose={() => setOpenDrawer(null)} />
                  </div>
                </div>
              ) : (
                <div className="space-y-4">
                  <p className="text-theme-secondary text-sm">No shop registration details added yet.</p>
                  <ShopRegistrationForm onClose={() => setOpenDrawer(null)} />
                </div>
              )}
            </Drawer>

            {/* Working Details */}
            {workingAs.length > 0 && (
              <div className="mb-12">
                <h2 className="text-2xl font-bold text-theme-primary mb-6 flex items-center gap-2">
                  <Briefcase className="w-6 h-6" />
                  Working With Company As
                </h2>
                <div className="flex flex-wrap gap-2">
                  {workingAs.map((item) => (
                    <span
                      key={item.key}
                      className="px-3 py-1 bg-primary-500/20 text-primary-500 rounded-full text-sm font-medium"
                    >
                      {item.label}
                    </span>
                  ))}
                </div>
              </div>
            )}

            {/* Interests */}
            {interests.length > 0 && (
              <div className="mb-12">
                <h2 className="text-2xl font-bold text-theme-primary mb-6 flex items-center gap-2">
                  <Target className="w-6 h-6" />
                  Interests
                </h2>
                <div className="flex flex-wrap gap-2">
                  {interests.map((item) => (
                    <span
                      key={item.key}
                      className="px-3 py-1 bg-green-500/20 text-green-500 rounded-full text-sm font-medium"
                    >
                      {item.label}
                    </span>
                  ))}
                </div>
              </div>
            )}

            {/* Tender Preferences */}
            {user.interestedInTenders && (user.tenderMinimumAmount || user.tenderMaximumAmount || user.tenderArea || user.tenderCategory) && (
              <div className="mb-12">
                <h2 className="text-2xl font-bold text-theme-primary mb-6">Tender Preferences</h2>
                <div className="grid md:grid-cols-2 gap-6">
                  {user.tenderMinimumAmount && (
                    <div className="p-4 rounded-xl bg-theme-input border border-primary-500/20">
                      <p className="text-xs text-theme-muted mb-1">Minimum Amount</p>
                      <p className="text-sm font-medium text-theme-primary">
                        ₹{user.tenderMinimumAmount.toLocaleString()}
                      </p>
                    </div>
                  )}
                  {user.tenderMaximumAmount && (
                    <div className="p-4 rounded-xl bg-theme-input border border-primary-500/20">
                      <p className="text-xs text-theme-muted mb-1">Maximum Amount</p>
                      <p className="text-sm font-medium text-theme-primary">
                        ₹{user.tenderMaximumAmount.toLocaleString()}
                      </p>
                    </div>
                  )}
                  {user.tenderArea && (
                    <div className="p-4 rounded-xl bg-theme-input border border-primary-500/20">
                      <p className="text-xs text-theme-muted mb-1">Preferred Area</p>
                      <p className="text-sm font-medium text-theme-primary">{user.tenderArea}</p>
                    </div>
                  )}
                  {user.tenderCategory && (
                    <div className="p-4 rounded-xl bg-theme-input border border-primary-500/20">
                      <p className="text-xs text-theme-muted mb-1">Category</p>
                      <p className="text-sm font-medium text-theme-primary">{user.tenderCategory}</p>
                    </div>
                  )}
                </div>
              </div>
            )}

            {/* Documents */}
            {(user.shopactDocument || user.udyamAadharDocument || user.gstDocument || user.aadharCardImage || user.panCardImage) && (
              <div className="mb-12">
                <h2 className="text-2xl font-bold text-theme-primary mb-6 flex items-center gap-2">
                  <FileText className="w-6 h-6" />
                  Documents
                </h2>
                <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
                  {user.shopactDocument && (
                    <a
                      href={user.shopactDocument.startsWith("http") ? user.shopactDocument : `${process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000"}${user.shopactDocument}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="p-4 rounded-xl bg-theme-input border border-primary-500/20 hover:border-primary-500 transition-colors"
                    >
                      <FileText className="w-8 h-8 text-primary-500 mb-2" />
                      <p className="text-sm font-medium text-theme-primary">Shopact Document</p>
                    </a>
                  )}
                  {user.udyamAadharDocument && (
                    <a
                      href={user.udyamAadharDocument.startsWith("http") ? user.udyamAadharDocument : `${process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000"}${user.udyamAadharDocument}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="p-4 rounded-xl bg-theme-input border border-primary-500/20 hover:border-primary-500 transition-colors"
                    >
                      <FileText className="w-8 h-8 text-primary-500 mb-2" />
                      <p className="text-sm font-medium text-theme-primary">Udyam Aadhar</p>
                    </a>
                  )}
                  {user.gstDocument && (
                    <a
                      href={user.gstDocument.startsWith("http") ? user.gstDocument : `${process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000"}${user.gstDocument}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="p-4 rounded-xl bg-theme-input border border-primary-500/20 hover:border-primary-500 transition-colors"
                    >
                      <FileText className="w-8 h-8 text-primary-500 mb-2" />
                      <p className="text-sm font-medium text-theme-primary">GST Document</p>
                    </a>
                  )}
                  {user.aadharCardImage && (
                    <div className="p-4 rounded-xl bg-theme-input border border-primary-500/20">
                      <div className="aspect-video rounded-lg overflow-hidden mb-2">
                        <img
                          src={user.aadharCardImage.startsWith("http") ? user.aadharCardImage : `${process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000"}${user.aadharCardImage}`}
                          alt="Aadhar Card"
                          className="w-full h-full object-cover"
                        />
                      </div>
                      <p className="text-sm font-medium text-theme-primary">Aadhar Card</p>
                      {user.aadharVerified && (
                        <span className="text-xs text-green-500 flex items-center gap-1 mt-1">
                          <CheckCircle className="w-3 h-3" />
                          Verified
                        </span>
                      )}
                    </div>
                  )}
                  {user.panCardImage && (
                    <div className="p-4 rounded-xl bg-theme-input border border-primary-500/20">
                      <div className="aspect-video rounded-lg overflow-hidden mb-2">
                        <img
                          src={user.panCardImage.startsWith("http") ? user.panCardImage : `${process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000"}${user.panCardImage}`}
                          alt="Pan Card"
                          className="w-full h-full object-cover"
                        />
                      </div>
                      <p className="text-sm font-medium text-theme-primary">Pan Card</p>
                    </div>
                  )}
                </div>
              </div>
            )}

            {/* Membership Section */}
            <div className="mb-12">
              <h2 className="text-2xl font-bold text-theme-primary mb-6 flex items-center gap-2">
                <Shield className="w-6 h-6" />
                Membership Details
              </h2>

              {/* Fetch my plans to check status */}
              <MembershipWidget />
            </div>

            {/* Service Status */}
            <div className="mb-12">
              <h2 className="text-2xl font-bold text-theme-primary mb-6">Service Status</h2>
              <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
                {serviceStatuses.map((service) => (
                  <div
                    key={service.name}
                    className={`p-4 rounded-xl border ${service.active
                      ? "bg-green-500/10 border-green-500/30"
                      : "bg-theme-input border-primary-500/20"
                      }`}
                  >
                    <div className="flex items-center justify-between mb-2">
                      <p className="text-sm font-medium text-theme-primary">{service.name}</p>
                      {service.active ? (
                        <CheckCircle className="w-4 h-4 text-green-500" />
                      ) : (
                        <XCircle className="w-4 h-4 text-theme-muted" />
                      )}
                    </div>
                    <p className={`text-xs ${service.active ? "text-green-500" : "text-theme-muted"}`}>
                      {service.active ? "Active" : "Inactive"}
                    </p>
                    {!service.active && (
                      <Link
                        href="/plans"
                        className="mt-3 flex items-center justify-center gap-1 w-full py-2 bg-primary-500 text-white text-xs font-semibold rounded-lg hover:bg-primary-600 transition-colors"
                      >
                        Activate Now
                        <ExternalLink className="w-3 h-3" />
                      </Link>
                    )}
                  </div>
                ))}
              </div>
            </div>
          </motion.div>
        </div>
      </main>
      <Footer />
    </div>
  );
}
