'use client';

import { useMutation, useSuspenseQuery } from '@tanstack/react-query';
import { toast } from 'sonner';
import { deleteCertificateMutation } from '../api/certificate-mutations';
import { certificatesQueryOptions } from '../api/queries';
import { TrainingRecordAttachmentList } from './training-record-attachment-list';

interface TrainingRecordCertificateManagerProps {
  trainingRecordId: number;
  canManage?: boolean;
  title?: string;
}

export function TrainingRecordCertificateManager({
  trainingRecordId,
  canManage = true,
  title
}: TrainingRecordCertificateManagerProps) {
  const { data } = useSuspenseQuery(certificatesQueryOptions(trainingRecordId));

  const deleteMutation = useMutation({
    ...deleteCertificateMutation,
    onSuccess: () => {
      toast.success('ลบเอกสารเรียบร้อยแล้ว');
    },
    onError: () => {
      toast.error('ไม่สามารถลบเอกสารได้');
    }
  });

  const items = data.certificates.map((certificate) => ({
    id: certificate.id,
    fileName: certificate.file_name,
    fileSize: certificate.file_size,
    fileType: certificate.file_type,
    fileUrl: certificate.file_url,
    onDelete: canManage
      ? () =>
          deleteMutation.mutate({
            trainingRecordId,
            certificateId: certificate.id
          })
      : undefined,
    isDeleting: deleteMutation.isPending
  }));

  return (
    <div className='space-y-3'>
      <TrainingRecordAttachmentList items={items} title={title} />
      {!canManage ? (
        <div className='text-muted-foreground text-sm'>
          จัดการเอกสารได้เฉพาะตอนที่รายการนี้ยังอยู่ในสถานะฉบับร่างหรือขอแก้ไข
        </div>
      ) : null}
    </div>
  );
}
