"use client"

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import type { DriveFileInfo } from "@/lib/api/types"
import { displayFileBaseName, displayFileName } from "@/lib/drive/display-file-name"
import {
  DRIVE_DIALOG_BODY,
  DRIVE_DIALOG_CONTENT,
  DRIVE_DIALOG_HEADER,
  DRIVE_DIALOG_OVERLAY,
  DRIVE_TEXT_SECONDARY,
  DRIVE_TEXT_TITLE,
} from "@/lib/drive/drive-dialog-styles"
import { cn } from "@/lib/utils"

function formatBytes(size: number): string {
  if (size < 1024) return `${size} o`
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} Ko`
  return `${(size / (1024 * 1024)).toFixed(1)} Mo`
}

function formatDate(iso: string): string {
  const date = new Date(iso)
  if (Number.isNaN(date.getTime())) return iso
  return date.toLocaleString("fr-FR", {
    dateStyle: "medium",
    timeStyle: "short",
  })
}

function DetailRow({ label, value }: { label: string; value: string }) {
  return (
    <div className="grid grid-cols-[120px_1fr] gap-3 py-2 text-sm">
      <span className="text-muted-foreground">{label}</span>
      <span className="break-all">{value}</span>
    </div>
  )
}

export function DocsDetailsDialog({
  open,
  onOpenChange,
  file,
}: {
  open: boolean
  onOpenChange: (open: boolean) => void
  file: DriveFileInfo
}) {
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent
        overlayClassName={DRIVE_DIALOG_OVERLAY}
        className={cn(DRIVE_DIALOG_CONTENT, "sm:max-w-[480px]")}
      >
        <DialogHeader className={DRIVE_DIALOG_HEADER}>
          <DialogTitle className={cn("text-base font-medium", DRIVE_TEXT_TITLE)}>
            Détails
          </DialogTitle>
          <DialogDescription className={cn("text-sm", DRIVE_TEXT_SECONDARY)}>
            Informations sur le document.
          </DialogDescription>
        </DialogHeader>
        <div className={cn(DRIVE_DIALOG_BODY, "divide-y divide-border")}>
          <DetailRow label="Nom" value={displayFileBaseName(file.name)} />
          <DetailRow label="Fichier" value={displayFileName(file.name)} />
          <DetailRow label="Emplacement" value={file.path} />
          <DetailRow label="Type" value={file.mime_type || "—"} />
          <DetailRow label="Taille" value={formatBytes(file.size)} />
          <DetailRow label="Modifié" value={formatDate(file.last_modified)} />
        </div>
      </DialogContent>
    </Dialog>
  )
}
