'use client';

import { Download, FileText, MoreHorizontal, Pencil, Trash2 } from 'lucide-react';
import { format } from 'date-fns';

import { FileIcon as SharedFileIcon } from './file-icon';

import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Skeleton } from '@/components/ui/skeleton';

export interface FileRow {
  id: string;
  filename: string;
  originalName: string;
  mimeType: string | null;
  sizeBytes: string | null;
  storagePath?: string;
  category: string | null;
  createdAt: string | Date;
  uploadedBy: string;
  /** Optional — present when the file is scoped to a sales deal.
   *  Consumers like InterestDocumentsTab filter on this to split the
   *  "This deal" vs "From client" cohorts. */
  interestId?: string | null;
}

interface FileGridProps {
  files: FileRow[];
  onDownload: (file: FileRow) => void;
  onPreview: (file: FileRow) => void;
  onRename: (file: FileRow) => void;
  onDelete: (file: FileRow) => void;
  isLoading?: boolean;
}

function formatBytes(bytes: string | null): string {
  if (!bytes) return '';
  const n = Number(bytes);
  if (n < 1024) return `${n} B`;
  if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
  return `${(n / (1024 * 1024)).toFixed(1)} MB`;
}

function FileIcon({ mimeType }: { mimeType: string | null }) {
  return <SharedFileIcon mimeType={mimeType} className="h-8 w-8" />;
}

export function FileGrid({
  files,
  onDownload,
  onPreview,
  onRename,
  onDelete,
  isLoading,
}: FileGridProps) {
  if (isLoading) {
    return (
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
        {Array.from({ length: 10 }).map((_, i) => (
          <Skeleton key={i} className="h-32 rounded-lg" />
        ))}
      </div>
    );
  }

  if (files.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center py-16 text-center text-muted-foreground">
        <FileText className="h-10 w-10 mb-3 opacity-40" />
        <p className="text-sm font-medium">No files yet</p>
        <p className="text-xs mt-1">Upload files using the zone above</p>
      </div>
    );
  }

  return (
    <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
      {files.map((file) => (
        <div
          key={file.id}
          className="group relative rounded-lg border bg-card hover:border-primary/50 hover:shadow-sm transition-all"
        >
          <button
            type="button"
            onClick={() => onPreview(file)}
            aria-label={`Preview ${file.filename}`}
            className="flex w-full flex-col items-center gap-2 rounded-lg p-3 text-left focus:outline-none focus:ring-2 focus:ring-ring"
          >
            <FileIcon mimeType={file.mimeType} />
            <p className="w-full truncate text-center text-xs font-medium" title={file.filename}>
              {file.filename}
            </p>
            <div className="flex flex-col items-center gap-0.5 text-xs text-muted-foreground">
              <span>{formatBytes(file.sizeBytes)}</span>
              <span>{format(new Date(file.createdAt), 'MMM d, yyyy')}</span>
            </div>
          </button>

          <div className="absolute right-1 top-1 opacity-0 group-hover:opacity-100 transition-opacity">
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="icon" className="h-6 w-6" aria-label="File actions">
                  <MoreHorizontal className="h-3.5 w-3.5" aria-hidden />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-40">
                <DropdownMenuItem onClick={() => onDownload(file)}>
                  <Download className="mr-2 h-3.5 w-3.5" />
                  Download
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => onRename(file)}>
                  <Pencil className="mr-2 h-3.5 w-3.5" />
                  Rename
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem
                  onClick={() => onDelete(file)}
                  className="text-destructive focus:text-destructive"
                >
                  <Trash2 className="mr-2 h-3.5 w-3.5" />
                  Delete
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
      ))}
    </div>
  );
}
