"use client";

import { useState, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@/lib/queryClient";
import { X, Upload, Image, AlertCircle } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { GalleryItem } from "@/models/GalleryItem";

interface MediaUploaderProps {
  onSuccess?: () => void;
  galleries?: any[] | GalleryItem[];
}

export const categories = [
  { value: "image", label: "Image" },
  { value: "video", label: "Video" },
  { value: "audio", label: "Audio" },
  { value: "document", label: "Document" },
  { value: "3d", label: "3D Model" },
];
export default function MediaUploader({
  onSuccess,
  galleries = [],
}: MediaUploaderProps) {
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [category, setCategory] = useState("image");
  const [filePreview, setFilePreview] = useState<string | null>(null);
  const [dragActive, setDragActive] = useState(false);
  const [uploadError, setUploadError] = useState<string | null>(null);
  const { toast } = useToast();

  const fileInputRef = useRef<HTMLInputElement>(null);
  const queryClient = useQueryClient();

  // File upload state
  const [file, setFile] = useState<File | null>(null);

  // Upload mutation
  const uploadMutation = useMutation({
    mutationFn: async (formData: FormData) => {
      const response = await apiRequest("POST", "/galleries", formData);
      return response;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/admin/media"] });
      toast({
        title: "Upload Successful",
        description: "Your media has been successfully uploaded",
      });
      resetForm();
      if (onSuccess) onSuccess();
    },
    onError: (error: any) => {
      console.error("Upload error:", error);
      toast(error.message || "Failed to upload the media. Please try again.");
    },
  });

  const resetForm = () => {
    setTitle("");
    setDescription("");
    setCategory("image");
    setFile(null);
    setFilePreview(null);
    setUploadError(null);
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = e.target.files?.[0];
    handleFile(selectedFile);
  };

  const handleFile = (selectedFile?: File | null) => {
    setUploadError(null);

    if (!selectedFile) {
      return;
    }

    // Validate file type based on selected category
    const isImage = selectedFile.type.startsWith("image/");
    const isVideo = selectedFile.type.startsWith("video/");
    const isAudio = selectedFile.type.startsWith("audio/");

    if (
      (category === "image" && !isImage) ||
      (category === "video" && !isVideo) ||
      (category === "audio" && !isAudio)
    ) {
      setUploadError(`Invalid file type. Please upload a ${category} file.`);
      return;
    }

    // Validate file size (10MB max)
    if (selectedFile.size > 10 * 1024 * 1024) {
      setUploadError("File size too large. Maximum size is 10MB.");
      return;
    }

    setFile(selectedFile);

    // Create preview for images
    if (isImage) {
      const reader = new FileReader();
      reader.onload = (e) => {
        setFilePreview(e.target?.result as string);
      };
      reader.readAsDataURL(selectedFile);
    } else {
      // For non-images, just show the file name
      setFilePreview(null);
    }
  };

  const handleDrag = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();

    if (e.type === "dragenter" || e.type === "dragover") {
      setDragActive(true);
    } else if (e.type === "dragleave") {
      setDragActive(false);
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);

    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      handleFile(e.dataTransfer.files[0]);
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    if (!file) {
      setUploadError("Please select a file to upload");
      return;
    }

    if (!title.trim()) {
      setUploadError("Please provide a title");
      return;
    }

    const formData = new FormData();
    formData.append("file", file);
    formData.append("title", title);
    formData.append("description", description);
    formData.append("category", category);

    const formDataObject: Record<string, any> = {};
    for (const [key, value] of formData.entries()) {
      formDataObject[key] = value;
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
          <div
            className={`h-72 border-2 border-dashed rounded-md flex flex-col items-center justify-center cursor-pointer transition-colors ${
              dragActive ? "border-primary bg-primary/5" : "border-border"
            } ${uploadError ? "border-destructive" : ""}`}
            onDragEnter={handleDrag}
            onDragOver={handleDrag}
            onDragLeave={handleDrag}
            onDrop={handleDrop}
            onClick={() => fileInputRef.current?.click()}
          >
            {filePreview ? (
              <div className="relative w-full h-full p-2">
                <img
                  src={filePreview}
                  alt="Preview"
                  className="w-full h-full object-contain"
                />
                <Button
                  type="button"
                  variant="destructive"
                  size="icon"
                  className="absolute top-1 right-1"
                  onClick={(e) => {
                    e.stopPropagation();
                    setFile(null);
                    setFilePreview(null);
                  }}
                >
                  <X className="h-4 w-4" />
                </Button>
              </div>
            ) : (
              <>
                <Input
                  ref={fileInputRef}
                  type="file"
                  className="hidden"
                  onChange={handleFileChange}
                  accept={
                    category === "image"
                      ? "image/*"
                      : category === "video"
                      ? "video/*"
                      : "audio/*"
                  }
                />
                <div className="text-center">
                  {uploadError ? (
                    <AlertCircle className="h-10 w-10 mx-auto text-destructive mb-2" />
                  ) : (
                    <>
                      {category === "image" ? (
                        <Image className="h-10 w-10 mx-auto text-muted-foreground mb-2" />
                      ) : (
                        <Upload className="h-10 w-10 mx-auto text-muted-foreground mb-2" />
                      )}
                    </>
                  )}
                  {uploadError ? (
                    <p className="text-sm text-destructive mb-1">
                      {uploadError}
                    </p>
                  ) : (
                    <p className="text-sm text-muted-foreground mb-1">
                      {file
                        ? file.name
                        : `Drag and drop your ${category} here, or click to browse`}
                    </p>
                  )}
                  <p className="text-xs text-muted-foreground">
                    Max file size: 10MB
                  </p>
                </div>
              </>
            )}
          </div>
        </div>

        <div className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="title">Title</Label>
            <Input
              id="title"
              placeholder="Enter a title for your Gallery"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              required
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="description">Description (optional)</Label>
            <Textarea
              id="description"
              placeholder="Provide a brief description..."
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              rows={3}
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="category">Category</Label>
            <Select value={category} onValueChange={setCategory}>
              <SelectTrigger id="category">
                <SelectValue placeholder="Select category" />
              </SelectTrigger>
              <SelectContent>
                {categories.map((type) => (
                  <SelectItem key={type.value} value={type.value}>
                    {type.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>
      </div>

      <div className="flex justify-end space-x-3">
        <Button type="button" variant="outline" onClick={resetForm}>
          Reset
        </Button>
        <Button type="submit" disabled={uploadMutation.isPending || !file}>
          {uploadMutation.isPending ? "Uploading..." : "Submit"}
        </Button>
      </div>
    </form>
  );
}
