"use client";

import { useMemo, useRef, useState } from "react";
import { FileVideo2, UploadCloud, X } from "lucide-react";

import { Button } from "@/components/ui/button";
import {
  formatBytes,
  validateClientFile,
  type ClientFileValidationOptions
} from "@/lib/client/file-validation";

interface MediaUploadDropzoneProps {
  file?: File | null;
  onFileSelected: (file: File) => void;
  onClear?: () => void;
  disabled?: boolean;
  busy?: boolean;
  title?: string;
  description?: string;
  accept?: string;
  validation?: ClientFileValidationOptions;
  onValidationError?: (message: string) => void;
}

export function MediaUploadDropzone({
  file = null,
  onFileSelected,
  onClear,
  disabled = false,
  busy = false,
  title = "Upload source media",
  description = "Drop a video file here or browse from your device.",
  accept = "video/*,.mp4,.mov,.m4v,.webm,.mkv,.avi,.wmv,.flv",
  validation,
  onValidationError
}: MediaUploadDropzoneProps) {
  const inputRef = useRef<HTMLInputElement>(null);
  const [isDragActive, setIsDragActive] = useState(false);

  const isBlocked = disabled || busy;

  const fileSubtitle = useMemo(() => {
    if (!file) {
      return description;
    }

    return `${formatBytes(file.size)} • ${file.type || "unknown format"}`;
  }, [description, file]);

  const processFile = (candidate: File | null | undefined) => {
    if (!candidate) {
      return;
    }

    const validationResult = validateClientFile(candidate, validation);
    if (!validationResult.ok) {
      onValidationError?.(validationResult.errors[0] ?? "File validation failed.");
      return;
    }

    onFileSelected(candidate);
  };

  return (
    <section className="space-y-3">
      <div
        className={`glass-panel rounded-2xl border border-dashed p-6 transition ${
          isDragActive ? "border-sky-300/70 bg-sky-500/10" : "border-white/20"
        } ${isBlocked ? "cursor-not-allowed opacity-70" : ""}`}
        role="button"
        tabIndex={isBlocked ? -1 : 0}
        aria-disabled={isBlocked}
        aria-busy={busy}
        aria-label={file ? `Selected media ${file.name}` : "Upload source media"}
        onDragOver={(event) => {
          event.preventDefault();
          if (isBlocked) {
            return;
          }
          setIsDragActive(true);
        }}
        onDragLeave={() => setIsDragActive(false)}
        onDrop={(event) => {
          event.preventDefault();
          setIsDragActive(false);
          if (isBlocked) {
            return;
          }

          processFile(event.dataTransfer.files?.[0]);
        }}
        onKeyDown={(event) => {
          if (isBlocked) {
            return;
          }

          if (event.key === "Enter" || event.key === " ") {
            event.preventDefault();
            inputRef.current?.click();
          }
        }}
      >
        <div className="flex flex-col items-center gap-3 text-center">
          <span className="inline-flex size-12 items-center justify-center rounded-2xl border border-white/15 bg-white/5">
            {file ? <FileVideo2 className="size-6 text-sky-200" /> : <UploadCloud className="size-6 text-slate-300" />}
          </span>
          <div className="space-y-1">
            <p className="text-sm font-medium text-slate-100">{file ? file.name : title}</p>
            <p className="text-xs text-slate-400">{fileSubtitle}</p>
          </div>
          <div className="flex flex-wrap justify-center gap-2">
            <input
              ref={inputRef}
              hidden
              type="file"
              accept={accept}
              disabled={isBlocked}
              onChange={(event) => processFile(event.target.files?.[0])}
            />
            <Button
              variant="outline"
              size="sm"
              className="border-white/20 bg-slate-900/70 text-slate-200 hover:bg-slate-800 focus-visible:ring-sky-300/60"
              disabled={isBlocked}
              onClick={() => inputRef.current?.click()}
            >
              {file ? "Replace File" : "Choose File"}
            </Button>
            {file && onClear ? (
              <Button variant="ghost" size="sm" disabled={isBlocked} onClick={onClear}>
                <X data-icon="inline-start" />
                Clear
              </Button>
            ) : null}
          </div>
          <p className="text-[11px] uppercase tracking-wide text-slate-500">Tap, click, or drag a file</p>
        </div>
      </div>
    </section>
  );
}
