'use client';

import { useState } from 'react';
import Link from 'next/link';
import { ClipboardSignature, FileText, Eye, Download } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { AggregatedSection } from './aggregated-section';
import { SigningDetailsDialog } from './signing-details-dialog';
import { FileIcon } from '@/components/files/file-icon';
import { FilePreviewDialog } from '@/components/files/file-preview-dialog';
import { useAggregatedFiles, useAggregatedWorkflows } from '@/hooks/use-aggregated-listing';
import { StatusPill, type StatusPillStatus } from '@/components/ui/status-pill';
import { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';
import { triggerUrlDownload } from '@/lib/utils/download';
import type {
  AggregatedFile,
  AggregatedGroup,
  AggregatedWorkflow,
} from '@/hooks/use-aggregated-listing';

interface Props {
  portSlug: string;
  entityType: 'client' | 'company' | 'yacht';
  entityId: string;
}

function mapWorkflowStatus(status: string): StatusPillStatus {
  const known: Record<string, StatusPillStatus> = {
    draft: 'draft',
    sent: 'sent',
    partially_signed: 'partial',
    completed: 'completed',
    expired: 'expired',
    cancelled: 'cancelled',
  };
  return known[status] ?? 'pending';
}

async function handleFileDownload(fileId: string) {
  try {
    const res = await apiFetch<{ data: { url: string; filename: string } }>(
      `/api/v1/files/${fileId}/download`,
    );
    triggerUrlDownload(res.data.url, res.data.filename);
  } catch (err) {
    toastError(err);
  }
}

export function EntityFolderView({ portSlug, entityType, entityId }: Props) {
  const [detailsId, setDetailsId] = useState<string | null>(null);
  const [previewFile, setPreviewFile] = useState<{
    id: string;
    name: string;
    mimeType: string | null;
  } | null>(null);

  // Hook data is the bare AggregatedGroup<T>[] array (hooks unwrap the API envelope).
  const { data: workflowGroups = [], isLoading: workflowsLoading } = useAggregatedWorkflows(
    entityType,
    entityId,
  );
  const { data: fileGroups = [], isLoading: filesLoading } = useAggregatedFiles(
    entityType,
    entityId,
  );

  return (
    <div className="space-y-4">
      <AggregatedSection<'workflows'>
        title="Signing in progress"
        icon={<ClipboardSignature className="h-4 w-4 text-muted-foreground" aria-hidden />}
        groups={workflowGroups}
        loading={workflowsLoading}
        emptyMessage="No workflows in flight for this entity."
        renderRow={(w: AggregatedWorkflow, _group: AggregatedGroup<AggregatedWorkflow>) => (
          <div className="flex items-center justify-between gap-2 text-sm">
            <Link href={`/${portSlug}/documents/${w.id}`} className="truncate hover:underline">
              {w.title}
            </Link>
            <StatusPill status={mapWorkflowStatus(w.status)}>
              {w.status.replace(/_/g, ' ')}
            </StatusPill>
          </div>
        )}
      />

      <AggregatedSection<'files'>
        title="Files"
        icon={<FileText className="h-4 w-4 text-muted-foreground" aria-hidden />}
        groups={fileGroups}
        loading={filesLoading}
        emptyMessage="No files for this entity yet."
        renderRow={(f: AggregatedFile, _group: AggregatedGroup<AggregatedFile>) => {
          const signedFromDocumentId = f.signedFromDocumentId;
          return (
            <div className="group flex items-center justify-between gap-3 rounded-sm px-1 py-0.5 text-sm hover:bg-accent/30">
              <button
                type="button"
                className="flex min-w-0 flex-1 items-center gap-2 text-left hover:text-brand focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand/40 rounded-sm"
                onClick={() => setPreviewFile({ id: f.id, name: f.filename, mimeType: f.mimeType })}
                aria-label={`Preview ${f.filename}`}
              >
                <FileIcon mimeType={f.mimeType} />
                <span className="truncate group-hover:underline">{f.filename}</span>
                {signedFromDocumentId ? (
                  <span
                    className="ml-1 inline-flex shrink-0 items-center rounded-full bg-emerald-50 px-1.5 py-px text-xs font-medium text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300"
                    title="This file is a signed copy of a Documenso/uploaded workflow"
                  >
                    Signed
                  </span>
                ) : null}
                {f.interestBerthLabel && f.interestId ? (
                  <Link
                    href={`/${portSlug}/interests/${f.interestId}`}
                    onClick={(e) => e.stopPropagation()}
                    className="ml-1 inline-flex shrink-0 items-center rounded-full border bg-muted/40 px-1.5 py-px text-xs font-medium text-muted-foreground hover:border-primary/40 hover:bg-accent/40 hover:text-foreground"
                    title={`Linked to interest ${f.interestBerthLabel}`}
                  >
                    {f.interestBerthLabel}
                  </Link>
                ) : null}
              </button>
              <div className="flex items-center gap-2 text-xs text-muted-foreground tabular-nums shrink-0">
                <span>{new Date(f.createdAt).toLocaleDateString(undefined)}</span>
                {signedFromDocumentId ? (
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-8 gap-1 px-2 text-xs text-brand"
                    onClick={() => setDetailsId(signedFromDocumentId)}
                  >
                    <Eye className="h-3 w-3" aria-hidden />
                    View signing details
                  </Button>
                ) : null}
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-8 w-8 opacity-0 group-hover:opacity-100 focus-visible:opacity-100 transition-opacity"
                  onClick={() => void handleFileDownload(f.id)}
                  aria-label={`Download ${f.filename}`}
                  title="Download"
                >
                  <Download className="h-3.5 w-3.5" aria-hidden />
                </Button>
              </div>
            </div>
          );
        }}
      />

      <SigningDetailsDialog
        documentId={detailsId}
        open={Boolean(detailsId)}
        onOpenChange={(open) => !open && setDetailsId(null)}
      />

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