'use client';
import { useState, useCallback, useEffect } from 'react';
import { PdfViewerWrapper } from './PdfViewerWrapper';
import { PreparePanel } from './PreparePanel';
import type { DocumentSigner } from '@/lib/db/schema';

interface DocumentPageClientProps {
  docId: string;
  docStatus: string;
  defaultEmail: string;
  clientName: string;
  agentDownloadUrl?: string | null;
  signedAt?: Date | null;
  clientPropertyAddress?: string | null;
  initialSigners: DocumentSigner[];
  /** All people on the client record (primary + co-buyers). Used to auto-seed signers. */
  clientContacts?: { name: string; email: string }[];
}

const SIGNER_COLORS = ['#6366f1', '#f43f5e', '#10b981', '#f59e0b'];

export function DocumentPageClient({
  docId,
  docStatus,
  defaultEmail,
  clientName,
  agentDownloadUrl,
  signedAt,
  clientPropertyAddress,
  initialSigners,
  clientContacts = [],
}: DocumentPageClientProps) {
  const [previewToken, setPreviewToken] = useState<string | null>(null);
  const [selectedFieldId, setSelectedFieldId] = useState<string | null>(null);
  const [textFillData, setTextFillData] = useState<Record<string, string>>({});
  const [aiPlacementKey, setAiPlacementKey] = useState(0);

  // Auto-seed signers from client contacts when no signers have been configured yet
  const defaultSigners: DocumentSigner[] = initialSigners.length > 0
    ? initialSigners
    : clientContacts
        .filter(c => c.email)
        .map((c, i) => ({ email: c.email, color: SIGNER_COLORS[i % SIGNER_COLORS.length] }));

  const [signers, setSigners] = useState<DocumentSigner[]>(defaultSigners);
  const [unassignedFieldIds, setUnassignedFieldIds] = useState<Set<string>>(new Set());

  // Persist auto-seeded signers to DB so they survive refresh
  useEffect(() => {
    if (initialSigners.length === 0 && defaultSigners.length > 0) {
      fetch(`/api/documents/${docId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ signers: defaultSigners }),
      }).catch(() => {});
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleFieldsChanged = useCallback(() => {
    setPreviewToken(null);
  }, []);

  const handleFieldValueChange = useCallback((fieldId: string, value: string) => {
    setTextFillData(prev => ({ ...prev, [fieldId]: value }));
    setPreviewToken(null); // TXTF-03: reset staleness on any text value change
  }, []);

  const handleQuickFill = useCallback((fieldId: string, value: string) => {
    setTextFillData(prev => ({ ...prev, [fieldId]: value }));
    setPreviewToken(null); // TXTF-03: reset staleness on quick fill
  }, []);

  const handleAiAutoPlace = useCallback(async () => {
    const res = await fetch(`/api/documents/${docId}/ai-prepare`, { method: 'POST' });
    if (!res.ok) {
      const err = await res.json().catch(() => ({ error: 'AI placement failed' }));
      throw new Error(err.error ?? err.message ?? 'AI placement failed');
    }
    const { textFillData: aiTextFill } = await res.json() as {
      fields: unknown[];
      textFillData: Record<string, string>;
    };
    // Merge AI pre-fill into existing textFillData (AI values take precedence)
    setTextFillData(prev => ({ ...prev, ...aiTextFill }));
    // Trigger FieldPlacer to re-fetch from DB (fields were written server-side)
    setAiPlacementKey(k => k + 1);
    // Reset preview staleness — fields changed
    setPreviewToken(null);
  }, [docId]);

  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <div className="lg:col-span-2">
        <PdfViewerWrapper
          docId={docId}
          docStatus={docStatus}
          onFieldsChanged={handleFieldsChanged}
          selectedFieldId={selectedFieldId}
          textFillData={textFillData}
          onFieldSelect={setSelectedFieldId}
          onFieldValueChange={handleFieldValueChange}
          aiPlacementKey={aiPlacementKey}
          signers={signers}
          unassignedFieldIds={unassignedFieldIds}
        />
      </div>
      <div className="lg:col-span-1 lg:sticky lg:top-6 lg:self-start lg:max-h-[calc(100vh-6rem)] lg:overflow-y-auto">
        <PreparePanel
          docId={docId}
          defaultEmail={defaultEmail}
          clientName={clientName}
          currentStatus={docStatus}
          agentDownloadUrl={agentDownloadUrl}
          signedAt={signedAt}
          clientPropertyAddress={clientPropertyAddress}
          previewToken={previewToken}
          onPreviewTokenChange={setPreviewToken}
          textFillData={textFillData}
          selectedFieldId={selectedFieldId}
          onQuickFill={handleQuickFill}
          onAiAutoPlace={handleAiAutoPlace}
          signers={signers}
          onSignersChange={setSigners}
          unassignedFieldIds={unassignedFieldIds}
          onUnassignedFieldIdsChange={setUnassignedFieldIds}
        />
      </div>
    </div>
  );
}
