import React, { useState } from "react";
import { CheckCircle, Clock, Search, XCircle, Eye } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
import { usePendingPartnersQuery } from "../../hooks/use-legal-query";
import { useApprovePartnerMutation } from "../../hooks/use-legal-mutation";
import PageHeader from "../../components/ui/PageHeader";
import Button from "../../components/ui/Button";
import { useToast } from "../../hooks/use-toast";
import { DocumentPreviewModal } from "../../components/ui/DocumentPreviewModal";
import { PageLayout } from "../../components/layout/PageLayout";

export const ApprovalsPage: React.FC = () => {
  const { success, error } = useToast();
  const { data: partners = [], isLoading } = usePendingPartnersQuery();
  const approveMutation = useApprovePartnerMutation();
  const [searchTerm, setSearchTerm] = useState("");

  // Preview Modal state
  const [selectedPartner, setSelectedPartner] = useState<any | null>(null);
  const [isPreviewOpen, setIsPreviewOpen] = useState(false);
  const [verifiedDocs, setVerifiedDocs] = useState<
    Record<string, { nda: boolean; msa: boolean }>
  >({});

  const approvePartner = (partnerId: string, email: string) => {
    approveMutation.mutate(partnerId, {
      onSuccess: () => {
        success(
          "Partner access approved",
          `Access has been granted to ${email}.`,
        );
        setIsPreviewOpen(false);
        setSelectedPartner(null);
      },
      onError: (err: any) => {
        error(
          "Approval failed",
          err.response?.data?.error || "Could not approve partner access.",
        );
      },
    });
  };

  const handleOpenPreview = (partner: any, _docType: "NDA" | "MSA") => {
    setSelectedPartner(partner);
    setIsPreviewOpen(true);
  };

  const handleVerify = (partnerId: string, docType: "NDA" | "MSA") => {
    setVerifiedDocs((prev) => {
      const partnerStatus = prev[partnerId] || { nda: false, msa: false };
      return {
        ...prev,
        [partnerId]: {
          ...partnerStatus,
          [docType === "NDA" ? "nda" : "msa"]: true,
        },
      };
    });
    success(
      `${docType} document signature verified.`,
      "Verification status updated.",
    );
  };

  const filteredPartners = partners.filter((p) =>
    p.email.toLowerCase().includes(searchTerm.toLowerCase()),
  );

  if (isLoading) {
    return (
      <div className="flex-1 flex items-center justify-center min-h-[60vh]">
        <div className="w-8 h-8 border-4 border-ink-900/30 border-t-ink-900 rounded-full animate-spin" />
      </div>
    );
  }

  // Header component
  const headerNode = (
    <PageHeader
      title="Approvals Queue"
      subtitle="Review and approve partner legal documents to grant platform access."
    />
  );

  // Toolbar component
  const toolbarNode = (
    <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3.5 p-3.5 bg-ink-0 border border-ink-200 rounded-xl shadow-sm">
      <div className="flex items-center gap-2 flex-1 max-w-md">
        <div className="relative flex-1">
          <Search className="w-4 h-4 text-ink-400 absolute left-3 top-1/2 -translate-y-1/2" />
          <input
            type="text"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            placeholder="Search pending partners by email..."
            className="w-full pl-9 pr-4 py-1.5 bg-ink-50 border border-ink-200 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-ink-900/10 text-ink-900 placeholder-ink-400 font-semibold"
          />
        </div>
      </div>
    </div>
  );

  return (
    <PageLayout header={headerNode} toolbar={toolbarNode}>
      {/* List Container */}
      <div className="flex-1 w-full overflow-x-auto">
        <table className="w-full text-left text-sm whitespace-nowrap">
          <thead className="bg-ink-50 border-b border-ink-200 text-ink-500 font-bold uppercase tracking-wider text-xs sticky top-0 z-10">
            <tr>
              <th className="px-5 py-3">Partner</th>
              <th className="px-5 py-3">NDA Document</th>
              <th className="px-5 py-3">MSA Document</th>
              <th className="px-5 py-3 text-right">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-ink-200 bg-ink-0">
            <AnimatePresence>
              {filteredPartners.length === 0 ? (
                <tr>
                  <td colSpan={4} className="px-5 py-12 text-center">
                    <div className="w-12 h-12 rounded-full bg-ink-50 flex items-center justify-center mx-auto mb-4 border border-ink-200">
                      <CheckCircle className="w-6 h-6 text-ink-900" />
                    </div>
                    <p className="text-ink-900 font-bold text-sm">
                      Queue is empty
                    </p>
                    <p className="text-ink-500 text-xs mt-1">
                      All partners have been reviewed.
                    </p>
                  </td>
                </tr>
              ) : (
                filteredPartners.map((partner) => {
                  const nda = partner.acceptances.find(
                    (a) => a.document.type === "NDA",
                  );
                  const msa = partner.acceptances.find(
                    (a) => a.document.type === "MSA",
                  );

                  const partnerVerified = verifiedDocs[partner.id] || {
                    nda: false,
                    msa: false,
                  };

                  return (
                    <motion.tr
                      key={partner.id}
                      initial={{ opacity: 1 }}
                      exit={{
                        opacity: 0,
                        x: -20,
                        backgroundColor: "rgba(0, 0, 0, 0.02)",
                      }}
                      className="hover:bg-ink-50 transition-colors group"
                    >
                      <td className="px-5 py-4">
                        <div className="flex items-center gap-3">
                          <div className="w-8 h-8 rounded-full bg-gradient-to-br from-ink-900 to-ink-800 flex items-center justify-center text-ink-0 font-bold text-xs shadow-md">
                            {partner.email.charAt(0).toUpperCase()}
                          </div>
                          <div>
                            <p className="font-bold text-ink-900 text-sm">
                              {partner.email}
                            </p>
                            <p className="text-xs text-ink-500 flex items-center gap-1">
                              <Clock className="w-3 h-3" />
                              {new Date(partner.createdAt).toLocaleDateString()}
                            </p>
                          </div>
                        </div>
                      </td>
                      <td className="px-5 py-4">
                        {nda ? (
                          <div className="flex items-center gap-2">
                            <CheckCircle className="w-4 h-4 text-emerald-600" />
                            <span className="text-xs font-bold text-ink-900 bg-ink-100 border border-ink-200 px-2 py-0.5 rounded-md">
                              {nda.documentUrl
                                ? "Uploaded PDF"
                                : "Digital Sign"}
                            </span>
                             {nda.signatureBase64 && (
                              <div className="w-12 h-6 border border-ink-200 rounded bg-white flex items-center justify-center p-0.5 shadow-sm overflow-hidden shrink-0 ml-1" title="Drawn Signature">
                                <img
                                  src={nda.signatureBase64}
                                  alt="NDA Signature"
                                  className="max-w-full max-h-full object-contain"
                                  style={{ filter: 'brightness(0)' }}
                                />
                              </div>
                            )}
                            <button
                              onClick={() => handleOpenPreview(partner, "NDA")}
                              className="inline-flex items-center gap-1.5 text-xs font-bold text-ink-700 hover:text-ink-900 cursor-pointer ml-2 bg-ink-50 hover:bg-ink-100 border border-ink-200 px-2.5 py-1 rounded-lg transition-all"
                            >
                              <Eye className="w-3.5 h-3.5" />
                              <span>Preview</span>
                            </button>
                            {partnerVerified.nda && (
                              <span className="text-[10px] text-emerald-600 font-bold uppercase tracking-wider ml-1 bg-emerald-50 px-1.5 py-0.5 rounded border border-emerald-200">
                                Verified
                              </span>
                            )}
                          </div>
                        ) : !partner.assignedNdaId ? (
                          <div className="flex items-center gap-2 text-ink-500">
                            <CheckCircle className="w-4 h-4 text-ink-400" />
                            <span className="text-xs font-semibold bg-ink-50 border border-ink-200 text-ink-500 px-2 py-0.5 rounded-md">
                              Not Required
                            </span>
                          </div>
                        ) : (
                          <div className="flex items-center gap-2 text-ink-400">
                            <XCircle className="w-4 h-4" />
                            <span className="text-xs font-bold bg-ink-50 border border-ink-200 text-ink-400 px-2 py-0.5 rounded-md">
                              Missing
                            </span>
                          </div>
                        )}
                      </td>
                      <td className="px-5 py-4">
                        {msa ? (
                          <div className="flex items-center gap-2">
                            <CheckCircle className="w-4 h-4 text-emerald-600" />
                            <span className="text-xs font-bold text-ink-900 bg-ink-100 border border-ink-200 px-2 py-0.5 rounded-md">
                              {msa.documentUrl
                                ? "Uploaded PDF"
                                : "Digital Sign"}
                            </span>
                            {msa.signatureBase64 && (
                              <div className="w-12 h-6 border border-ink-200 rounded bg-white flex items-center justify-center p-0.5 shadow-sm overflow-hidden shrink-0 ml-1" title="Drawn Signature">
                                <img
                                  src={msa.signatureBase64}
                                  alt="MSA Signature"
                                  className="max-w-full max-h-full object-contain"
                                  style={{ filter: 'brightness(0)' }}
                                />
                              </div>
                            )}
                            <button
                              onClick={() => handleOpenPreview(partner, "MSA")}
                              className="inline-flex items-center gap-1.5 text-xs font-bold text-ink-700 hover:text-ink-900 cursor-pointer ml-2 bg-ink-50 hover:bg-ink-100 border border-ink-200 px-2.5 py-1 rounded-lg transition-all"
                            >
                              <Eye className="w-3.5 h-3.5" />
                              <span>Preview</span>
                            </button>
                            {partnerVerified.msa && (
                              <span className="text-[10px] text-emerald-600 font-bold uppercase tracking-wider ml-1 bg-emerald-50 px-1.5 py-0.5 rounded border border-emerald-200">
                                Verified
                              </span>
                            )}
                          </div>
                        ) : !partner.assignedMsaId ? (
                          <div className="flex items-center gap-2 text-ink-500">
                            <CheckCircle className="w-4 h-4 text-ink-400" />
                            <span className="text-xs font-semibold bg-ink-50 border border-ink-200 text-ink-500 px-2 py-0.5 rounded-md">
                              Not Required
                            </span>
                          </div>
                        ) : (
                          <div className="flex items-center gap-2 text-ink-400">
                            <XCircle className="w-4 h-4" />
                            <span className="text-xs font-bold bg-ink-50 border border-ink-200 text-ink-400 px-2 py-0.5 rounded-md">
                              Missing
                            </span>
                          </div>
                        )}
                      </td>
                      <td className="px-5 py-4 text-right">
                        <Button
                          onClick={() =>
                            approvePartner(partner.id, partner.email)
                          }
                          disabled={
                            approveMutation.isPending &&
                            approveMutation.variables === partner.id
                          }
                          variant="primary"
                          size="sm"
                        >
                          {approveMutation.isPending &&
                          approveMutation.variables === partner.id
                            ? "Approving..."
                            : "Approve Access"}
                        </Button>
                      </td>
                    </motion.tr>
                  );
                })
              )}
            </AnimatePresence>
          </tbody>
        </table>
      </div>

      {/* Document Preview Modal */}
      {selectedPartner && (
        <DocumentPreviewModal
          isOpen={isPreviewOpen}
          onClose={() => {
            setIsPreviewOpen(false);
            setSelectedPartner(null);
          }}
          partnerId={selectedPartner.id}
          partnerEmail={selectedPartner.email}
          partnerCreatedAt={selectedPartner.createdAt}
          acceptances={selectedPartner.acceptances}
          verifiedDocs={
            verifiedDocs[selectedPartner.id] || { nda: false, msa: false }
          }
          onVerify={(docType) => handleVerify(selectedPartner.id, docType)}
          onApprovePartner={() =>
            approvePartner(selectedPartner.id, selectedPartner.email)
          }
          isApproving={
            approveMutation.isPending &&
            approveMutation.variables === selectedPartner.id
          }
          assignedNdaId={selectedPartner.assignedNdaId}
          assignedMsaId={selectedPartner.assignedMsaId}
        />
      )}
    </PageLayout>
  );
};

export default ApprovalsPage;
