'use client';
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import dynamic from 'next/dynamic';
import type { DocumentSigner, SignatureFieldData } from '@/lib/db/schema';
import { isClientVisibleField } from '@/lib/db/schema';

// PreviewModal imports react-pdf which calls new DOMMatrix() at module level —
// must be loaded client-only to avoid SSR crash, same pattern as PdfViewer.
const PreviewModal = dynamic(() => import('./PreviewModal').then(m => m.PreviewModal), { ssr: false });

/** Auto-assigned signer color palette (D-01). Cycles if more than 4 signers. */
const SIGNER_COLORS = ['#6366f1', '#f43f5e', '#10b981', '#f59e0b'];

interface PreparePanelProps {
  docId: string;
  defaultEmail: string;
  clientName: string;
  currentStatus: string;
  agentDownloadUrl?: string | null;
  signedAt?: Date | null;
  clientPropertyAddress?: string | null;
  previewToken: string | null;
  onPreviewTokenChange: (token: string | null) => void;
  textFillData: Record<string, string>;
  selectedFieldId: string | null;
  onQuickFill: (fieldId: string, value: string) => void;
  onAiAutoPlace: () => Promise<void>;
  // Multi-signer props — wired in Phase 16 Plan 01, consumed here in Plan 02
  signers?: DocumentSigner[];
  onSignersChange?: (signers: DocumentSigner[]) => void;
  unassignedFieldIds?: Set<string>;
  onUnassignedFieldIdsChange?: (ids: Set<string>) => void;
}

function isValidEmail(email: string): boolean {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

export function PreparePanel({
  docId, defaultEmail, clientName, currentStatus,
  agentDownloadUrl, signedAt, clientPropertyAddress,
  previewToken, onPreviewTokenChange,
  textFillData, selectedFieldId, onQuickFill,
  onAiAutoPlace,
  signers = [],
  onSignersChange,
  onUnassignedFieldIdsChange,
}: PreparePanelProps) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [aiLoading, setAiLoading] = useState(false);
  const [result, setResult] = useState<{ ok: boolean; message: string } | null>(null);
  const [previewBytes, setPreviewBytes] = useState<ArrayBuffer | null>(null);
  const [showPreview, setShowPreview] = useState(false);

  // Signer list local state
  const [signerInput, setSignerInput] = useState('');
  const [signerInputError, setSignerInputError] = useState<string | null>(null);

  async function saveSigners(updated: DocumentSigner[]) {
    onSignersChange?.(updated);
    // Persist immediately so signers survive page refresh
    await fetch(`/api/documents/${docId}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ signers: updated }),
    });
  }

  function handleAddSigner() {
    const email = signerInput.trim().toLowerCase();
    if (!email || !isValidEmail(email)) {
      setSignerInputError('invalid');
      return;
    }
    if (signers.some(s => s.email === email)) {
      setSignerInputError('duplicate');
      return;
    }
    const color = SIGNER_COLORS[signers.length % SIGNER_COLORS.length];
    saveSigners([...signers, { email, color }]);
    setSignerInput('');
    setSignerInputError(null);
  }

  function handleRemoveSigner(email: string) {
    const updated = signers.filter(s => s.email !== email);
    saveSigners(updated);
    onUnassignedFieldIdsChange?.(new Set());
  }

  if (currentStatus === 'Signed') {
    return (
      <div style={{ borderRadius: '0.5rem', border: '1px solid #D1FAE5', padding: '1rem', backgroundColor: '#F0FDF4' }}>
        <p style={{ fontSize: '0.875rem', color: '#065F46', fontWeight: 600, marginBottom: '0.5rem' }}>
          Document Signed
        </p>
        {signedAt && (
          <p style={{ fontSize: '0.75rem', color: '#6B7280', marginBottom: '0.75rem' }}>
            Signed on{' '}
            {new Date(signedAt).toLocaleString('en-US', {
              timeZone: 'America/Denver',
              month: 'short',
              day: 'numeric',
              year: 'numeric',
              hour: 'numeric',
              minute: '2-digit',
            })}
          </p>
        )}
        {agentDownloadUrl ? (
          <a
            href={agentDownloadUrl}
            style={{
              display: 'inline-block',
              padding: '0.5rem 1rem',
              backgroundColor: '#1B2B4B',
              color: '#FFFFFF',
              borderRadius: '0.375rem',
              fontSize: '0.875rem',
              fontWeight: 500,
              textDecoration: 'none',
            }}
          >
            Download Signed PDF
          </a>
        ) : (
          <p style={{ fontSize: '0.75rem', color: '#9CA3AF' }}>Signed PDF not available.</p>
        )}
      </div>
    );
  }

  if (currentStatus !== 'Draft') {
    return (
      <div style={{ borderRadius: '0.5rem', border: '1px solid #E5E7EB', padding: '1rem', backgroundColor: '#F9FAFB', fontSize: '0.875rem', color: '#6B7280' }}>
        Document status is <strong>{currentStatus}</strong> — preparation is only available for Draft documents.
      </div>
    );
  }

  async function handleAiAutoPlaceClick() {
    setAiLoading(true);
    setResult(null);
    try {
      await onAiAutoPlace();
    } catch (e) {
      setResult({ ok: false, message: String(e) });
    } finally {
      setAiLoading(false);
    }
  }

  async function handlePreview() {
    setLoading(true);
    setResult(null);
    try {
      const res = await fetch(`/api/documents/${docId}/preview`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ textFillData }),
      });
      if (res.ok) {
        const bytes = await res.arrayBuffer();
        setPreviewBytes(bytes);
        onPreviewTokenChange(Date.now().toString());
        setShowPreview(true);
      } else {
        const err = await res.json().catch(() => ({ error: 'Preview failed' }));
        setResult({ ok: false, message: err.message ?? err.error ?? 'Preview failed' });
      }
    } catch (e) {
      setResult({ ok: false, message: String(e) });
    } finally {
      setLoading(false);
    }
  }

  async function handlePrepare() {
    setLoading(true);
    setResult(null);

    try {
      // Send-block validation: fetch current fields and check for unassigned client-visible fields
      const fieldsRes = await fetch(`/api/documents/${docId}/fields`);
      const allFields: SignatureFieldData[] = await fieldsRes.json();
      const clientFields = allFields.filter(isClientVisibleField);

      if (signers.length === 0 && clientFields.length > 0) {
        setResult({ ok: false, message: 'Add at least one signer before sending.' });
        setLoading(false);
        return;
      }

      const unassigned = clientFields.filter((f: SignatureFieldData) => !f.signerEmail);
      if (unassigned.length > 0 && signers.length > 0) {
        onUnassignedFieldIdsChange?.(new Set(unassigned.map((f: SignatureFieldData) => f.id)));
        setResult({ ok: false, message: `${unassigned.length} field(s) need a signer assigned before sending.` });
        setLoading(false);
        return;
      }

      // Clear any previous unassigned field highlights
      onUnassignedFieldIdsChange?.(new Set());

      const prepareRes = await fetch(`/api/documents/${docId}/prepare`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ textFillData, signers }),
      });
      if (!prepareRes.ok) {
        const err = await prepareRes.json().catch(() => ({ error: 'Unknown error' }));
        setResult({ ok: false, message: err.error ?? 'Prepare failed' });
      } else {
        const sendRes = await fetch(`/api/documents/${docId}/send`, { method: 'POST' });
        if (!sendRes.ok) {
          const err = await sendRes.json().catch(() => ({ error: 'Unknown error' }));
          setResult({ ok: false, message: `Prepared but email failed: ${err.error ?? 'Unknown error'}` });
        } else {
          setResult({ ok: true, message: 'Document prepared and signing email sent.' });
        }
        router.refresh();
      }
    } catch (e) {
      setResult({ ok: false, message: String(e) });
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="rounded-lg border border-gray-200 bg-gray-100 p-4 space-y-4">
      <h2 className="font-semibold text-gray-900">Prepare Document</h2>


      {/* Quick-fill panel — only shown when a text field is selected */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">Text field fill</label>
        {selectedFieldId ? (
          <div className="space-y-1.5">
            <p className="text-xs text-gray-400">
              Click a suggestion to fill the selected field.
            </p>
            {clientName && (
              <button
                type="button"
                onClick={() => onQuickFill(selectedFieldId, clientName)}
                className="w-full text-left px-3 py-2 text-sm border rounded bg-white hover:bg-blue-50 hover:border-blue-300 transition-colors"
              >
                <span className="text-xs text-gray-400 block">Client Name</span>
                <span className="truncate block">{clientName}</span>
              </button>
            )}
            {clientPropertyAddress && (
              <button
                type="button"
                onClick={() => onQuickFill(selectedFieldId, clientPropertyAddress)}
                className="w-full text-left px-3 py-2 text-sm border rounded bg-white hover:bg-blue-50 hover:border-blue-300 transition-colors"
              >
                <span className="text-xs text-gray-400 block">Property Address</span>
                <span className="truncate block">{clientPropertyAddress}</span>
              </button>
            )}
            <button
              type="button"
              onClick={() => onQuickFill(selectedFieldId, defaultEmail)}
              className="w-full text-left px-3 py-2 text-sm border rounded bg-white hover:bg-blue-50 hover:border-blue-300 transition-colors"
            >
              <span className="text-xs text-gray-400 block">Client Email</span>
              <span className="truncate block">{defaultEmail}</span>
            </button>
          </div>
        ) : (
          <p className="text-sm text-gray-400 italic">
            Click a text field on the document to edit or quick-fill it.
          </p>
        )}
      </div>

      {/* Signer list section — D-02, D-03 */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">Signers</label>
        <div className="flex gap-2">
          <input
            type="email"
            value={signerInput}
            onChange={(e) => { setSignerInput(e.target.value); setSignerInputError(null); }}
            onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); handleAddSigner(); } }}
            placeholder="signer@example.com"
            className={`flex-1 border rounded-md px-2 py-1.5 text-sm ${signerInputError ? 'border-red-400' : 'border-gray-300'}`}
          />
          <button
            type="button"
            onClick={handleAddSigner}
            disabled={signerInput.trim() === ''}
            className="bg-gray-700 text-white px-3 py-1.5 rounded-md text-sm font-medium hover:bg-gray-800 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            Add Signer
          </button>
        </div>
        <p className="text-xs text-gray-400 mt-1">Each signer receives their own signing link.</p>
        {signerInputError === 'invalid' && (
          <p className="text-sm text-red-600 mt-1">Please enter a valid email address.</p>
        )}
        {signerInputError === 'duplicate' && (
          <p className="text-sm text-red-600 mt-1">That email is already in the signer list.</p>
        )}
        {signers.length === 0 ? (
          <p className="text-sm text-gray-400 italic mt-2">No signers added yet.</p>
        ) : (
          <div className="space-y-1.5 mt-2">
            {signers.map(signer => (
              <div key={signer.email} className="flex items-center gap-2 bg-white border border-gray-200 rounded-md py-1 px-2">
                <span className="w-2 h-2 rounded-full flex-shrink-0" style={{ backgroundColor: signer.color }} />
                <span className="flex-1 text-sm text-gray-700 truncate">{signer.email}</span>
                <button
                  type="button"
                  onClick={() => handleRemoveSigner(signer.email)}
                  className="w-8 h-8 flex items-center justify-center text-gray-400 hover:text-red-600 cursor-pointer"
                  style={{ background: 'none', border: 'none', fontSize: '16px', lineHeight: 1 }}
                  aria-label={`Remove signer ${signer.email}`}
                >&#xd7;</button>
              </div>
            ))}
          </div>
        )}
      </div>

      <button
        onClick={handleAiAutoPlaceClick}
        disabled={aiLoading || loading}
        className="w-full py-2 px-4 bg-violet-600 text-white rounded hover:bg-violet-700 disabled:opacity-50 disabled:cursor-not-allowed text-sm font-medium"
        type="button"
      >
        {aiLoading ? 'AI placing fields...' : 'AI Auto-place Fields'}
      </button>

      <button
        onClick={handlePreview}
        disabled={loading}
        className="w-full py-2 px-4 bg-gray-700 text-white rounded hover:bg-gray-800 disabled:opacity-50 disabled:cursor-not-allowed text-sm font-medium"
        type="button"
      >
        {loading ? 'Generating preview...' : previewToken ? 'Preview again' : 'Preview'}
      </button>

      <button
        onClick={handlePrepare}
        disabled={loading || previewToken === null}
        className="w-full py-2 px-4 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed text-sm font-medium"
        type="button"
      >
        {loading ? 'Preparing...' : 'Prepare and Send'}
      </button>

      {result && (
        <p className={`text-sm ${result.ok ? 'text-green-600' : 'text-red-600'}`}>
          {result.message}
        </p>
      )}

      {showPreview && previewBytes && (
        <PreviewModal pdfBytes={previewBytes} onClose={() => setShowPreview(false)} />
      )}
    </div>
  );
}
