import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { BASE_PATH } from "@/const";
import { assetUrl } from "@/lib/asset";
import { useState } from "react";
import { toast } from "sonner";

export default function FileUploadField({
  label,
  value,
  onChange,
  type,
  placeholder,
}: {
  label: string;
  value: string;
  onChange: (url: string) => void;
  type: "audio" | "image";
  placeholder?: string;
}) {
  const [uploading, setUploading] = useState(false);
  const inputId = `upload-${type}-${label.replace(/\s+/g, "-")}`;

  const handleFile = async (file: File) => {
    setUploading(true);
    try {
      const formData = new FormData();
      formData.append("file", file);

      const res = await fetch(`${BASE_PATH}/api/upload/${type}`, {
        method: "POST",
        credentials: "include",
        body: formData,
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data?.error || "Falha no upload");

      onChange(data.url);
      toast.success("Arquivo enviado com sucesso.");
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Falha no upload");
    } finally {
      setUploading(false);
    }
  };

  return (
    <div className="space-y-2">
      <Label>{label}</Label>
      <div className="flex gap-2">
        <Input
          value={value}
          onChange={e => onChange(e.target.value)}
          placeholder={placeholder || "URL ou envie um arquivo"}
          className="flex-1"
        />
        <input
          id={inputId}
          type="file"
          accept={type === "audio" ? "audio/*" : "image/*"}
          className="hidden"
          onChange={e => {
            const file = e.target.files?.[0];
            if (file) void handleFile(file);
            e.target.value = "";
          }}
        />
        <Button type="button" variant="outline" disabled={uploading} asChild>
          <label htmlFor={inputId} className="cursor-pointer">
            {uploading ? "Enviando..." : "Enviar arquivo"}
          </label>
        </Button>
      </div>
      {value && type === "audio" && <audio controls src={assetUrl(value)} className="w-full h-10" />}
      {value && type === "image" && (
        <img src={assetUrl(value)} alt="" className="h-20 w-20 object-cover rounded border border-sof-border" />
      )}
    </div>
  );
}
