"use client"

import { Paperclip, Upload, X } from "lucide-react"
import { useCallback, useState } from "react"
import { toast } from "sonner"
import { api } from "@/lib/api"
import { Button } from "@/components/ui/button"
import { formatDateTime } from "@/lib/format"

export type Attachment = {
  id: string
  file_name: string
  file_url?: string
  file_size?: number
  content_type?: string
  uploaded_by?: string
  created_at: string
}

type Props = {
  attachments: Attachment[]
  uploadEndpoint: string
  language: "ar" | "en"
  canUpload?: boolean
  onRefresh?: () => void
}

export function AttachmentPanel({ attachments, uploadEndpoint, language, canUpload, onRefresh }: Props) {
  const [uploading, setUploading] = useState(false)

  const handleUpload = useCallback(async (files: FileList | null) => {
    if (!files || files.length === 0) return
    setUploading(true)
    try {
      for (const file of Array.from(files)) {
        const formData = new FormData()
        formData.append("file", file)
        await api.post(uploadEndpoint, formData, {
          headers: { "Content-Type": "multipart/form-data" },
        })
      }
      toast.success(language === "ar" ? "تم رفع المرفقات." : "Attachments uploaded.")
      onRefresh?.()
    } catch (err) {
      toast.error(language === "ar" ? "فشل رفع المرفق." : "Failed to upload attachment.")
    } finally {
      setUploading(false)
    }
  }, [uploadEndpoint, language, onRefresh])

  return (
    <div className="space-y-3">
      {canUpload && (
        <label className="inline-flex cursor-pointer items-center gap-2 rounded-lg border border-border bg-background px-3 py-2 text-sm font-medium transition-colors hover:bg-muted">
          <Upload className="h-4 w-4" />
          {language === "ar" ? "رفع ملف" : "Upload file"}
          <input
            type="file"
            multiple
            className="hidden"
            onChange={e => handleUpload(e.target.files)}
            disabled={uploading}
          />
        </label>
      )}

      {attachments.length === 0 ? (
        <p className="text-sm text-muted-foreground">
          {language === "ar" ? "لا توجد مرفقات." : "No attachments."}
        </p>
      ) : (
        <div className="space-y-2">
          {attachments.map(att => (
            <div
              key={att.id}
              className="flex items-center justify-between rounded-lg border border-border p-3 text-sm"
            >
              <div className="flex items-center gap-2">
                <Paperclip className="h-4 w-4 text-muted-foreground" />
                <div>
                  <p className="font-medium">{att.file_name}</p>
                  <p className="text-[11px] text-muted-foreground">
                    {att.uploaded_by && `${att.uploaded_by} · `}
                    {formatDateTime(att.created_at)}
                  </p>
                </div>
              </div>
              {att.file_url && (
                <a
                  href={att.file_url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-xs text-gold-600 hover:underline"
                >
                  {language === "ar" ? "عرض" : "View"}
                </a>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  )
}