"use client";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/inputs/input";
import { cn } from "@/lib/utils";
import { FileUp, Image as ImageIcon, Link } from "lucide-react";
import { useEffect, useRef, useState } from "react";

export interface MediaInsertDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  mode: "image" | "file";
  onInsertImage: (src: string, altText: string) => void;
  onInsertFile: (url: string, name: string) => void;
}

export function MediaInsertDialog({
  open,
  onOpenChange,
  mode,
  onInsertImage,
  onInsertFile,
}: MediaInsertDialogProps) {
  const [tab, setTab] = useState<"upload" | "url">("upload");
  const [uploadedFile, setUploadedFile] = useState<File | null>(null);
  const [urlValue, setUrlValue] = useState("");
  const [altText, setAltText] = useState("");
  const fileInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (!open) {
      setTab("upload");
      setUploadedFile(null);
      setUrlValue("");
      setAltText("");
    }
  }, [open]);

  const isImage = mode === "image";
  const title = isImage ? "Insert Image" : "Insert File";
  const accept = isImage ? "image/*" : "application/pdf,image/*";

  const canConfirm = tab === "upload" ? uploadedFile !== null : urlValue.trim().length > 0;

  const handleConfirm = () => {
    if (tab === "upload" && uploadedFile) {
      const blobUrl = URL.createObjectURL(uploadedFile);
      if (isImage) onInsertImage(blobUrl, altText || uploadedFile.name);
      else onInsertFile(blobUrl, uploadedFile.name);
    } else if (tab === "url" && urlValue.trim()) {
      const url = urlValue.trim();
      if (isImage) {
        onInsertImage(url, altText || url.split("/").pop()?.split("?")[0] || url);
      } else {
        onInsertFile(url, url.split("/").pop()?.split("?")[0] || url);
      }
    }
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            {isImage ? <ImageIcon className="size-5" /> : <FileUp className="size-5" />}
            {title}
          </DialogTitle>
        </DialogHeader>

        {/* Tab switcher */}
        <div className="flex gap-1 rounded-lg bg-muted p-1">
          {(["upload", "url"] as const).map((t) => (
            <button
              key={t}
              type="button"
              onClick={() => setTab(t)}
              className={cn(
                "flex flex-1 items-center justify-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors",
                tab === t ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground"
              )}
            >
              {t === "url" && <Link className="size-3.5" />}
              {t === "upload" ? "Upload from device" : "Enter URL"}
            </button>
          ))}
        </div>

        {tab === "upload" ? (
          <div className="space-y-3">
            <div
              className="flex min-h-32 cursor-pointer flex-col items-center justify-center rounded-lg border-2 border-dashed border-border p-6 text-center hover:border-primary/50 hover:bg-muted/30"
              onClick={() => fileInputRef.current?.click()}
            >
              <input
                ref={fileInputRef}
                type="file"
                accept={accept}
                className="hidden"
                onChange={(e) => setUploadedFile(e.target.files?.[0] ?? null)}
              />
              {uploadedFile ? (
                <p className="text-sm font-medium text-foreground">{uploadedFile.name}</p>
              ) : (
                <>
                  <FileUp className="mb-2 size-8 text-muted-foreground" />
                  <p className="text-sm text-muted-foreground">
                    {isImage ? "Drag & drop an image or click to browse" : "Drag & drop a PDF or click to browse"}
                  </p>
                </>
              )}
            </div>
            {isImage && (
              <Input
                placeholder="Alt text (optional)"
                value={altText}
                onChange={(e) => setAltText(e.target.value)}
              />
            )}
          </div>
        ) : (
          <div className="space-y-3">
            <Input
              placeholder={isImage ? "https://example.com/image.jpg" : "https://example.com/document.pdf"}
              value={urlValue}
              onChange={(e) => setUrlValue(e.target.value)}
              autoFocus
            />
            {isImage && (
              <Input
                placeholder="Alt text (optional)"
                value={altText}
                onChange={(e) => setAltText(e.target.value)}
              />
            )}
          </div>
        )}

        <DialogFooter className="gap-2">
          <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button onClick={handleConfirm} disabled={!canConfirm}>Insert</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
