'use client';

import { Pencil, X } from 'lucide-react';
import { DocumentPhotoGallery } from '@/components/documents/document-photo-gallery';
import { DocumentViewCard } from '@/components/documents/document-view-card';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { getDocumentType, parseAttachmentMeta, parseDocumentPhotos, parseMetadata, type DocumentTypeCode } from '@/lib/document-catalog';
import { UserDocument } from '@/lib/api';

export function DocumentViewDialog({
  open,
  onOpenChange,
  documentType,
  userId,
  token,
  document,
  readOnly,
  onEdit
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  documentType: DocumentTypeCode;
  userId: string;
  token: string | null;
  document: UserDocument;
  readOnly?: boolean;
  onEdit?: () => void;
}) {
  const config = getDocumentType(documentType);
  const metadata = parseMetadata(document.metadataJson);
  const storageKeys = parseDocumentPhotos(metadata);
  const attachmentMeta = parseAttachmentMeta(metadata);

  if (!config) return null;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[92vh] overflow-y-auto rounded-[28px] p-0 sm:max-w-[480px]">
        <DialogHeader className="sticky top-0 z-10 border-b border-[#eceef4] bg-white px-5 py-4">
          <div className="flex items-center justify-between gap-3">
            <DialogTitle className="text-xl font-semibold">{config.label}</DialogTitle>
            <button type="button" onClick={() => onOpenChange(false)} className="rounded-full p-2 hover:bg-[#f4f5f8]" aria-label="Закрыть">
              <X className="h-4 w-4" />
            </button>
          </div>
        </DialogHeader>

        <div className="space-y-5 px-5 pb-5 pt-4">
          <DocumentViewCard documentType={documentType} document={document} />

          {storageKeys.length > 0 ? (
            <section>
              <p className="mb-3 text-sm font-medium text-[#1f2430]">Прикреплённые файлы</p>
              <DocumentPhotoGallery
                userId={userId}
                token={token}
                storageKeys={storageKeys}
                attachmentMeta={attachmentMeta}
                readOnly
              />
            </section>
          ) : null}

          {!readOnly && onEdit ? (
            <Button type="button" className="w-full rounded-[18px] py-6" onClick={onEdit}>
              <Pencil className="mr-2 h-4 w-4" />
              Редактировать
            </Button>
          ) : null}
        </div>
      </DialogContent>
    </Dialog>
  );
}
