"use client";

import type { ProjectFile } from "@/lib/api/types";
import { useFormattedDate } from "@/hooks/use-formatted-date";
import { Check, File, FileImage } from "lucide-react";
import { useTranslations } from "next-intl";
import Image from "next/image";
import { cn } from "@/lib/utils";
import { useState } from "react";

interface SelectableFileCardProps {
  file: ProjectFile;
  selected: boolean;
  onSelect: (fileId: number) => void;
}

// Helper to get file icon and colors based on mime type or extension
function getFileIconInfo(mimeType: string, fileName: string) {
  const ext = fileName.split(".").pop()?.toLowerCase();

  // PDF
  if (mimeType === "application/pdf" || ext === "pdf") {
    return {
      iconPath: "/icons/files/pdf.svg",
      bgColor: "bg-primary/5 dark:bg-primary/10",
      borderColor: "border-border",
    };
  }

  // Word documents
  if (mimeType.includes("word") || ext === "doc" || ext === "docx") {
    return {
      iconPath: "/icons/files/word.svg",
      bgColor: "bg-primary/5 dark:bg-primary/10",
      borderColor: "border-border",
    };
  }

  // Excel spreadsheets
  if (
    mimeType.includes("spreadsheet") ||
    mimeType.includes("excel") ||
    ext === "xls" ||
    ext === "xlsx"
  ) {
    return {
      iconPath: "/icons/files/excel.svg",
      bgColor: "bg-primary/5 dark:bg-primary/10",
      borderColor: "border-border",
    };
  }

  // CSV
  if (mimeType === "text/csv" || ext === "csv") {
    return {
      iconPath: "/icons/files/csv.svg",
      bgColor: "bg-primary/5 dark:bg-primary/10",
      borderColor: "border-border",
    };
  }

  // PowerPoint
  if (mimeType.includes("presentation") || ext === "ppt" || ext === "pptx") {
    return {
      iconPath: "/icons/files/powerpoint.svg",
      bgColor: "bg-primary/5 dark:bg-primary/10",
      borderColor: "border-border",
    };
  }

  // Images - use lucide icon
  if (mimeType.startsWith("image/")) {
    return {
      iconPath: null,
      lucideIcon: FileImage,
      bgColor: "bg-background dark:bg-muted",
      borderColor: "border-border",
      iconColor: "text-muted-foreground",
    };
  }

  // Default - use lucide icon
  return {
    iconPath: null,
    lucideIcon: File,
    iconColor: "text-muted-foreground",
    bgColor: "bg-background dark:bg-muted",
    borderColor: "border-border",
  };
}

export function SelectableFileCard({
  file,
  selected,
  onSelect,
}: SelectableFileCardProps) {
  const t = useTranslations();
  const { formatDate } = useFormattedDate();
  const fileIconInfo = getFileIconInfo(file.mime_type, file.file_name);
  const LucideIcon = fileIconInfo.lucideIcon;
  const [imageError, setImageError] = useState(false);

  // Check if the file is an image
  const isImage = file.mime_type.startsWith("image/");

  const formattedDate = formatDate(file.created_at);

  const handleClick = () => {
    onSelect(file.id);
  };

  return (
    <div
      onClick={handleClick}
      className={cn(
        "bg-card border rounded-lg shadow-sm overflow-hidden flex flex-col cursor-pointer transition-all",
        selected
          ? "border-primary ring-2 ring-primary/20"
          : fileIconInfo.borderColor,
        "hover:shadow-md"
      )}
    >
      {/* Top Section - Image Preview or Icon Area */}
      <div className={cn("h-[120px] relative", !isImage || imageError ? fileIconInfo.bgColor : "bg-muted")}>
        {/* Checkbox in top-left */}
        <div className="absolute top-2 start-2 z-10">
          <div
            className={cn(
              "w-5 h-5 rounded border-2 flex items-center justify-center transition-colors",
              selected
                ? "bg-primary border-primary"
                : "bg-card border-border hover:border-primary"
            )}
          >
            {selected && <Check className="h-3 w-3 text-white" />}
          </div>
        </div>

        {/* Image Preview or Icon */}
        {isImage && !imageError ? (
          <Image
            src={file.file_url}
            alt={file.file_name}
            fill
            className="object-cover"
            sizes="(max-width: 640px) 50vw, (max-width: 1024px) 33vw, 25vw"
            onError={() => setImageError(true)}
          />
        ) : (
          <div className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2">
            <div className="bg-card rounded-full w-[56px] h-[56px] flex items-center justify-center shadow-sm border border-border/50">
              {fileIconInfo.iconPath ? (
                <img
                  src={fileIconInfo.iconPath}
                  alt={file.file_name}
                  className="w-8 h-8 object-contain"
                />
              ) : (
                LucideIcon && (
                  <LucideIcon className={`w-8 h-8 ${fileIconInfo.iconColor}`} />
                )
              )}
            </div>
          </div>
        )}
      </div>

      {/* Bottom Section - File Info */}
      <div className="p-3 space-y-1.5 min-w-0">
        {/* File Name */}
        <p
          className="text-sm font-medium text-foreground truncate"
          title={file.file_name}
        >
          {file.file_name}
        </p>

        {/* Upload Date */}
        <p className="text-xs text-muted-foreground">
          {t("files.card.uploadDate")}: {formattedDate}
        </p>

        {/* Size */}
        <p className="text-xs text-muted-foreground">
          {t("files.card.size")}: {file.size_formatted}
        </p>
      </div>
    </div>
  );
}
