'use client';

import { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { FileSignature } from 'lucide-react';

import { DocumentList } from '@/components/documents/document-list';
import { FileGrid, type FileRow } 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 { useConfirmation } from '@/hooks/use-confirmation';
import { apiFetch } from '@/lib/api/client';
import { triggerUrlDownload } from '@/lib/utils/download';

interface InterestDocumentsTabProps {
  interestId: string;
}

interface InterestData {
  id: string;
  clientId?: string | null;
}

/**
 * Documents tab - legal instruments (EOI / contract / reservation) with
 * full signing status, plus an Attachments section for any other file the
 * rep wants on the deal. Replaces the standalone Files tab - at the
 * interest level virtually everything is either a legal doc or rare
 * one-off, and a separate tab was dead weight 95% of the time.
 */
export function InterestDocumentsTab({ interestId }: InterestDocumentsTabProps) {
  const queryClient = useQueryClient();
  const [previewFile, setPreviewFile] = useState<FileRow | null>(null);
  const { confirm, dialog: confirmDialog } = useConfirmation();

  const { data: interest } = useQuery<InterestData>({
    queryKey: ['interests', interestId],
    queryFn: () =>
      apiFetch<{ data: InterestData }>(`/api/v1/interests/${interestId}`).then((r) => r.data),
  });

  // Two cohorts: files tagged with this interestId ("This deal") +
  // files belonging to the parent client without an interestId, or
  // tagged to another interest of the same client ("From client").
  // Until the interest record loads we pass a sentinel clientId so
  // the server returns empty rather than the unscoped port-wide list.
  const clientId = interest?.clientId ?? '__pending__';
  const thisDealQueryKey = ['files', { interestId }] as const;
  const fromClientQueryKey = ['files', { clientId }] as const;

  const { data: thisDealFiles, isLoading: thisDealLoading } = usePaginatedQuery<FileRow>({
    queryKey: thisDealQueryKey,
    endpoint: `/api/v1/files?interestId=${encodeURIComponent(interestId)}`,
    filterDefinitions: [],
  });

  const { data: clientFiles, isLoading: clientFilesLoading } = usePaginatedQuery<FileRow>({
    queryKey: fromClientQueryKey,
    endpoint: `/api/v1/files?clientId=${encodeURIComponent(clientId)}`,
    filterDefinitions: [],
  });

  // "From client" excludes anything we already surface under "This deal".
  const fromClientFiles = clientFiles.filter((f) => !f.interestId || f.interestId !== interestId);

  useRealtimeInvalidation({
    'file:uploaded': [thisDealQueryKey, fromClientQueryKey],
    'file:updated': [thisDealQueryKey, fromClientQueryKey],
    'file:deleted': [thisDealQueryKey, fromClientQueryKey],
  });

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

  const handleDelete = async (file: FileRow) => {
    const ok = await confirm({
      title: 'Delete file',
      description: `Delete "${file.filename}"? This cannot be undone.`,
      confirmLabel: 'Delete',
    });
    if (!ok) return;
    try {
      await apiFetch(`/api/v1/files/${file.id}`, { method: 'DELETE' });
      queryClient.invalidateQueries({ queryKey: thisDealQueryKey });
      queryClient.invalidateQueries({ queryKey: fromClientQueryKey });
    } catch {
      // silent
    }
  };

  const hasThisDeal = thisDealFiles.length > 0;
  const hasFromClient = fromClientFiles.length > 0;
  const hasAttachments = hasThisDeal || hasFromClient;

  return (
    <div className="space-y-8">
      <section className="space-y-4">
        <div className="flex items-center justify-between">
          <h3 className="text-sm font-medium text-muted-foreground">Signature documents</h3>
        </div>

        <DocumentList
          interestId={interestId}
          emptyState={
            <div className="flex flex-col items-center gap-3 rounded-lg border border-dashed border-border bg-muted/20 px-6 py-10 text-center">
              <div className="flex size-10 items-center justify-center rounded-full bg-background text-muted-foreground">
                <FileSignature className="size-5" aria-hidden />
              </div>
              <div className="space-y-1">
                <p className="text-sm font-medium text-foreground">No documents yet</p>
                <p className="text-xs text-muted-foreground">
                  Generate the EOI from the Overview tab to send it for signing in one click.
                </p>
              </div>
            </div>
          }
        />
      </section>

      <section className="space-y-4">
        <div className="flex items-center justify-between">
          <h3 className="text-sm font-medium text-muted-foreground">Attachments</h3>
          {hasAttachments ? (
            <span className="text-xs text-muted-foreground">
              {thisDealFiles.length + fromClientFiles.length} file
              {thisDealFiles.length + fromClientFiles.length === 1 ? '' : 's'}
            </span>
          ) : null}
        </div>

        <PermissionGate resource="files" action="upload">
          {interest?.clientId ? (
            <FileUploadZone
              entityType="client"
              entityId={interest.clientId}
              clientId={interest.clientId}
              // Pass the interest FK so the upload-zone's scope radio
              // surfaces "This deal" (default) vs "Client-level". The
              // server-side service routes the file to the nested
              // interest folder when the rep picks "This deal", or
              // leaves it at the client folder when they pick
              // client-level.
              interestId={interestId}
              onUploadComplete={() => {
                queryClient.invalidateQueries({ queryKey: thisDealQueryKey });
                queryClient.invalidateQueries({ queryKey: fromClientQueryKey });
              }}
            />
          ) : null}
        </PermissionGate>

        {(hasThisDeal || thisDealLoading) && (
          <div className="space-y-2">
            <h4 className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
              This deal
            </h4>
            <FileGrid
              files={thisDealFiles}
              onDownload={handleDownload}
              onPreview={setPreviewFile}
              onRename={() => {}}
              onDelete={handleDelete}
              isLoading={thisDealLoading}
            />
          </div>
        )}

        {(hasFromClient || clientFilesLoading) && (
          <div className="space-y-2">
            <h4 className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
              From client
            </h4>
            <FileGrid
              files={fromClientFiles}
              onDownload={handleDownload}
              onPreview={setPreviewFile}
              onRename={() => {}}
              onDelete={handleDelete}
              isLoading={clientFilesLoading}
            />
          </div>
        )}
      </section>

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