"use client";

import { useRef, useState } from "react";
import { Download, Eye, FileText, FileVideo, Image, Paperclip, Trash2, Upload } from "lucide-react";
import { FilePreviewModal } from "@/components/attachments/file-preview-modal";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { useAttachments } from "@/hooks/use-attachments";
import { formatFileSize, getFileKind, isPreviewableFile } from "@/lib/file-utils";
import { formatRelativeDate } from "@/lib/utils";
import type { Attachment } from "@/types";

interface AttachmentsPanelProps {
  entityType: Attachment["entity_type"];
  entityId: string | null;
  projectId?: string | null;
  teamId?: string | null;
  editable?: boolean;
  title?: string;
}

function AttachmentIcon({ mimeType, fileName }: { mimeType: string | null; fileName: string }) {
  const kind = getFileKind(mimeType, fileName);
  if (kind === "image") return <Image className="h-3.5 w-3.5 shrink-0 text-sky-500" />;
  if (kind === "video") return <FileVideo className="h-3.5 w-3.5 shrink-0 text-violet-500" />;
  return <FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />;
}

export function AttachmentsPanel({
  entityType,
  entityId,
  projectId = null,
  teamId = null,
  editable = true,
  title = "Attachments",
}: AttachmentsPanelProps) {
  const inputRef = useRef<HTMLInputElement>(null);
  const [previewingAttachment, setPreviewingAttachment] = useState<Attachment | null>(null);
  const { attachments, loading, uploading, error, uploadFiles, deleteAttachment } =
    useAttachments({
      entityType,
      entityId,
      projectId,
      teamId,
    });

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between gap-3">
        <div className="flex items-center gap-2">
          <Paperclip className="h-4 w-4 text-muted-foreground" />
          <h3 className="text-sm font-semibold">{title}</h3>
        </div>
        {editable && (
          <>
            <input
              ref={inputRef}
              type="file"
              multiple
              accept="image/*,video/*,application/pdf,.csv,.xlsx,.zip,.rar,.txt,.md,.doc,.docx"
              className="hidden"
              onChange={(event) => {
                const files = event.target.files;
                if (!files || files.length === 0) return;
                void uploadFiles(files);
                event.target.value = "";
              }}
            />
            <Button
              type="button"
              size="sm"
              variant="outline"
              onClick={() => inputRef.current?.click()}
              disabled={!entityId || uploading}
            >
              <Upload className="h-4 w-4" />
              {uploading ? "Uploading..." : "Upload"}
            </Button>
          </>
        )}
      </div>

      {error && (
        <div className="rounded-xl border border-destructive/20 bg-destructive/5 px-4 py-3 text-sm text-destructive">
          {error}
        </div>
      )}

      {loading ? (
        <div className="space-y-2">
          <Skeleton className="h-16 rounded-xl" />
          <Skeleton className="h-16 rounded-xl" />
        </div>
      ) : attachments.length === 0 ? (
        <div className="rounded-xl border border-dashed border-border p-4 text-sm text-muted-foreground">
          No files attached yet.
        </div>
      ) : (
        <div className="space-y-2">
          {attachments.map((attachment) => (
            <div
              key={attachment.id}
              className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-border/60 bg-background/60 p-3"
            >
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-2">
                  <AttachmentIcon mimeType={attachment.mime_type} fileName={attachment.file_name} />
                  <p className="truncate text-sm font-medium">{attachment.file_name}</p>
                </div>
                <p className="mt-1 text-xs text-muted-foreground">
                  {formatFileSize(attachment.size_bytes)} • added{" "}
                  {formatRelativeDate(attachment.created_at)}
                </p>
              </div>

              <div className="flex items-center gap-2">
                {isPreviewableFile(attachment.mime_type, attachment.file_name) && (
                  <Button
                    type="button"
                    size="sm"
                    variant="outline"
                    onClick={() => setPreviewingAttachment(attachment)}
                  >
                    <Eye className="h-3.5 w-3.5" />
                    Preview
                  </Button>
                )}
                <a
                  href={attachment.public_url}
                  target="_blank"
                  rel="noreferrer"
                  className="inline-flex items-center gap-1 rounded-md border border-border px-3 py-2 text-xs text-muted-foreground hover:text-foreground"
                >
                  <Download className="h-3.5 w-3.5" />
                  Open
                </a>
                {editable && (
                  <Button
                    type="button"
                    size="sm"
                    variant="ghost"
                    className="text-destructive"
                    onClick={() => {
                      void deleteAttachment(attachment);
                    }}
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                )}
              </div>
            </div>
          ))}
        </div>
      )}

      {previewingAttachment && (
        <FilePreviewModal
          open={!!previewingAttachment}
          onClose={() => setPreviewingAttachment(null)}
          fileName={previewingAttachment.file_name}
          publicUrl={previewingAttachment.public_url}
          mimeType={previewingAttachment.mime_type}
        />
      )}
    </div>
  );
}
