import { useRef, useState } from "react";
import { Upload, X, FileText, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";

export async function signedUrl(path: string) {
  const { data } = await supabase.storage.from("uploads").createSignedUrl(path, 60 * 60);
  return data?.signedUrl ?? "";
}

export function FileUploadField({
  value,
  onChange,
  accept,
  kind = "file",
}: {
  value: string;
  onChange: (v: string) => void;
  accept?: string;
  kind?: "file" | "image";
}) {
  const inputRef = useRef<HTMLInputElement>(null);
  const [busy, setBusy] = useState(false);
  const [preview, setPreview] = useState("");

  async function upload(file: File) {
    setBusy(true);
    try {
      const { data: auth } = await supabase.auth.getUser();
      const uid = auth.user?.id;
      if (!uid) throw new Error("Please sign in again");
      const ext = file.name.split(".").pop() ?? "bin";
      const path = `${uid}/${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
      const { error } = await supabase.storage.from("uploads").upload(path, file);
      if (error) throw error;
      onChange(path);
      if (kind === "image") setPreview(await signedUrl(path));
      toast.success("Uploaded");
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Upload failed");
    } finally {
      setBusy(false);
    }
  }

  const isRemote = /^https?:\/\//.test(value ?? "");

  return (
    <div className="space-y-2">
      <input
        ref={inputRef}
        type="file"
        accept={accept ?? (kind === "image" ? "image/*" : undefined)}
        className="hidden"
        onChange={(e) => {
          const f = e.target.files?.[0];
          if (f) void upload(f);
          e.target.value = "";
        }}
      />
      <div className="flex items-center gap-2">
        <Button type="button" variant="outline" size="sm" onClick={() => inputRef.current?.click()} disabled={busy}>
          {busy ? <Loader2 className="mr-1 size-4 animate-spin" /> : <Upload className="mr-1 size-4" />}
          {value ? "Replace" : kind === "image" ? "Upload photo" : "Upload file"}
        </Button>
        {value && (
          <>
            <span className="flex min-w-0 items-center gap-1 text-xs text-muted-foreground">
              <FileText className="size-3 shrink-0" />
              <span className="truncate">{isRemote ? value : value.split("/").pop()}</span>
            </span>
            <Button
              type="button"
              variant="ghost"
              size="icon"
              onClick={() => {
                onChange("");
                setPreview("");
              }}
            >
              <X className="size-4" />
            </Button>
          </>
        )}
      </div>
      {kind === "image" && (preview || isRemote) && (
        <img
          src={preview || value}
          alt="Uploaded preview"
          className="h-24 w-auto rounded-md border object-cover"
        />
      )}
    </div>
  );
}

export function AttachmentCell({ value }: { value: string | null }) {
  const [loading, setLoading] = useState(false);
  if (!value) return <span className="text-muted-foreground">—</span>;
  const isRemote = /^https?:\/\//.test(value);
  return (
    <button
      type="button"
      className="text-primary underline-offset-2 hover:underline"
      onClick={async () => {
        if (isRemote) {
          window.open(value, "_blank", "noopener");
          return;
        }
        setLoading(true);
        const url = await signedUrl(value);
        setLoading(false);
        if (url) window.open(url, "_blank", "noopener");
        else toast.error("Could not open file");
      }}
    >
      {loading ? "Opening..." : "View"}
    </button>
  );
}
