import React, { useState, useEffect } from "react";
import type { User } from "../../../types";
import { apiClient } from "../../../lib/api-client";
import {
  Check,
  X,
  ShieldAlert,
  Eye,
  Globe,
  Building2,
  FileCheck2,
  Calendar,
  Download,
} from "lucide-react";
import { DocumentPreview } from "../../agreements/components/DocumentPreview";

export const ClientApprovalQueue: React.FC = () => {
  const [clients, setClients] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedClient, setSelectedClient] = useState<User | null>(null);
  const [processingId, setProcessingId] = useState<string | null>(null);
  const [viewingDoc, setViewingDoc] = useState<{
    title: string;
    type: "NDA" | "MSA";
    company: string;
    signature?: string;
    date?: string;
  } | null>(null);

  const downloadDocument = async (
    type: "NDA" | "MSA",
    company: string,
    signature?: string,
    date?: string,
  ) => {
    // Load html2pdf dynamically
    const html2pdf = await new Promise<any>((resolve, reject) => {
      if ((window as any).html2pdf) {
        resolve((window as any).html2pdf);
        return;
      }
      const script = document.createElement("script");
      script.src = "https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js";
      script.onload = () => resolve((window as any).html2pdf);
      script.onerror = () => reject(new Error("Failed to load PDF library"));
      document.body.appendChild(script);
    });

    const title =
      type === "NDA"
        ? "Mutual Non-Disclosure Agreement"
        : "Master Services Agreement";

    const formattedDate = date
      ? new Date(date).toLocaleDateString("en-US", {
          year: "numeric",
          month: "long",
          day: "numeric",
        })
      : "[Pending Signature]";

    const element = document.createElement("div");
    element.style.padding = "45px 50px";
    element.style.fontFamily = "Georgia, serif";
    element.style.color = "#1e293b";
    element.style.backgroundColor = "#ffffff";
    element.style.lineHeight = "1.6";
    element.style.fontSize = "13px";

    const bodyContent = type === "NDA" 
      ? `
        <div style="text-align: justify; margin-bottom: 20px;">
          <p>This <strong>MUTUAL NON-DISCLOSURE AGREEMENT</strong> (the "Agreement") is made and entered into as of the date of final execution below (the "Effective Date"), by and between:</p>
          
          <div style="padding-left: 20px; border-left: 2px solid #cbd5e1; margin: 15px 0; font-family: sans-serif; font-size: 11px; color: #475569;">
            <p style="margin-bottom: 8px;"><strong>TECH4BIZ SOLUTIONS INC.</strong>, a corporation organized and existing under the laws of Delaware, with its principal executive office located at 100 Innovation Way, Suite 400 (hereinafter referred to as <strong>"Tech4Biz"</strong> or the <strong>"Disclosing Party"</strong>); and</p>
            <p style="margin: 0;"><strong>${company.toUpperCase()}</strong>, a business entity registered and operating under the laws of its jurisdiction of incorporation (hereinafter referred to as the <strong>"Company"</strong> or the <strong>"Receiving Party"</strong>).</p>
          </div>

          <p style="font-style: italic; font-size: 11px; border-top: 1px solid #f1f5f9; border-bottom: 1px solid #f1f5f9; padding: 8px 0; margin: 15px 0;">
            WHEREAS, Tech4Biz and the Company (collectively referred to as the "Parties" and individually as a "Party") desire to share proprietary information to evaluate a potential business relationship concerning technology integrations, hardware IP licensing (including RISC-V cores, FPGA modules), and developer frameworks (the "Purpose").
          </p>

          <p>NOW, THEREFORE, in consideration of the mutual covenants and promises contained herein, the Parties agree as follows:</p>

          <div style="margin-top: 20px;">
            <h3 style="font-family: sans-serif; font-size: 11px; font-weight: bold; text-transform: uppercase; color: #0f172a; margin-bottom: 4px;">1. Definition of Confidential Information</h3>
            <p style="margin-top: 0;">"Confidential Information" shall mean all information or material disclosed by one Party to the other Party that has value in such Party's business, including but not limited to technical data, hardware designs, silicon blueprints, compiler architecture, source code, product plans, marketing strategies, or business metrics, whether designated as confidential or which under the circumstances of disclosure should reasonably be understood to be confidential.</p>
          </div>

          <div style="margin-top: 20px;">
            <h3 style="font-family: sans-serif; font-size: 11px; font-weight: bold; text-transform: uppercase; color: #0f172a; margin-bottom: 4px;">2. Obligations of Confidentiality and Non-Use</h3>
            <p style="margin-top: 0;">The Receiving Party agrees: (a) to hold the Disclosing Party's Confidential Information in strict confidence using the same degree of care it uses to protect its own confidential information, but in no event less than a reasonable degree of care; (b) not to disclose such Confidential Information to any third party without prior written consent; and (c) to use the Confidential Information solely for the evaluation and execution of the Purpose.</p>
          </div>

          <div style="margin-top: 20px;">
            <h3 style="font-family: sans-serif; font-size: 11px; font-weight: bold; text-transform: uppercase; color: #0f172a; margin-bottom: 4px;">3. Permitted Disclosures</h3>
            <p style="margin-top: 0;">The Receiving Party may disclose Confidential Information only to those of its employees, contractors, and advisors who have a verifiable "need to know" in connection with the Purpose and who are bound by confidentiality obligations at least as restrictive as those contained in this Agreement.</p>
          </div>

          <div style="margin-top: 20px;">
            <h3 style="font-family: sans-serif; font-size: 11px; font-weight: bold; text-transform: uppercase; color: #0f172a; margin-bottom: 4px;">4. Term and Survival</h3>
            <p style="margin-top: 0;">This Agreement shall govern disclosures made within three (3) years from the Effective Date. The obligations of confidentiality, non-disclosure, and non-use shall survive for five (5) years following the termination of this Agreement, or indefinitely with respect to trade secrets.</p>
          </div>

          <div style="margin-top: 20px;">
            <h3 style="font-family: sans-serif; font-size: 11px; font-weight: bold; text-transform: uppercase; color: #0f172a; margin-bottom: 4px;">5. Governing Law and Jurisdiction</h3>
            <p style="margin-top: 0;">This Agreement shall be governed by, construed, and enforced in accordance with the laws of the State of Delaware, without regard to its conflict of laws principles. Any legal action arising hereunder shall be brought exclusively in the state or federal courts located in Delaware.</p>
          </div>
        </div>
      `
      : `
        <div style="text-align: justify; margin-bottom: 20px;">
          <p>This <strong>MASTER SERVICES AGREEMENT</strong> (the "MSA" or "Agreement") defines the commercial framework for service delivery, digital asset provisioning, and technology licensing, by and between:</p>
          
          <div style="padding-left: 20px; border-left: 2px solid #cbd5e1; margin: 15px 0; font-family: sans-serif; font-size: 11px; color: #475569;">
            <p style="margin-bottom: 8px;"><strong>TECH4BIZ SOLUTIONS INC.</strong>, a Delaware corporation, with its principal office at 100 Innovation Way, Suite 400 (hereinafter referred to as <strong>"Tech4Biz"</strong>); and</p>
            <p style="margin: 0;"><strong>${company.toUpperCase()}</strong>, a business entity registered and operating under the laws of its jurisdiction of incorporation (hereinafter referred to as the <strong>"Client"</strong>).</p>
          </div>

          <p style="font-style: italic; font-size: 11px; border-top: 1px solid #f1f5f9; border-bottom: 1px solid #f1f5f9; padding: 8px 0; margin: 15px 0;">
            WHEREAS, Tech4Biz provides high-fidelity silicon designs, custom compilation systems, and software engineering consulting; and the Client wishes to engage Tech4Biz to access such tools and services under the terms and conditions set forth herein.
          </p>

          <p>NOW, THEREFORE, in consideration of the mutual covenants and promises contained herein, the Parties agree as follows:</p>

          <div style="margin-top: 20px;">
            <h3 style="font-family: sans-serif; font-size: 11px; font-weight: bold; text-transform: uppercase; color: #0f172a; margin-bottom: 4px;">1. Scope of Work and Deliverables</h3>
            <p style="margin-top: 0;">All services, deliverables, and digital asset repositories (including synthesized silicon architectures, software libraries, and proprietary compiler tools) provided by Tech4Biz shall be set forth in individually executed Statements of Work ("SOWs") signed by authorized representatives of both Parties. Each SOW shall reference and be governed by the terms of this MSA.</p>
          </div>

          <div style="margin-top: 20px;">
            <h3 style="font-family: sans-serif; font-size: 11px; font-weight: bold; text-transform: uppercase; color: #0f172a; margin-bottom: 4px;">2. Intellectual Property and Licensing</h3>
            <p style="margin-top: 0;">Except as explicitly outlined in an SOW, all background Intellectual Property owned by Tech4Biz (including hardware designs, compilers, and the CodeNuk framework) remains the exclusive property of Tech4Biz. Client is granted a limited, non-exclusive, non-transferable, revocable license to utilize downloaded assets solely for internal testing and development purposes.</p>
          </div>

          <div style="margin-top: 20px;">
            <h3 style="font-family: sans-serif; font-size: 11px; font-weight: bold; text-transform: uppercase; color: #0f172a; margin-bottom: 4px;">3. Payment Terms and Financial Covenants</h3>
            <p style="margin-top: 0;">Client shall pay Tech4Biz the fees specified in each SOW. Unless otherwise stated in an SOW, all payments are due Net 30 days from the invoice date. Late payments shall accumulate interest at the rate of 1.5% per month, or the maximum rate permitted by law, whichever is lower.</p>
          </div>

          <div style="margin-top: 20px;">
            <h3 style="font-family: sans-serif; font-size: 11px; font-weight: bold; text-transform: uppercase; color: #0f172a; margin-bottom: 4px;">4. Limitation of Liability</h3>
            <p style="margin-top: 0;">IN NO EVENT SHALL EITHER PARTY BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES. TECH4BIZ TOTAL AGGREGATE LIABILITY UNDER THIS AGREEMENT AND ANY SOW SHALL NOT EXCEED THE TOTAL FEES PAID BY CLIENT TO TECH4BIZ UNDER THE APPLICABLE SOW IN THE SIX (6) MONTHS PRECEDING THE CLAIM.</p>
          </div>

          <div style="margin-top: 20px;">
            <h3 style="font-family: sans-serif; font-size: 11px; font-weight: bold; text-transform: uppercase; color: #0f172a; margin-bottom: 4px;">5. Confidentiality</h3>
            <p style="margin-top: 0;">The Parties agree that the existence, terms, and performance of this Agreement, as well as all proprietary information shared hereunder, shall be treated as confidential and governed by the active Mutual Non-Disclosure Agreement (NDA) executed by the Parties.</p>
          </div>
        </div>
      `;

    element.innerHTML = `
      <div style="text-align: center; margin-bottom: 30px; border-bottom: 2px solid #0f172a; padding-bottom: 15px;">
        <h1 style="font-size: 18px; font-family: sans-serif; font-weight: bold; text-transform: uppercase; margin: 0 0 5px 0; color: #0f172a; letter-spacing: 0.5px;">
          ${title}
        </h1>
        <p style="font-size: 10px; font-family: sans-serif; text-transform: uppercase; letter-spacing: 1px; color: #64748b; margin: 0 0 5px 0; font-weight: bold;">
          Tech4Biz Technology Integration Portal
        </p>
        <p style="font-size: 9px; font-family: monospace; color: #64748b; margin: 0; font-weight: bold;">
          REF: T4B-${type}-${company.toUpperCase().replace(/[^A-Z0-9]/g, "-")}-2026
        </p>
      </div>

      ${bodyContent}

      <div style="margin-top: 40px; border-top: 1px solid #cbd5e1; padding-top: 20px;">
        <p style="font-size: 9px; text-transform: uppercase; color: #475569; font-family: sans-serif; font-weight: bold; margin-bottom: 20px; text-align: center; letter-spacing: 1px;">
          IN WITNESS WHEREOF, the Parties have executed this Agreement as of the dates indicated below.
        </p>
        <table style="width: 100%; border-collapse: collapse; font-family: sans-serif; font-size: 10px;">
          <tr>
            <td style="width: 45%; vertical-align: top; padding-right: 20px;">
              <p style="font-weight: bold; color: #0f172a; border-bottom: 1px solid #e2e8f0; padding-bottom: 4px; margin: 0 0 8px 0; text-transform: uppercase; letter-spacing: 0.5px;">
                For: Tech4Biz Solutions Inc.
              </p>
              <div style="height: 50px; border-bottom: 1px solid #94a3b8; margin-bottom: 8px; display: flex; align-items: flex-end; padding-bottom: 2px;">
                <span style="font-family: Georgia, serif; font-style: italic; font-size: 14px; color: #5c9c37; font-weight: bold;">Yasha Khandelwal</span>
              </div>
              <p style="margin: 2px 0; color: #475569;"><strong>Name:</strong> Yasha Khandelwal</p>
              <p style="margin: 2px 0; color: #475569;"><strong>Title:</strong> CEO</p>
              <p style="margin: 2px 0; color: #475569;"><strong>Date:</strong> January 1, 2026</p>
            </td>
            <td style="width: 10%;"></td>
            <td style="width: 45%; vertical-align: top; padding-left: 20px;">
              <p style="font-weight: bold; color: #0f172a; border-bottom: 1px solid #e2e8f0; padding-bottom: 4px; margin: 0 0 8px 0; text-transform: uppercase; letter-spacing: 0.5px;">
                For: ${company.toUpperCase()}
              </p>
              <div style="height: 50px; border-bottom: 1px solid #94a3b8; margin-bottom: 8px; display: flex; align-items: flex-end; justify-content: center; padding-bottom: 2px;">
                ${
                  signature
                    ? `<img src="${signature}" style="max-height: 40px; max-width: 100%; object-fit: contain;" />`
                    : `<span style="font-size: 9px; color: #94a3b8; font-style: italic; margin-bottom: 5px;">[Awaiting Signature]</span>`
                }
              </div>
              <p style="margin: 2px 0; color: #475569;"><strong>Name:</strong> Authorized Representative</p>
              <p style="margin: 2px 0; color: #475569;"><strong>Title:</strong> Corporate Designee</p>
              <p style="margin: 2px 0; color: #475569;"><strong>Date:</strong> ${formattedDate}</p>
            </td>
          </tr>
        </table>
      </div>
    `;

    const opt = {
      margin:       15,
      filename:     `${company.toLowerCase().replace(/[^a-z0-9]/g, "-")}-${type.toLowerCase()}-agreement.pdf`,
      image:        { type: 'jpeg', quality: 0.98 },
      html2canvas:  { scale: 2.5, useCORS: true },
      jsPDF:        { unit: 'mm', format: 'a4', orientation: 'portrait' }
    };

    html2pdf().from(element).set(opt).save();
  };

  const fetchClients = async () => {
    setLoading(true);
    try {
      const response = await apiClient.get<User[]>("/admin/clients");
      setClients(response.data);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchClients();
  }, []);

  const handleUpdateStatus = async (
    clientId: string,
    newStatus: "APPROVED" | "REJECTED",
  ) => {
    setProcessingId(clientId);
    try {
      await apiClient.put(`/admin/clients/${clientId}`, { status: newStatus });
      setClients((prev) =>
        prev.map((c) =>
          c.id === clientId ? { ...c, onboardingStatus: newStatus } : c,
        ),
      );
      if (selectedClient?.id === clientId) {
        setSelectedClient((prev) =>
          prev ? { ...prev, onboardingStatus: newStatus } : null,
        );
      }
    } catch (err) {
      console.error(err);
    } finally {
      setProcessingId(null);
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-bold text-ink-800">
            Client Onboarding Approvals
          </h2>
          <p className="text-sm text-ink-600">
            Review and authorize client portal access requests, legal NDA, and
            MSA agreements.
          </p>
        </div>
        <span className="rounded-lg bg-warning/10 px-3 py-1 text-xs font-semibold text-warning border border-warning/20">
          {
            clients.filter((c) => c.onboardingStatus === "PENDING_APPROVAL")
              .length
          }{" "}
          Pending Review
        </span>
      </div>

      <div className="grid gap-6 lg:grid-cols-3">
        {/* Table/List */}
        <div className="lg:col-span-2 rounded-xl border border-ink-100 bg-white p-4 shadow-sm space-y-4">
          <h3 className="text-xs font-bold uppercase tracking-wider text-ink-600">
            Client Accounts
          </h3>
          {loading ? (
            <div className="space-y-3 py-4">
              {[1, 2].map((n) => (
                <div
                  key={n}
                  className="h-16 animate-pulse rounded-lg bg-ink-50"
                />
              ))}
            </div>
          ) : clients.length === 0 ? (
            <div className="py-8 text-center text-sm text-ink-600">
              No client accounts found.
            </div>
          ) : (
            <div className="divide-y divide-ink-100">
              {clients.map((client) => (
                <div
                  key={client.id}
                  className={`flex items-center justify-between py-3.5 first:pt-0 last:pb-0 transition-colors ${
                    selectedClient?.id === client.id ? "bg-primary-50/20" : ""
                  }`}
                >
                  <div className="space-y-1.5">
                    <div className="flex items-center gap-2">
                      <p className="text-sm font-bold text-ink-800">
                        {client.companyName || "Incomplete Profile"}
                      </p>
                      <span className="text-xs font-semibold text-ink-600 font-mono">
                        ({client.email})
                      </span>
                    </div>
                    <div className="flex items-center gap-3 text-xs text-ink-600">
                      <span className="flex items-center gap-1">
                        <Building2 className="h-3.5 w-3.5" />
                        {client.sector || "N/A"}
                      </span>
                      <span className="flex items-center gap-1">
                        <Calendar className="h-3.5 w-3.5" />
                        Joined: {client.createdAt.split("T")[0]}
                      </span>
                    </div>
                  </div>

                  <div className="flex items-center gap-2.5">
                    {/* Status Badge */}
                    <span
                      className={`rounded px-2.5 py-1 text-[10px] font-bold uppercase tracking-wider border ${
                        client.onboardingStatus === "APPROVED"
                          ? "bg-success/10 text-success border-success/20"
                          : client.onboardingStatus === "REJECTED"
                            ? "bg-danger/10 text-danger border-danger/20"
                            : client.onboardingStatus === "PENDING_APPROVAL"
                              ? "bg-warning/10 text-warning border-warning/20 animate-pulse"
                              : "bg-ink-100 text-ink-600 border-ink-200"
                      }`}
                    >
                      {client.onboardingStatus.replace("_", " ")}
                    </span>

                    {/* Review Button */}
                    <button
                      onClick={() => setSelectedClient(client)}
                      className="rounded-lg border border-ink-200 bg-white p-2 text-ink-600 hover:text-ink-800 hover:bg-ink-50 transition-colors"
                      title="Review Agreements"
                    >
                      <Eye className="h-4 w-4" />
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Details Panel */}
        <div className="rounded-xl border border-ink-100 bg-white p-5 shadow-sm space-y-6">
          <h3 className="text-xs font-bold uppercase tracking-wider text-ink-600">
            Detail Inspector
          </h3>
          {selectedClient ? (
            <div className="space-y-6">
              {/* Profile Details */}
              <div className="space-y-3">
                <h4 className="text-base font-bold text-ink-800">
                  {selectedClient.companyName}
                </h4>
                <div className="space-y-2 text-xs text-ink-700">
                  <div className="flex justify-between border-b border-ink-50 pb-1.5">
                    <span className="text-ink-600 font-medium">Domain:</span>
                    <span className="font-semibold">
                      {selectedClient.sector}
                    </span>
                  </div>
                  <div className="flex justify-between border-b border-ink-50 pb-1.5">
                    <span className="text-ink-600 font-medium">
                      Company Size:
                    </span>
                    <span className="font-semibold">
                      {selectedClient.companySize}
                    </span>
                  </div>
                  <div className="flex justify-between border-b border-ink-50 pb-1.5">
                    <span className="text-ink-600 font-medium">Website:</span>
                    <a
                      href={selectedClient.website}
                      target="_blank"
                      rel="noreferrer"
                      className="font-semibold text-primary-700 hover:underline flex items-center gap-1"
                    >
                      <Globe className="h-3 w-3" />
                      Link
                    </a>
                  </div>
                  <div className="flex justify-between border-b border-ink-50 pb-1.5">
                    <span className="text-ink-600 font-medium">
                      Email Address:
                    </span>
                    <span className="font-semibold">
                      {selectedClient.email}
                    </span>
                  </div>
                </div>
              </div>

              {/* Signature Blocks */}
              <div className="space-y-3 pt-2 border-t border-ink-100">
                <h5 className="text-xs font-bold uppercase tracking-wider text-ink-600">
                  Agreement Signatures
                </h5>
                <div className="grid grid-cols-2 gap-3">
                  {/* NDA Signature */}
                  <div className="rounded-lg border border-ink-100 bg-ink-50 p-2.5 flex flex-col items-center">
                    <span className="text-[10px] font-bold text-ink-600 mb-2">
                      NDA Signature
                    </span>
                    {selectedClient.ndaSignature ? (
                      <>
                        <div className="bg-white rounded p-1.5 border border-ink-100 w-full flex justify-center mb-2">
                          <img
                            src={selectedClient.ndaSignature.dataUrl}
                            alt="NDA Sign"
                            className="h-10 object-contain mix-blend-multiply"
                          />
                        </div>
                        <div className="flex gap-1.5 w-full">
                          <button
                            type="button"
                            onClick={() =>
                              setViewingDoc({
                                title: "Mutual Non-Disclosure Agreement (NDA)",
                                type: "NDA",
                                company:
                                  selectedClient.companyName ||
                                  selectedClient.email ||
                                  "Client",
                                signature: selectedClient.ndaSignature?.dataUrl,
                                date: selectedClient.ndaSignature?.date,
                              })
                            }
                            className="flex-1 py-1 rounded bg-white border border-ink-200 text-[10px] font-bold text-ink-700 hover:bg-ink-100 hover:text-ink-900 transition-colors flex items-center justify-center gap-0.5 cursor-pointer"
                          >
                            <Eye className="w-3 h-3" /> View
                          </button>
                          <button
                            type="button"
                            onClick={() =>
                              downloadDocument(
                                "NDA",
                                selectedClient.companyName ||
                                  selectedClient.email ||
                                  "Client",
                                selectedClient.ndaSignature?.dataUrl,
                                selectedClient.ndaSignature?.date,
                              )
                            }
                            className="flex-1 py-1 rounded bg-primary-400 text-[10px] font-bold text-ink-800 hover:bg-primary-300 transition-premium shadow-sm flex items-center justify-center gap-0.5 cursor-pointer"
                          >
                            <Download className="w-3 h-3" /> Get
                          </button>
                        </div>
                      </>
                    ) : (
                      <>
                        <span className="text-[10px] italic text-danger flex items-center gap-1 my-3">
                          <ShieldAlert className="h-3.5 w-3.5" />
                          Unsigned
                        </span>
                        <button
                          type="button"
                          onClick={() =>
                            setViewingDoc({
                              title: "Mutual Non-Disclosure Agreement (NDA)",
                              type: "NDA",
                              company:
                                selectedClient.companyName ||
                                selectedClient.email ||
                                "Client",
                            })
                          }
                          className="w-full py-1.5 rounded bg-white border border-ink-200 text-[10px] font-bold text-ink-600 hover:bg-ink-100 transition-colors flex items-center justify-center gap-0.5 cursor-pointer"
                        >
                          <Eye className="w-3 h-3" /> View Template
                        </button>
                      </>
                    )}
                  </div>

                  {/* MSA Signature */}
                  <div className="rounded-lg border border-ink-100 bg-ink-50 p-2.5 flex flex-col items-center">
                    <span className="text-[10px] font-bold text-ink-600 mb-2">
                      MSA Signature
                    </span>
                    {selectedClient.msaSignature ? (
                      <>
                        <div className="bg-white rounded p-1.5 border border-ink-100 w-full flex justify-center mb-2">
                          <img
                            src={selectedClient.msaSignature.dataUrl}
                            alt="MSA Sign"
                            className="h-10 object-contain mix-blend-multiply"
                          />
                        </div>
                        <div className="flex gap-1.5 w-full">
                          <button
                            type="button"
                            onClick={() =>
                              setViewingDoc({
                                title: "Master Services Agreement (MSA)",
                                type: "MSA",
                                company:
                                  selectedClient.companyName ||
                                  selectedClient.email ||
                                  "Client",
                                signature: selectedClient.msaSignature?.dataUrl,
                                date: selectedClient.msaSignature?.date,
                              })
                            }
                            className="flex-1 py-1 rounded bg-white border border-ink-200 text-[10px] font-bold text-ink-700 hover:bg-ink-100 hover:text-ink-900 transition-colors flex items-center justify-center gap-0.5 cursor-pointer"
                          >
                            <Eye className="w-3 h-3" /> View
                          </button>
                          <button
                            type="button"
                            onClick={() =>
                              downloadDocument(
                                "MSA",
                                selectedClient.companyName ||
                                  selectedClient.email ||
                                  "Client",
                                selectedClient.msaSignature?.dataUrl,
                                selectedClient.msaSignature?.date,
                              )
                            }
                            className="flex-1 py-1 rounded bg-primary-400 text-[10px] font-bold text-ink-800 hover:bg-primary-300 transition-premium shadow-sm flex items-center justify-center gap-0.5 cursor-pointer"
                          >
                            <Download className="w-3 h-3" /> Get
                          </button>
                        </div>
                      </>
                    ) : (
                      <>
                        <span className="text-[10px] italic text-danger flex items-center gap-1 my-3">
                          <ShieldAlert className="h-3.5 w-3.5" />
                          Unsigned
                        </span>
                        <button
                          type="button"
                          onClick={() =>
                            setViewingDoc({
                              title: "Master Services Agreement (MSA)",
                              type: "MSA",
                              company:
                                selectedClient.companyName ||
                                selectedClient.email ||
                                "Client",
                            })
                          }
                          className="w-full py-1.5 rounded bg-white border border-ink-200 text-[10px] font-bold text-ink-600 hover:bg-ink-100 transition-colors flex items-center justify-center gap-0.5 cursor-pointer"
                        >
                          <Eye className="w-3 h-3" /> View Template
                        </button>
                      </>
                    )}
                  </div>
                </div>
              </div>

              {/* Action buttons */}
              {selectedClient.onboardingStatus === "PENDING_APPROVAL" && (
                <div className="grid grid-cols-2 gap-3 pt-4 border-t border-ink-100">
                  <button
                    onClick={() =>
                      handleUpdateStatus(selectedClient.id, "REJECTED")
                    }
                    disabled={processingId === selectedClient.id}
                    className="flex items-center justify-center gap-1.5 rounded-lg border border-danger/30 text-danger bg-danger/5 hover:bg-danger/10 px-4 py-2.5 text-xs font-semibold transition-colors disabled:opacity-50"
                  >
                    <X className="h-4 w-4" />
                    Reject Application
                  </button>
                  <button
                    onClick={() =>
                      handleUpdateStatus(selectedClient.id, "APPROVED")
                    }
                    disabled={processingId === selectedClient.id}
                    className="flex items-center justify-center gap-1.5 rounded-lg bg-primary-400 text-ink-800 hover:bg-primary-300 px-4 py-2.5 text-xs font-semibold transition-premium shadow-premium disabled:opacity-50"
                  >
                    <Check className="h-4 w-4" />
                    Approve Client
                  </button>
                </div>
              )}

              {selectedClient.onboardingStatus === "APPROVED" && (
                <div className="bg-success/5 border border-success/20 rounded-lg p-3 flex items-center gap-2 text-success">
                  <FileCheck2 className="h-5 w-5" />
                  <span className="text-xs font-bold">
                    Client approved! Documents unlocked for signing.
                  </span>
                </div>
              )}

              {selectedClient.onboardingStatus === "REJECTED" && (
                <div className="bg-danger/5 border border-danger/20 rounded-lg p-3 flex items-center gap-2 text-danger">
                  <X className="h-5 w-5" />
                  <span className="text-xs font-bold">
                    Client application has been rejected.
                  </span>
                </div>
              )}
            </div>
          ) : (
            <div className="py-12 text-center text-xs text-ink-600 italic">
              Select a client from the queue to view their documents and
              signatures.
            </div>
          )}
        </div>
      </div>
      {viewingDoc && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-ink-900/60 backdrop-blur-sm">
          <div className="relative w-full max-w-4xl bg-white rounded-2xl shadow-2xl overflow-hidden border border-ink-100 flex flex-col max-h-[90vh]">
            {/* Header */}
            <div className="p-4 border-b border-ink-100 flex justify-between items-center bg-ink-50">
              <h3 className="text-sm font-bold text-ink-800">
                Document Viewer: {viewingDoc.title}
              </h3>
              <button
                onClick={() => setViewingDoc(null)}
                className="p-1.5 rounded-lg border border-ink-200 bg-white hover:bg-ink-100 text-ink-600 hover:text-ink-800 transition-colors text-xs font-semibold flex items-center gap-1 cursor-pointer"
              >
                <X className="w-4 h-4" /> Close
              </button>
            </div>

            {/* Content */}
            <div className="flex-1 overflow-y-auto p-6 bg-ink-50">
              <DocumentPreview
                title={viewingDoc.title}
                documentType={viewingDoc.type}
                companyName={viewingDoc.company}
                signatureDataUrl={viewingDoc.signature}
                signatureDate={viewingDoc.date}
              />
            </div>

            {/* Footer */}
            <div className="p-4 border-t border-ink-100 flex justify-end gap-3 bg-white">
              <button
                type="button"
                onClick={() => {
                  downloadDocument(
                    viewingDoc.type,
                    viewingDoc.company,
                    viewingDoc.signature,
                    viewingDoc.date,
                  );
                }}
                className="px-4 py-2 rounded-xl bg-primary-400 text-xs font-bold text-ink-800 hover:bg-primary-300 transition-premium shadow-premium flex items-center gap-1.5 cursor-pointer"
              >
                <Download className="w-4 h-4" /> Download PDF Agreement
              </button>
              <button
                type="button"
                onClick={() => setViewingDoc(null)}
                className="px-4 py-2 rounded-xl border border-ink-200 bg-white text-xs font-bold text-ink-700 hover:bg-ink-50 transition-colors cursor-pointer"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
