"use client";


import { motion } from "framer-motion";
import { useInView } from "framer-motion";
import { useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { useGetAllTendersQuery } from "@/redux/apis/tenderApi";
import { useSaveUserTenderMutation, useGetMySavedTendersQuery, useRemoveUserTenderMutation } from "@/redux/apis/saveTenderApi";
import { useSelector } from "react-redux";
import { selectIsAuthenticated } from "@/redux/slices/authSlice";
import { FileText, Download, Eye, X, Bookmark } from "lucide-react";
import type { Tender } from "@/lib/api";
import PlanRestrictionModal from "./PlanRestrictionModal";

export default function TenderTable() {
  const router = useRouter();
  const isAuthenticated = useSelector(selectIsAuthenticated);
  const { data: savedTendersData } = useGetMySavedTendersQuery(undefined, { skip: !isAuthenticated });
  const [saveUserTender] = useSaveUserTenderMutation();
  const [removeUserTender] = useRemoveUserTenderMutation();
  const savedTenderIds = savedTendersData?.data?.map((t: { tenderId: number }) => t.tenderId) || [];

  const handleSaveToggle = async (tenderId: number) => {
    if (!isAuthenticated) {
      router.push("/login");
      return;
    }
    try {
      const isSaved = savedTenderIds.includes(tenderId);
      if (isSaved) {
        await removeUserTender(tenderId).unwrap();
      } else {
        await saveUserTender({ tenderId }).unwrap();
      }
    } catch (error: unknown) {
      if ((error as { data?: { message?: string } })?.data?.message?.toLowerCase().includes("plan")) {
        setShowPlanModal(true);
      } else {
        console.error("Failed to save/unsave tender:", error);
      }
    }
  };

  const { data: response, error: apiError, isLoading } = useGetAllTendersQuery({ limit: 4, isActive: true });
  const tenders = response?.data?.tenders || [];
  const ref = useRef(null);
  const isInView = useInView(ref, { once: true, margin: "-100px" });
  const [selectedTender, setSelectedTender] = useState<Tender | null>(null);
  const [showDocumentsModal, setShowDocumentsModal] = useState(false);
  const [showPlanModal, setShowPlanModal] = useState(false);

  const formatCurrency = (amount: number | null) => {
    if (!amount) return "N/A";
    return new Intl.NumberFormat("en-IN", {
      style: "currency",
      currency: "INR",
      maximumFractionDigits: 0,
    }).format(amount);
  };

  const formatDate = (dateString: string | null) => {
    if (!dateString) return "N/A";
    return new Date(dateString).toLocaleDateString("en-IN", {
      year: "numeric",
      month: "short",
      day: "numeric",
    });
  };

  // Helper function to safely parse document fields that may contain access control messages
  const safeParseDocuments = (docString: string | null): string[] => {
    if (!docString) return [];

    // Check if it's an access control message (starts with "Please")
    if (docString.startsWith("Please")) {
      return [];
    }

    try {
      const parsed = JSON.parse(docString);
      return Array.isArray(parsed) ? parsed : [];
    } catch {
      return [];
    }
  };

  // Helper to check if a document field is valid (not an access control message)
  const isValidDocument = (doc: string | null): boolean => {
    if (!doc) return false;
    return !doc.startsWith("Please");
  };

  const handleViewDocuments = (tender: Tender) => {
    setSelectedTender(tender);
    setShowDocumentsModal(true);
  };

  const getDocumentUrl = (path: string) => {
    const apiUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000/api";
    return `${apiUrl}/uploads/${path}`;
  };

  if (isLoading) {
    return (
      <section ref={ref} className="py-16 bg-gray-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center">
            <div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-green-600"></div>
            <p className="mt-4 text-gray-600">Loading tenders...</p>
          </div>
        </div>
      </section>
    );
  }

  if (apiError) {
    return (
      <section ref={ref} className="py-16 bg-gray-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center text-red-600">
            <p>Failed to load tenders. Please try again later.</p>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section ref={ref} className="relative pt-4 pb-8 bg-gray-50 overflow-x-hidden w-full">
      {/* Top Decorative Elements */}
      <div className="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-transparent via-green-500/30 to-transparent"></div>
      <div className="absolute top-2 left-1/2 -translate-x-1/2 w-24 h-1 bg-gradient-to-r from-green-400 to-green-600 rounded-full"></div>



      {/* Animated Pulsing Dots */}
      <div className="absolute top-12 left-1/4 z-10">
        <motion.div
          initial={{ opacity: 0 }}
          animate={isInView ? { opacity: 1 } : { opacity: 0 }}
          transition={{ delay: 0.5 }}
          className="relative"
        >
          <motion.div
            animate={{
              scale: [1, 1.5, 1],
              opacity: [0.8, 0, 0.8],
            }}
            transition={{
              duration: 2,
              repeat: Infinity,
            }}
            className="absolute w-3 h-3 bg-green-500 rounded-full"
          />
          <div className="w-3 h-3 bg-green-600 rounded-full relative z-10" />
        </motion.div>
      </div>
      <div className="absolute top-12 right-1/4 z-10">
        <motion.div
          initial={{ opacity: 0 }}
          animate={isInView ? { opacity: 1 } : { opacity: 0 }}
          transition={{ delay: 0.7 }}
          className="relative"
        >
          <motion.div
            animate={{
              scale: [1, 1.5, 1],
              opacity: [0.8, 0, 0.8],
            }}
            transition={{
              duration: 2,
              repeat: Infinity,
              delay: 0.5,
            }}
            className="absolute w-3 h-3 bg-green-500 rounded-full"
          />
          <div className="w-3 h-3 bg-green-600 rounded-full relative z-10" />
        </motion.div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 w-full">
        <motion.div
          initial={{ opacity: 0, y: 30 }}
          animate={isInView ? { opacity: 1, y: 0 } : {}}
          transition={{ duration: 0.6 }}
          className="text-center mb-12 mt-8"
        >
          <h2 className="text-3xl sm:text-4xl font-bold text-gray-900 mb-4">
            Latest Tenders
          </h2>
          <p className="text-lg text-gray-600 max-w-2xl mx-auto">
            Browse through the latest government tenders available for solar energy projects
          </p>
        </motion.div>

        {tenders.length === 0 ? (
          <motion.div
            initial={{ opacity: 0 }}
            animate={isInView ? { opacity: 1 } : {}}
            className="text-center py-12"
          >
            <p className="text-gray-600 text-lg">No tenders available at the moment.</p>
          </motion.div>
        ) : (
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            animate={isInView ? { opacity: 1, y: 0 } : {}}
            transition={{ duration: 0.6, delay: 0.2 }}
            className="bg-white rounded-lg shadow-lg overflow-hidden w-full"
          >
            <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden w-full">
              <div className="overflow-x-auto w-full">
                <table className="min-w-full divide-y divide-gray-200 w-full">
                  <thead className="bg-gray-50/80 backdrop-blur-sm">
                    <tr>
                      <th className="px-3 py-3 sm:px-6 sm:py-5 text-left text-[10px] sm:text-xs font-bold text-gray-500 uppercase tracking-wider w-[50px]">
                        Status
                      </th>
                      <th className="px-3 py-3 sm:px-6 sm:py-5 text-left text-[10px] sm:text-xs font-bold text-gray-500 uppercase tracking-wider w-[25%]">
                        Tender Information
                      </th>
                      <th className="px-3 py-3 sm:px-6 sm:py-5 text-left text-[10px] sm:text-xs font-bold text-gray-500 uppercase tracking-wider">
                        Type
                      </th>
                      <th className="px-3 py-3 sm:px-6 sm:py-5 text-left text-[10px] sm:text-xs font-bold text-gray-500 uppercase tracking-wider">
                        Opening Date
                      </th>
                      <th className="px-3 py-3 sm:px-6 sm:py-5 text-left text-[10px] sm:text-xs font-bold text-gray-500 uppercase tracking-wider">
                        Closing Date
                      </th>
                      <th className="px-3 py-3 sm:px-6 sm:py-5 text-left text-[10px] sm:text-xs font-bold text-gray-500 uppercase tracking-wider">
                        Value
                      </th>
                      <th className="px-3 py-3 sm:px-6 sm:py-5 text-center text-[10px] sm:text-xs font-bold text-gray-500 uppercase tracking-wider">
                        Docs
                      </th>
                      <th className="px-3 py-3 sm:px-6 sm:py-5 text-right text-[10px] sm:text-xs font-bold text-gray-500 uppercase tracking-wider">
                        Action
                      </th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-100">
                    {tenders.map((tender, index) => (
                      <motion.tr
                        key={tender.id}
                        initial={{ opacity: 0, y: 10 }}
                        animate={isInView ? { opacity: 1, y: 0 } : {}}
                        transition={{ duration: 0.3, delay: index * 0.05 }}
                        className="hover:bg-green-50/30 transition-all group"
                      >
                        {/* Status Column */}
                        <td className="px-3 py-3 sm:px-6 sm:py-5 align-top">
                          {(function() {
                            const isLatest = (dateString: string | null | undefined) => {
                              if (!dateString) return false;
                              const tenderDate = new Date(dateString);
                              const today = new Date();
                              
                              // Reset time to compare dates only
                              tenderDate.setHours(0, 0, 0, 0);
                              today.setHours(0, 0, 0, 0);
                              
                              const diffTime = today.getTime() - tenderDate.getTime();
                              const diffDays = diffTime / (1000 * 60 * 60 * 24);
                              
                              // Show latest only if bid/open date is today or in the past (up to 15 days)
                              return diffDays >= 0 && diffDays <= 15;
                            };
                            return isLatest(tender.publicationDate) ? (
                              <div className="relative flex items-center justify-center w-14 h-14">
                                <motion.div
                                  animate={{ rotate: 360 }}
                                  transition={{ 
                                    duration: 8, 
                                    repeat: Infinity, 
                                    ease: "linear" 
                                  }}
                                  className="absolute inset-0 text-red-600 drop-shadow-md"
                                >
                                  {/* Starburst/Seal shape */}
                                  <svg viewBox="0 0 24 24" fill="currentColor" className="w-full h-full">
                                    <path d="M12 2l1.6 4.8 4.6.5-3.4 3.2 1 4.9-4.3-2.3-4.3 2.3 1-4.9-3.4-3.2 4.6-.5L12 2z" transform="scale(1.1)" style={{ transformOrigin: "center" }} />
                                    <path d="M12 0l2.5 7.5h7.5l-6 4.5 2.5 7.5-6-4.5-6 4.5 2.5-7.5-6-4.5h7.5z" opacity="0.5" transform="rotate(22.5 12 12) scale(0.8)" />
                                    <path d="M12,22c-5.52,0-10-4.48-10-10S6.48,2,12,2s10,4.48,10,10S17.52,22,12,22z" fill="none"/>
                                    <path d="M22,12l-2.8-2.1l0.6-3.4l-3.4-0.6L14.3,3.8L12,6.5L9.7,3.8L7.6,5.9L4.2,6.5l0.6,3.4L2,12l2.8,2.1l-0.6,3.4l3.4,0.6 l2.1,2.1L12,17.5l2.3,2.7l2.1-2.1l3.4-0.6l-0.6-3.4L22,12z" />
                                  </svg>
                                </motion.div>
                                <span className="relative z-10 text-[8px] font-black text-white tracking-wider uppercase transform -rotate-12">
                                  LATEST
                                </span>
                              </div>
                            ) : null;
                          })()}
                        </td>

                        {/* Tender Info */}
                        <td className="px-3 py-3 sm:px-6 sm:py-5 align-top">
                          <div className="flex flex-col gap-1">
                            <div className="flex items-start justify-between gap-2">
                              <span className="text-xs sm:text-sm font-bold text-gray-900 group-hover:text-green-700 transition-colors line-clamp-2 leading-relaxed">
                                {tender.tenderTitle}
                              </span>
                            </div>
                            <div className="flex items-center gap-2 mt-1">
                              <span className="text-[10px] sm:text-xs text-gray-400 font-mono">
                                #{tender.tenderReferenceNumber || "NA"}
                              </span>
                            </div>
                            {tender.tenderId && (
                              <div className="text-[10px] text-gray-400">ID: {tender.tenderId}</div>
                            )}
                          </div>
                        </td>

                        {/* Type & Status */}
                        <td className="px-3 py-3 sm:px-6 sm:py-5 align-top">
                          <div className="flex flex-col gap-2 items-start">
                            <span className="inline-flex items-center px-2 py-0.5 sm:px-2.5 sm:py-1 rounded-md text-[10px] sm:text-xs font-bold bg-blue-50 text-blue-700 uppercase tracking-wide border border-blue-100">
                              {tender.tenderType || "TENDER"}
                            </span>
                            <span
                              className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-bold border ${tender.isActive
                                ? "bg-green-50 text-green-700 border-green-200"
                                : "bg-gray-50 text-gray-600 border-gray-200"
                                }`}
                            >
                              <span className={`w-1.5 h-1.5 rounded-full ${tender.isActive ? "bg-green-500 animate-pulse" : "bg-gray-400"}`}></span>
                              {tender.isActive ? "Active" : "Closed"}
                            </span>
                          </div>
                        </td>

                        {/* Opening Date */}
                        <td className="px-3 py-3 sm:px-6 sm:py-5 align-top">
                          <div className="flex flex-col">
                            <span className="text-xs sm:text-sm text-green-700 font-bold">
                              {formatDate(tender.bidOpenDate)}
                            </span>
                            <span className="text-[10px] text-gray-400 font-medium uppercase tracking-wider">Start</span>
                          </div>
                        </td>

                        {/* Closing Date */}
                        <td className="px-3 py-3 sm:px-6 sm:py-5 align-top">
                          <div className="flex flex-col">
                            <span className="text-xs sm:text-sm text-red-600 font-bold">
                              {formatDate(tender.bidSubmissionDate)}
                            </span>
                            <span className="text-[10px] text-gray-400 font-medium uppercase tracking-wider">End</span>
                          </div>
                        </td>

                        {/* Value */}
                        <td className="px-3 py-3 sm:px-6 sm:py-5 align-top">
                          <div className="flex flex-col gap-1">
                            <p className="text-sm sm:text-lg font-bold text-gray-900 tracking-tight">
                              {formatCurrency(tender.amount)}
                            </p>
                            {tender.emdAmount && (
                              <p className="text-[10px] sm:text-xs text-gray-500">
                                EMD: {formatCurrency(tender.emdAmount)}
                              </p>
                            )}
                          </div>
                        </td>

                        {/* Documents */}
                        <td className="px-3 py-3 sm:px-6 sm:py-5 align-middle text-center">
                          <button
                            onClick={() => handleViewDocuments(tender)}
                            className="inline-flex flex-col items-center justify-center gap-1 p-1 sm:p-2 rounded-lg hover:bg-white text-gray-500 hover:text-blue-600 border border-transparent hover:border-gray-200 hover:shadow-sm transition-all group/btn"
                          >
                            <div className="relative">
                              <FileText className="w-5 h-5 sm:w-6 sm:h-6 group-hover/btn:scale-110 transition-transform" />
                              {(() => {
                                const otherDocs = safeParseDocuments(tender.otherDocuments);
                                const totalDocs = [
                                  tender.boqDocument,
                                  tender.tenderNoticeDocument,
                                  ...otherDocs
                                ].filter(doc => doc && isValidDocument(doc)).length;
                                return totalDocs > 0 ? (
                                  <span className="absolute -top-1 -right-1 w-3 h-3 sm:w-4 sm:h-4 flex items-center justify-center bg-blue-600 text-white text-[8px] sm:text-[10px] font-bold rounded-full ring-2 ring-white">
                                    {totalDocs}
                                  </span>
                                ) : null;
                              })()}
                            </div>
                            <span className="text-[8px] sm:text-[10px] font-bold uppercase tracking-wider">Docs</span>
                          </button>
                        </td>

                        {/* Actions */}
                        <td className="px-3 py-3 sm:px-6 sm:py-5 align-middle text-right">
                          <div className="flex flex-col items-end gap-2">
                            <button
                              onClick={() => router.push(`/tenders/${tender.id}`)}
                              className="w-full px-2 py-1.5 sm:px-4 sm:py-2 bg-green-600 text-white text-[10px] sm:text-xs font-bold uppercase tracking-wider rounded-lg hover:bg-green-700 transition-colors shadow-sm active:scale-95 text-center min-w-[80px] sm:min-w-[100px]"
                            >
                              View Details
                            </button>
                            <div className="flex items-center justify-end gap-2 w-full">
                              <button
                                onClick={() => handleSaveToggle(tender.id)}
                                className={`p-1.5 sm:p-2 rounded-lg border transition-all ${savedTenderIds.includes(tender.id)
                                  ? "bg-green-50 border-green-200 text-green-600"
                                  : "bg-white border-gray-200 text-gray-400 hover:border-gray-300 hover:text-gray-600"
                                  }`}
                                title={savedTenderIds.includes(tender.id) ? "Unsave" : "Save"}
                              >
                                <Bookmark className={`w-3 h-3 sm:w-4 sm:h-4 ${savedTenderIds.includes(tender.id) ? "fill-current" : ""}`} />
                              </button>
                            </div>
                          </div>
                        </td>
                      </motion.tr>
                    ))}
                  </tbody>
                </table>
              </div>
              <div className="px-6 py-4 bg-gray-50 border-t border-gray-200 flex justify-center">
                <button
                  onClick={() => router.push("/tenders")}
                  className="group flex items-center gap-2 px-6 py-2.5 bg-white border border-gray-300 text-gray-700 font-bold text-sm rounded-full hover:bg-gray-50 hover:border-gray-400 hover:text-gray-900 transition-all shadow-sm active:scale-95"
                >
                  View All Tenders
                  <span className="group-hover:translate-x-1 transition-transform">→</span>
                </button>
              </div>
            </div>
          </motion.div>
        )}
      </div>

      {/* Documents Modal */}
      {showDocumentsModal && selectedTender && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <motion.div
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0, scale: 0.9 }}
            className="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-hidden"
          >
            {/* Modal Header */}
            <div className="flex items-center justify-between p-6 border-b border-gray-200 bg-green-50">
              <h2 className="text-xl font-bold text-gray-900">
                📄 Documents - {selectedTender.tenderTitle}
              </h2>
              <button
                onClick={() => setShowDocumentsModal(false)}
                className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <X className="w-5 h-5 text-gray-500" />
              </button>
            </div>

            {/* Modal Body */}
            <div className="p-6 overflow-y-auto max-h-[calc(90vh-140px)]">
              {(() => {
                const otherDocs = safeParseDocuments(selectedTender.otherDocuments);
                const hasValidDocuments = isValidDocument(selectedTender.boqDocument) ||
                  isValidDocument(selectedTender.tenderNoticeDocument) ||
                  otherDocs.length > 0;

                // Check if documents are restricted
                const hasRestrictedDocs = (!isValidDocument(selectedTender.boqDocument) && selectedTender.boqDocument) ||
                  (!isValidDocument(selectedTender.tenderNoticeDocument) && selectedTender.tenderNoticeDocument) ||
                  (!isValidDocument(selectedTender.otherDocuments) && selectedTender.otherDocuments);

                // Determine restriction type
                let restrictionType: 'login' | 'plan' | null = null;
                if (hasRestrictedDocs) {
                  const restrictionMessage = selectedTender.boqDocument || selectedTender.tenderNoticeDocument || selectedTender.otherDocuments || '';
                  if (restrictionMessage.includes('Please login')) {
                    restrictionType = 'login';
                  } else if (restrictionMessage.includes('Please purchase')) {
                    restrictionType = 'plan';
                  }
                }

                // Show restriction message if documents are restricted
                if (hasRestrictedDocs && restrictionType) {
                  return (
                    <div className="text-center py-12">
                      <div className="max-w-md mx-auto">
                        {restrictionType === 'login' ? (
                          <>
                            <div className="w-20 h-20 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
                              <FileText className="w-10 h-10 text-blue-600" />
                            </div>
                            <h3 className="text-xl font-semibold text-gray-900 mb-2">🔐 Login Required</h3>
                            <p className="text-gray-600 mb-6">
                              Please login first to see the tender documents and details
                            </p>
                            <button
                              onClick={() => window.location.href = '/login'}
                              className="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium"
                            >
                              Login Now
                            </button>
                          </>
                        ) : (
                          <>
                            <div className="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                              <FileText className="w-10 h-10 text-green-600" />
                            </div>
                            <h3 className="text-xl font-semibold text-gray-900 mb-2">💎 Plan Required</h3>
                            <p className="text-gray-600 mb-6">
                              Please purchase the tender plan first to see the documents and details
                            </p>
                            <button
                              onClick={() => window.location.href = '/plans'}
                              className="px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors font-medium"
                            >
                              View Plans
                            </button>
                          </>
                        )}
                      </div>
                    </div>
                  );
                }

                if (!hasValidDocuments) {
                  return (
                    <div className="text-center py-12">
                      <FileText className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                      <p className="text-gray-500">No documents uploaded for this tender</p>
                    </div>
                  );
                }

                return (
                  <div className="space-y-4">
                    {/* BOQ Document */}
                    {selectedTender.boqDocument && isValidDocument(selectedTender.boqDocument) && (
                      <motion.div
                        initial={{ opacity: 0, y: 20 }}
                        animate={{ opacity: 1, y: 0 }}
                        className="flex flex-col sm:flex-row sm:items-center justify-between p-3 sm:p-4 bg-blue-50 rounded-lg border border-blue-200 gap-3 sm:gap-4"
                      >
                        <div className="flex items-center gap-3 overflow-hidden">
                          <div className="p-2 bg-blue-100 rounded-lg flex-shrink-0">
                            <FileText className="w-6 h-6 text-blue-600" />
                          </div>
                          <div className="min-w-0 flex-1">
                            <p className="font-medium text-gray-900 text-sm sm:text-base">BOQ Document</p>
                            <p className="text-xs text-gray-500 truncate">
                              {selectedTender.boqDocument.split('/').pop()}
                            </p>
                          </div>
                        </div>
                        <div className="flex gap-2 w-full sm:w-auto">
                          <a
                            href={getDocumentUrl(selectedTender.boqDocument)}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="flex-1 sm:flex-none justify-center px-3 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-2 text-sm"
                          >
                            <Eye className="w-4 h-4" />
                            View
                          </a>
                          <a
                            href={getDocumentUrl(selectedTender.boqDocument)}
                            download
                            className="flex-1 sm:flex-none justify-center px-3 py-2 bg-white text-blue-600 border border-blue-600 rounded-lg hover:bg-blue-50 transition-colors flex items-center gap-2 text-sm"
                          >
                            <Download className="w-4 h-4" />
                            Download
                          </a>
                        </div>
                      </motion.div>
                    )}

                    {/* Tender Notice Document */}
                    {selectedTender.tenderNoticeDocument && isValidDocument(selectedTender.tenderNoticeDocument) && (
                      <motion.div
                        initial={{ opacity: 0, y: 20 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ delay: 0.1 }}
                        className="flex flex-col sm:flex-row sm:items-center justify-between p-3 sm:p-4 bg-green-50 rounded-lg border border-green-200 gap-3 sm:gap-4"
                      >
                        <div className="flex items-center gap-3 overflow-hidden">
                          <div className="p-2 bg-green-100 rounded-lg flex-shrink-0">
                            <FileText className="w-6 h-6 text-green-600" />
                          </div>
                          <div className="min-w-0 flex-1">
                            <p className="font-medium text-gray-900 text-sm sm:text-base">Tender Notice</p>
                            <p className="text-xs text-gray-500 truncate">
                              {selectedTender.tenderNoticeDocument.split('/').pop()}
                            </p>
                          </div>
                        </div>
                        <div className="flex gap-2 w-full sm:w-auto">
                          <a
                            href={getDocumentUrl(selectedTender.tenderNoticeDocument)}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="flex-1 sm:flex-none justify-center px-3 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors flex items-center gap-2 text-sm"
                          >
                            <Eye className="w-4 h-4" />
                            View
                          </a>
                          <a
                            href={getDocumentUrl(selectedTender.tenderNoticeDocument)}
                            download
                            className="flex-1 sm:flex-none justify-center px-3 py-2 bg-white text-green-600 border border-green-600 rounded-lg hover:bg-green-50 transition-colors flex items-center gap-2 text-sm"
                          >
                            <Download className="w-4 h-4" />
                            Download
                          </a>
                        </div>
                      </motion.div>
                    )}

                    {/* Other Documents */}
                    {otherDocs.length > 0 && (
                      <div className="space-y-2">
                        <h3 className="font-semibold text-gray-900 mb-3 text-sm sm:text-base">Other Documents</h3>
                        {otherDocs.map((doc: string, index: number) => (
                          <motion.div
                            key={index}
                            initial={{ opacity: 0, y: 20 }}
                            animate={{ opacity: 1, y: 0 }}
                            transition={{ delay: 0.2 + index * 0.05 }}
                            className="flex flex-col sm:flex-row sm:items-center justify-between p-3 sm:p-4 bg-gray-50 rounded-lg border border-gray-200 gap-3 sm:gap-4"
                          >
                            <div className="flex items-center gap-3 overflow-hidden">
                              <div className="p-2 bg-gray-100 rounded-lg flex-shrink-0">
                                <FileText className="w-6 h-6 text-gray-600" />
                              </div>
                              <div className="min-w-0 flex-1">
                                <p className="font-medium text-gray-900 text-sm sm:text-base">Document {index + 1}</p>
                                <p className="text-xs text-gray-500 truncate">
                                  {doc.split('/').pop()}
                                </p>
                              </div>
                            </div>
                            <div className="flex gap-2 w-full sm:w-auto">
                              <a
                                href={getDocumentUrl(doc)}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="flex-1 sm:flex-none justify-center px-3 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors flex items-center gap-2 text-sm"
                              >
                                <Eye className="w-4 h-4" />
                                View
                              </a>
                              <a
                                href={getDocumentUrl(doc)}
                                download
                                className="flex-1 sm:flex-none justify-center px-3 py-2 bg-white text-gray-600 border border-gray-600 rounded-lg hover:bg-gray-50 transition-colors flex items-center gap-2 text-sm"
                              >
                                <Download className="w-4 h-4" />
                                Download
                              </a>
                            </div>
                          </motion.div>
                        ))}
                      </div>
                    )}
                  </div>
                );
              })()}
            </div>

            {/* Modal Footer */}
            <div className="flex justify-end p-6 border-t border-gray-200 bg-gray-50">
              <button
                onClick={() => setShowDocumentsModal(false)}
                className="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
              >
                Close
              </button>
            </div>
          </motion.div>
        </div>
      )}
      <PlanRestrictionModal
        isOpen={showPlanModal}
        onClose={() => setShowPlanModal(false)}
      />
    </section>
  );
}
