'use client';

import { useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';

import { FileGrid } from '@/components/files/file-grid';
import { FileUploadZone } from '@/components/files/file-upload-zone';
import { FilePreviewDialog } from '@/components/files/file-preview-dialog';
import { PermissionGate } from '@/components/shared/permission-gate';
import { usePaginatedQuery } from '@/hooks/use-paginated-query';
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { apiFetch } from '@/lib/api/client';
import type { FileRow } from '@/components/files/file-grid';

interface InterestFilesTabProps {
  interestId: string;
}

export function InterestFilesTab({ interestId }: InterestFilesTabProps) {
  const queryClient = useQueryClient();
  const [previewFile, setPreviewFile] = useState<FileRow | null>(null);

  const { data, isLoading } = usePaginatedQuery<FileRow>({
    queryKey: ['files', { entityType: 'interest', entityId: interestId }],
    endpoint: `/api/v1/files?entityType=interest&entityId=${encodeURIComponent(interestId)}`,
    filterDefinitions: [],
  });

  useRealtimeInvalidation({
    'file:uploaded': [['files', { entityType: 'interest', entityId: interestId }]],
    'file:updated': [['files', { entityType: 'interest', entityId: interestId }]],
    'file:deleted': [['files', { entityType: 'interest', entityId: interestId }]],
  });

  const handleDownload = async (file: FileRow) => {
    try {
      const res = await apiFetch<{ data: { url: string; filename: string } }>(
        `/api/v1/files/${file.id}/download`,
      );
      const a = document.createElement('a');
      a.href = res.data.url;
      a.download = res.data.filename;
      a.click();
    } catch {
      // silent
    }
  };

  const handleDelete = async (file: FileRow) => {
    if (!confirm(`Delete "${file.filename}"? This cannot be undone.`)) return;
    try {
      await apiFetch(`/api/v1/files/${file.id}`, { method: 'DELETE' });
      queryClient.invalidateQueries({
        queryKey: ['files', { entityType: 'interest', entityId: interestId }],
      });
    } catch {
      // silent
    }
  };

  return (
    <div className="space-y-4">
      <PermissionGate resource="files" action="upload">
        <FileUploadZone
          entityType="interest"
          entityId={interestId}
          onUploadComplete={() => {
            queryClient.invalidateQueries({
              queryKey: ['files', { entityType: 'interest', entityId: interestId }],
            });
          }}
        />
      </PermissionGate>

      <FileGrid
        files={data}
        onDownload={handleDownload}
        onPreview={setPreviewFile}
        onRename={() => {}}
        onDelete={handleDelete}
        isLoading={isLoading}
      />

      <FilePreviewDialog
        open={!!previewFile}
        onOpenChange={(open) => !open && setPreviewFile(null)}
        fileId={previewFile?.id}
        fileName={previewFile?.filename}
        mimeType={previewFile?.mimeType ?? undefined}
      />
    </div>
  );
}
