'use client';

import { useEffect, useState } from 'react';
import { DocumentFormDialog } from '@/components/documents/document-form-dialog';
import { DocumentViewDialog } from '@/components/documents/document-view-dialog';
import { type DocumentTypeCode } from '@/lib/document-catalog';
import { UserDocument } from '@/lib/api';

export function DocumentDialog({
  open,
  onOpenChange,
  documentType,
  userId,
  token,
  existing,
  onSaved,
  readOnly
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  documentType: DocumentTypeCode;
  userId: string;
  token: string | null;
  existing?: UserDocument | null;
  onSaved: () => void | Promise<void>;
  readOnly?: boolean;
}) {
  const [mode, setMode] = useState<'view' | 'edit'>('edit');

  useEffect(() => {
    if (!open) return;
    setMode(existing ? 'view' : 'edit');
  }, [existing?.id, open]);

  function handleClose(nextOpen: boolean) {
    if (!nextOpen) {
      onOpenChange(false);
      return;
    }
    onOpenChange(true);
  }

  if (!open) return null;

  if (mode === 'view' && existing) {
    return (
      <DocumentViewDialog
        open={open}
        onOpenChange={handleClose}
        documentType={documentType}
        userId={userId}
        token={token}
        document={existing}
        readOnly={readOnly}
        onEdit={readOnly ? undefined : () => setMode('edit')}
      />
    );
  }

  return (
    <DocumentFormDialog
      open={open}
      onOpenChange={(nextOpen) => {
        if (!nextOpen && existing) {
          setMode('view');
          return;
        }
        handleClose(nextOpen);
      }}
      documentType={documentType}
      userId={userId}
      token={token}
      existing={existing}
      onSaved={onSaved}
      readOnly={readOnly}
      showBackToView={Boolean(existing) && !readOnly}
      onBackToView={existing ? () => setMode('view') : undefined}
    />
  );
}
