"use client";

import { useState } from "react";
import Link from "next/link";
import { useGetAllTendersQuery, useDeleteTenderMutation, type Tender } from "@/redux/apis/tender/tenderApi";
import Layout from "@/app/components/Layout";
import { FileText, Download, Eye, X } from "lucide-react";

export default function TendersPage() {
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);
  const [selectedTender, setSelectedTender] = useState<Tender | null>(null);
  const [showDocumentsModal, setShowDocumentsModal] = useState(false);

  const { data, isLoading, refetch } = useGetAllTendersQuery({
    page,
    limit: 10,
    search: search || undefined,
  });

  const [deleteTender] = useDeleteTenderMutation();

  const tenders = data?.data?.tenders || [];
  const totalPages = data?.data?.pagination?.totalPages || 1;
  const total = data?.data?.pagination?.total || 0;

  const handleDelete = async (id: number) => {
    if (!confirm("Are you sure you want to delete this tender?")) return;
    try {
      await deleteTender(id).unwrap();
      refetch();
      alert("Tender deleted successfully!");
    } catch (error) {
      console.error("Error deleting tender:", error);
      alert("Failed to delete tender");
    }
  };

  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}`;
  };

  return (
    <Layout>
      <div className="p-6">
        <div className="max-w-7xl mx-auto">
          <div className="flex justify-between items-center mb-6">
            <h1 className="text-2xl sm:text-3xl font-bold text-gray-900">All Tenders</h1>
            <Link
              href="/tenders/new"
              className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-2"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
              </svg>
              Add New Tender
            </Link>
          </div>

          <div className="bg-white rounded-lg shadow-sm p-6 mb-6">
            <input
              type="text"
              placeholder="Search tenders..."
              value={search}
              onChange={(e) => {
                setSearch(e.target.value);
                setPage(1);
              }}
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-gray-900"
            />
          </div>

          {isLoading ? (
            <div className="text-center py-12">
              <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
              <p className="mt-2 text-gray-600">Loading tenders...</p>
            </div>
          ) : tenders.length === 0 ? (
            <div className="bg-white rounded-lg shadow-sm p-12 text-center">
              <p className="text-gray-600">No tenders found</p>
            </div>
          ) : (
            <>
              <div className="bg-white rounded-lg shadow-sm overflow-hidden">
                <div className="overflow-x-auto">
                  <table className="min-w-full divide-y divide-gray-200">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                          Tender Title
                        </th>
                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                          Tender ID
                        </th>
                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                          Reference Number
                        </th>
                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                          Amount
                        </th>
                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                          Publication Date
                        </th>
                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                          Documents
                        </th>
                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                          Status
                        </th>
                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                          Actions
                        </th>
                      </tr>
                    </thead>
                    <tbody className="bg-white divide-y divide-gray-200">
                      {tenders.map((tender) => {
                        let otherDocs: string[] = [];
                        try {
                          // Check if it looks like a JSON array/object to avoid parsing errors on plain strings
                          if (tender.otherDocuments && (tender.otherDocuments.trim().startsWith('[') || tender.otherDocuments.trim().startsWith('{'))) {
                            otherDocs = JSON.parse(tender.otherDocuments);
                          } else {
                            // Treat as empty or maybe valid if it's a simple string? For now assume empty if not JSON.
                            otherDocs = [];
                          }
                        } catch (e) {
                          otherDocs = [];
                        }

                        const totalDocs = [
                          tender.boqDocument,
                          tender.tenderNoticeDocument,
                          ...otherDocs
                        ].filter(Boolean).length;

                        return (
                          <tr key={tender.id} className="hover:bg-gray-50">
                            <td className="px-6 py-4">
                              <div className="text-sm font-medium text-gray-900 max-w-xs truncate">
                                {tender.tenderTitle || "N/A"}
                              </div>
                              {(tender.city || tender.state) && (
                                <div className="text-xs text-gray-500">
                                  {tender.city}{tender.city && tender.state ? ", " : ""}{tender.state}
                                </div>
                              )}
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap">
                              <div className="text-sm text-gray-500">
                                {tender.tenderId || "N/A"}
                              </div>
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap">
                              <div className="text-sm text-gray-500">
                                {tender.tenderReferenceNumber || "N/A"}
                              </div>
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap">
                              <div className="text-sm text-gray-500">
                                {tender.amount
                                  ? `₹${Number(tender.amount).toLocaleString()}`
                                  : "N/A"}
                              </div>
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap">
                              <div className="text-sm text-gray-500">
                                {tender.publicationDate
                                  ? new Date(tender.publicationDate).toLocaleDateString()
                                  : "N/A"}
                              </div>
                            </td>
                            <td className="px-6 py-4">
                              <button
                                onClick={() => handleViewDocuments(tender)}
                                className="flex items-center gap-2 px-3 py-1.5 text-sm text-blue-600 hover:text-blue-800 hover:bg-blue-50 rounded-lg transition-colors"
                              >
                                <Eye className="w-4 h-4" />
                                View Documents
                                {(() => {
                                  let otherDocs: string[] = [];
                                  try {
                                    if (tender.otherDocuments && (tender.otherDocuments.trim().startsWith('[') || tender.otherDocuments.trim().startsWith('{'))) {
                                      otherDocs = JSON.parse(tender.otherDocuments);
                                    } else {
                                      otherDocs = [];
                                    }
                                  } catch (e) {
                                    otherDocs = [];
                                  }
                                  const totalDocs = [
                                    tender.boqDocument,
                                    tender.tenderNoticeDocument,
                                    ...otherDocs
                                  ].filter(Boolean).length;
                                  return totalDocs > 0 ? (
                                    <span className="ml-1 px-1.5 py-0.5 bg-blue-100 text-blue-700 text-xs rounded-full">
                                      {totalDocs}
                                    </span>
                                  ) : null;
                                })()}
                              </button>
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap">
                              <span
                                className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${tender.isActive
                                  ? "bg-green-100 text-green-800"
                                  : "bg-red-100 text-red-800"
                                  }`}
                              >
                                {tender.isActive ? "Active" : "Inactive"}
                              </span>
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                              <Link
                                href={`/tenders/new?id=${tender.id}`}
                                className="text-blue-600 hover:text-blue-900 mr-4 font-medium"
                              >
                                Edit
                              </Link>
                              <button
                                onClick={() => handleDelete(tender.id!)}
                                className="text-red-600 hover:text-red-900 font-medium"
                              >
                                Delete
                              </button>
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              </div>

              {totalPages > 1 && (
                <div className="mt-6 flex justify-center items-center gap-2">
                  <button
                    onClick={() => setPage((p) => Math.max(1, p - 1))}
                    disabled={page === 1}
                    className="px-4 py-2 border border-gray-300 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
                  >
                    Previous
                  </button>
                  <span className="px-4 py-2 text-sm text-gray-600">
                    Page {page} of {totalPages} (Total: {total})
                  </span>
                  <button
                    onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                    disabled={page === totalPages}
                    className="px-4 py-2 border border-gray-300 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
                  >
                    Next
                  </button>
                </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">
            <div 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">
                <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)]">
                {(() => {
                  let otherDocs: string[] = [];
                  try {
                    if (selectedTender.otherDocuments && (selectedTender.otherDocuments.trim().startsWith('[') || selectedTender.otherDocuments.trim().startsWith('{'))) {
                      otherDocs = JSON.parse(selectedTender.otherDocuments);
                    } else {
                      otherDocs = [];
                    }
                  } catch (e) {
                    otherDocs = [];
                  }
                  const hasDocuments = selectedTender.boqDocument ||
                    selectedTender.tenderNoticeDocument ||
                    otherDocs.length > 0;

                  if (!hasDocuments) {
                    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 && (
                        <div className="flex items-center justify-between p-4 bg-blue-50 rounded-lg border border-blue-200">
                          <div className="flex items-center gap-3">
                            <div className="p-2 bg-blue-100 rounded-lg">
                              <FileText className="w-6 h-6 text-blue-600" />
                            </div>
                            <div>
                              <p className="font-medium text-gray-900">BOQ Document</p>
                              <p className="text-sm text-gray-500">
                                {selectedTender.boqDocument.split('/').pop()}
                              </p>
                            </div>
                          </div>
                          <div className="flex gap-2">
                            <a
                              href={getDocumentUrl(selectedTender.boqDocument)}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-2"
                            >
                              <Eye className="w-4 h-4" />
                              View
                            </a>
                            <a
                              href={getDocumentUrl(selectedTender.boqDocument)}
                              download
                              className="px-4 py-2 bg-white text-blue-600 border border-blue-600 rounded-lg hover:bg-blue-50 transition-colors flex items-center gap-2"
                            >
                              <Download className="w-4 h-4" />
                              Download
                            </a>
                          </div>
                        </div>
                      )}

                      {/* Tender Notice Document */}
                      {selectedTender.tenderNoticeDocument && (
                        <div className="flex items-center justify-between p-4 bg-green-50 rounded-lg border border-green-200">
                          <div className="flex items-center gap-3">
                            <div className="p-2 bg-green-100 rounded-lg">
                              <FileText className="w-6 h-6 text-green-600" />
                            </div>
                            <div>
                              <p className="font-medium text-gray-900">Tender Notice Document</p>
                              <p className="text-sm text-gray-500">
                                {selectedTender.tenderNoticeDocument.split('/').pop()}
                              </p>
                            </div>
                          </div>
                          <div className="flex gap-2">
                            <a
                              href={getDocumentUrl(selectedTender.tenderNoticeDocument)}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors flex items-center gap-2"
                            >
                              <Eye className="w-4 h-4" />
                              View
                            </a>
                            <a
                              href={getDocumentUrl(selectedTender.tenderNoticeDocument)}
                              download
                              className="px-4 py-2 bg-white text-green-600 border border-green-600 rounded-lg hover:bg-green-50 transition-colors flex items-center gap-2"
                            >
                              <Download className="w-4 h-4" />
                              Download
                            </a>
                          </div>
                        </div>
                      )}

                      {/* Other Documents */}
                      {otherDocs.length > 0 && (
                        <div className="space-y-2">
                          <h3 className="font-semibold text-gray-900 mb-3">Other Documents</h3>
                          {otherDocs.map((doc: string, index: number) => (
                            <div
                              key={index}
                              className="flex items-center justify-between p-4 bg-gray-50 rounded-lg border border-gray-200"
                            >
                              <div className="flex items-center gap-3">
                                <div className="p-2 bg-gray-100 rounded-lg">
                                  <FileText className="w-6 h-6 text-gray-600" />
                                </div>
                                <div>
                                  <p className="font-medium text-gray-900">Document {index + 1}</p>
                                  <p className="text-sm text-gray-500">
                                    {doc.split('/').pop()}
                                  </p>
                                </div>
                              </div>
                              <div className="flex gap-2">
                                <a
                                  href={getDocumentUrl(doc)}
                                  target="_blank"
                                  rel="noopener noreferrer"
                                  className="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors flex items-center gap-2"
                                >
                                  <Eye className="w-4 h-4" />
                                  View
                                </a>
                                <a
                                  href={getDocumentUrl(doc)}
                                  download
                                  className="px-4 py-2 bg-white text-gray-600 border border-gray-600 rounded-lg hover:bg-gray-50 transition-colors flex items-center gap-2"
                                >
                                  <Download className="w-4 h-4" />
                                  Download
                                </a>
                              </div>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  );
                })()}
              </div>

              {/* Modal Footer */}
              <div className="flex justify-end p-6 border-t border-gray-200">
                <button
                  onClick={() => setShowDocumentsModal(false)}
                  className="px-6 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors"
                >
                  Close
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </Layout>
  );
}
