import React, { useState } from 'react';
import { Shield, FileText, CheckCircle, Clock, Download, ExternalLink, RefreshCw } from 'lucide-react';
import { useAuthStore } from '../hooks/use-auth';
import { useMyAcceptancesQuery } from '../hooks/use-legal-query';
import PageHeader from '../components/ui/PageHeader';
import Button from '../components/ui/Button';
import { PageLayout } from '../components/layout/PageLayout';
import Modal from '../components/ui/Modal';

export const ClientAgreementsPage: React.FC = () => {
  const user = useAuthStore((state) => state.user);
  const { data: acceptances, isLoading, refetch, isFetching } = useMyAcceptancesQuery();
  const [selectedDoc, setSelectedDoc] = useState<'NDA' | 'MSA' | null>(null);

  const ndaAcceptance = acceptances?.find(a => a.document.type === 'NDA');
  const msaAcceptance = acceptances?.find(a => a.document.type === 'MSA');

  const fileHost = (import.meta.env.VITE_API_URL || '/api/v1').replace('/api/v1', '');

  // Header component
  const headerNode = (
    <PageHeader
      title="Compliance & Legal Agreements"
      subtitle="Review and download your signed partnership agreements and compliance certificates."
      badge={
        <div className="flex items-center gap-1.5 px-2.5 py-0.5 rounded-full bg-emerald-50 border border-emerald-200 text-[10px] font-bold text-emerald-800 tracking-wider uppercase shrink-0">
          <Shield className="w-3.5 h-3.5" />
          <span>Compliance Certified</span>
        </div>
      }
    />
  );

  // Toolbar component
  const toolbarNode = (
    <div className="flex items-center justify-between p-3.5 bg-ink-0 border border-ink-200 rounded-xl shadow-sm">
      <div className="flex items-center gap-2">
        <span className="text-xs font-semibold text-ink-500">Last audited: today</span>
      </div>
      <button
        onClick={() => refetch()}
        disabled={isFetching}
        className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-ink-200 bg-ink-0 text-xs font-bold text-ink-700 hover:bg-ink-50 transition-all cursor-pointer disabled:opacity-50"
      >
        <RefreshCw className={`w-3.5 h-3.5 ${isFetching ? 'animate-spin' : ''}`} />
        <span>Sync Ledger</span>
      </button>
    </div>
  );

  const activeDocData = selectedDoc === 'NDA' ? ndaAcceptance : msaAcceptance;

  return (
    <PageLayout header={headerNode} toolbar={toolbarNode}>
      <div className="p-5 flex-1 min-h-0 overflow-y-auto flex flex-col gap-6">
        {isLoading ? (
          <div className="flex flex-col items-center justify-center py-20 flex-1">
            <RefreshCw className="w-8 h-8 text-ink-900 animate-spin mb-3" />
            <span className="text-sm font-semibold text-ink-500">Querying compliance ledger...</span>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* NDA Card */}
            <div className="bg-ink-0 border border-ink-200 rounded-2xl p-5 shadow-sm flex flex-col justify-between hover:border-ink-400 transition-all duration-300">
              <div>
                <div className="flex items-center justify-between mb-4">
                  <div className="w-10 h-10 rounded-xl bg-ink-900 text-ink-0 flex items-center justify-center">
                    <FileText className="w-5 h-5" />
                  </div>
                  {ndaAcceptance ? (
                    <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-bold bg-emerald-50 text-emerald-700 border border-emerald-250">
                      <CheckCircle className="w-3.5 h-3.5" />
                      Signed & Active
                    </span>
                  ) : (
                    <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-bold bg-amber-50 text-amber-700 border border-amber-250">
                      <Clock className="w-3.5 h-3.5" />
                      Pending Action
                    </span>
                  )}
                </div>

                <h3 className="text-base agreement-card-title font-extrabold text-ink-900">Mutual Non-Disclosure Agreement (NDA)</h3>
                <p className="text-xs agreement-card-desc text-ink-500 mt-1.5 leading-relaxed font-semibold">
                  Required to protect proprietary IP, silicon designs, and private data sharing during development.
                </p>

                {ndaAcceptance && (
                  <div className="mt-4 pt-4 border-t border-ink-100 space-y-2.5">
                    <div className="flex justify-between items-center text-xs">
                      <span className="font-semibold text-ink-500">Document Version</span>
                      <span className="font-bold text-ink-900">v{ndaAcceptance.document.version}</span>
                    </div>
                    <div className="flex justify-between items-center text-xs">
                      <span className="font-semibold text-ink-500">Accepted On</span>
                      <span className="font-bold text-ink-900">{new Date(ndaAcceptance.acceptedAt).toLocaleDateString()}</span>
                    </div>
                    <div className="flex justify-between items-center text-xs">
                      <span className="font-semibold text-ink-500">Signing IP</span>
                      <span className="font-mono text-ink-900 font-bold">{ndaAcceptance.ipAddress}</span>
                    </div>
                    <div className="flex flex-col gap-1 text-xs pt-1">
                      <span className="font-semibold text-ink-400 uppercase text-[9px] tracking-wider">Verification Hash</span>
                      <span className="font-mono text-[10px] text-ink-650 bg-ink-50 p-1.5 rounded border border-ink-150 break-all">
                        {ndaAcceptance.signatureHash || 'N/A'}
                      </span>
                    </div>
                  </div>
                )}
              </div>

              {ndaAcceptance && (
                <div className="mt-6 pt-4 border-t border-ink-100 flex gap-3">
                  <Button
                    onClick={() => setSelectedDoc('NDA')}
                    variant="secondary"
                    size="sm"
                    className="flex-1 justify-center"
                    icon={<ExternalLink className="w-3.5 h-3.5" />}
                  >
                    View Document
                  </Button>
                  {ndaAcceptance.documentUrl && (
                    <a
                      href={`${fileHost}${ndaAcceptance.documentUrl}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="inline-flex items-center justify-center p-2 rounded-lg border border-ink-200 bg-ink-0 text-ink-700 hover:bg-ink-50 hover:border-ink-300 transition-all shadow-sm"
                      title="Download PDF"
                    >
                      <Download className="w-4 h-4" />
                    </a>
                  )}
                </div>
              )}
            </div>

            {/* MSA Card */}
            <div className="bg-ink-0 border border-ink-200 rounded-2xl p-5 shadow-sm flex flex-col justify-between hover:border-ink-400 transition-all duration-300">
              <div>
                <div className="flex items-center justify-between mb-4">
                  <div className="w-10 h-10 rounded-xl bg-ink-900 text-ink-0 flex items-center justify-center">
                    <FileText className="w-5 h-5" />
                  </div>
                  {msaAcceptance ? (
                    <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-bold bg-emerald-50 text-emerald-700 border border-emerald-250">
                      <CheckCircle className="w-3.5 h-3.5" />
                      Signed & Active
                    </span>
                  ) : (
                    <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-bold bg-amber-50 text-amber-700 border border-amber-250">
                      <Clock className="w-3.5 h-3.5" />
                      Pending Action
                    </span>
                  )}
                </div>

                <h3 className="text-base agreement-card-title font-extrabold text-ink-900">Master Services Agreement (MSA)</h3>
                <p className="text-xs agreement-card-desc text-ink-500 mt-1.5 leading-relaxed font-semibold">
                  Defines the commercial framework, SLA guidelines, and consulting provisions for the partnership.
                </p>

                {msaAcceptance && (
                  <div className="mt-4 pt-4 border-t border-ink-100 space-y-2.5">
                    <div className="flex justify-between items-center text-xs">
                      <span className="font-semibold text-ink-500">Document Version</span>
                      <span className="font-bold text-ink-900">v{msaAcceptance.document.version}</span>
                    </div>
                    <div className="flex justify-between items-center text-xs">
                      <span className="font-semibold text-ink-500">Accepted On</span>
                      <span className="font-bold text-ink-900">{new Date(msaAcceptance.acceptedAt).toLocaleDateString()}</span>
                    </div>
                    <div className="flex justify-between items-center text-xs">
                      <span className="font-semibold text-ink-500">Signing IP</span>
                      <span className="font-mono text-ink-900 font-bold">{msaAcceptance.ipAddress}</span>
                    </div>
                    <div className="flex flex-col gap-1 text-xs pt-1">
                      <span className="font-semibold text-ink-400 uppercase text-[9px] tracking-wider">Verification Hash</span>
                      <span className="font-mono text-[10px] text-ink-650 bg-ink-50 p-1.5 rounded border border-ink-150 break-all">
                        {msaAcceptance.signatureHash || 'N/A'}
                      </span>
                    </div>
                  </div>
                )}
              </div>

              {msaAcceptance && (
                <div className="mt-6 pt-4 border-t border-ink-100 flex gap-3">
                  <Button
                    onClick={() => setSelectedDoc('MSA')}
                    variant="secondary"
                    size="sm"
                    className="flex-1 justify-center"
                    icon={<ExternalLink className="w-3.5 h-3.5" />}
                  >
                    View Document
                  </Button>
                  {msaAcceptance.documentUrl && (
                    <a
                      href={`${fileHost}${msaAcceptance.documentUrl}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="inline-flex items-center justify-center p-2 rounded-lg border border-ink-200 bg-ink-0 text-ink-700 hover:bg-ink-50 hover:border-ink-300 transition-all shadow-sm"
                      title="Download PDF"
                    >
                      <Download className="w-4 h-4" />
                    </a>
                  )}
                </div>
              )}
            </div>
          </div>
        )}
      </div>

      {/* Document Viewer Modal */}
      <Modal
        isOpen={selectedDoc !== null}
        onClose={() => setSelectedDoc(null)}
        title={selectedDoc === 'NDA' ? 'Non-Disclosure Agreement (NDA)' : 'Master Services Agreement (MSA)'}
        subtitle={activeDocData ? `Version ${activeDocData.document.version} — Cryptographically signed` : ''}
        size="lg"
      >
        {activeDocData && (
          <div className="space-y-6">
            {activeDocData.documentUrl ? (
              <div className="w-full h-[600px] border border-ink-200 rounded-xl overflow-hidden shadow-sm">
                {activeDocData.documentUrl.toLowerCase().endsWith('.pdf') ? (
                  <iframe
                    src={`${fileHost}${activeDocData.documentUrl}`}
                    title="Signed Document"
                    className="w-full h-full border-0 bg-white"
                  />
                ) : (
                  <div className="w-full h-full flex items-center justify-center bg-ink-50 overflow-auto p-4">
                    <img
                      src={`${fileHost}${activeDocData.documentUrl}`}
                      alt="Signed Document"
                      className="max-w-full max-h-full object-contain shadow-md rounded border border-ink-200"
                    />
                  </div>
                )}
              </div>
            ) : (
              <div className="space-y-6">
                <div className="max-h-[450px] overflow-y-auto p-4 bg-ink-50 rounded-xl border border-ink-200 font-serif text-sm leading-relaxed text-ink-800 whitespace-pre-line">
                  {activeDocData.document.content}
                </div>
                <div className="p-4 border border-emerald-500 bg-emerald-500/5 rounded-xl space-y-2 text-xs">
                  <h4 className="font-bold text-emerald-800 tracking-wider uppercase">Signature Verification Ledger</h4>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-ink-700">
                    <p><strong>Signed By:</strong> {user?.email}</p>
                    <p><strong>Signed On:</strong> {new Date(activeDocData.acceptedAt).toLocaleString()}</p>
                    <p><strong>IP Address:</strong> {activeDocData.ipAddress}</p>
                    <p className="sm:col-span-2"><strong>Verification Hash:</strong> <span className="font-mono text-[10px] break-all">{activeDocData.signatureHash}</span></p>
                  </div>
                </div>
              </div>
            )}

            <div className="flex justify-end gap-3 pt-4 border-t border-ink-100">
              <Button variant="secondary" onClick={() => setSelectedDoc(null)}>
                Close
              </Button>
              {activeDocData.documentUrl ? (
                <a
                  href={`${fileHost}${activeDocData.documentUrl}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center gap-1.5 rounded-lg bg-ink-900 px-4 py-2 text-xs font-semibold text-ink-0 hover:bg-ink-800 transition-all shadow-sm"
                >
                  <Download className="w-4 h-4" />
                  <span>Download Signed PDF</span>
                </a>
              ) : (
                <Button
                  onClick={() => {
                    const element = document.createElement("a");
                    const file = new Blob([
                      `${selectedDoc === 'NDA' ? 'Non-Disclosure Agreement (NDA)' : 'Master Services Agreement (MSA)'}\n\n`,
                      activeDocData.document.content,
                      `\n\n=== DIGITAL SIGNATURE ===\n`,
                      `Signed By: ${user?.email}\n`,
                      `Verification Hash: ${activeDocData.signatureHash || 'N/A'}\n`,
                      `IP Address: ${activeDocData.ipAddress}\n`,
                      `Signed On: ${new Date(activeDocData.acceptedAt).toLocaleString()}\n`
                    ], {type: 'text/plain'});
                    element.href = URL.createObjectURL(file);
                    element.download = `${selectedDoc}_Agreement_${user?.email?.split('@')[0]}.txt`;
                    document.body.appendChild(element);
                    element.click();
                    document.body.removeChild(element);
                  }}
                  variant="primary"
                  icon={<Download className="w-4 h-4" />}
                >
                  Download Signed Copy
                </Button>
              )}
            </div>
          </div>
        )}
      </Modal>
    </PageLayout>
  );
};

export default ClientAgreementsPage;
