"use client"

import { useState, useRef, useEffect } from "react"
import AppLayout from "@/Layouts/AppLayout"
import { Button } from "@/Components/UI/Button"
import { Input } from "@/Components/UI/Input"
import Pagination from "@/Components/UI/Pagination"
import { Card, CardContent } from "@/Components/UI/Card"
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/Components/UI/Tabs"
import { Modal } from "@/Components/UI/Modal"
import DeleteModal from "@/Components/DeleteModal"
import { useDeleteHandler } from '@/hooks/useDeleteHandler';
import useTranslate from "@/hooks/useTranslate"
import FileUploadField from "@/Components/UI/FileUploadField"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/UI/Select"
import { route } from "ziggy-js"
import { motion, AnimatePresence } from "framer-motion";


import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/Components/UI/DropdownMenu"
import {
  Grid3X3,
  List,
  Search,
  Upload,
  Play,
  Eye,
  Download,
  Trash2,
  ChevronDown,
  MoreVertical,
  ChevronLeft,
  ChevronRight,
  Image,
  FolderOpen,
} from "lucide-react"
import { router } from "@inertiajs/react"



export default function Gallery({ platforms, media }) {
  const [viewMode, setViewMode] = useState("grid")
  const [activeFilter, setActiveFilter] = useState("all")
  const [selectedPlatform, setSelectedPlatform] = useState("facebook")
  const [intendedPlatform, setIntendedPlatform] = useState("all")

  const [searchQuery, setSearchQuery] = useState("")
  const [currentPage, setCurrentPage] = useState(2)
  const [previewModal, setPreviewModal] = useState({ isOpen: false, item: null, currentIndex: 0 })
  const [mediaUploadModalOpen, setMediaUploadModalOpen] = useState(false)
  const [files, setFiles] = useState([])
  const fileInputRef = useRef(null)
  const [isFileSubmitting, setIsFileSubmitting] = useState(false)
  const [uploadProgress, setUploadProgress] = useState(0)
  const [uploadingFiles, setUploadingFiles] = useState([])

  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)
  const [mediaToDelete, setMediaToDelete] = useState(null)
  const [mediaItems, setMediaItems] = useState(media.data || [])

  useEffect(() => {
    setMediaItems(media.data)
  }, [media])




  const t = useTranslate()

  const filteredItems = mediaItems.filter((item) => {
    if (activeFilter === "images" && item.isVideo) return false
    if (activeFilter === "videos" && !item.isVideo) return false
    if (searchQuery && !item.title.toLowerCase().includes(searchQuery.toLowerCase())) return false
    return true
  })

  const openPreview = (item) => {
    const currentIndex = filteredItems.findIndex((i) => i.id === item.id)
    setPreviewModal({ isOpen: true, item, currentIndex })
  }

  const closePreview = () => {
    setPreviewModal({ isOpen: false, item: null, currentIndex: 0 })
  }

  const navigatePreview = (direction) => {
    const newIndex =
      direction === "next"
        ? (previewModal.currentIndex + 1) % filteredItems.length
        : (previewModal.currentIndex - 1 + filteredItems.length) % filteredItems.length

    const newItem = filteredItems[newIndex]
    setPreviewModal({ ...previewModal, item: newItem, currentIndex: newIndex })
  }



  const handleFilesChange = (newFiles) => {
    const filesArray = Array.isArray(newFiles) ? newFiles : (newFiles ? [newFiles] : [])
    setFiles(filesArray)
  }

  const handlePlatformChange = (platformSlug) => {
    setSelectedPlatform(platformSlug)

    router.get(route('user.gallery.index'),
      { slug: platformSlug }
    )

  };


  const handleUpload = () => {
    if (!files || files.length === 0) {
      alert('Please select at least one file to upload')
      return
    }

    if (!intendedPlatform) {
      alert('Please select a platform')
      return
    }

    setIsFileSubmitting(true)
    setUploadProgress(0)
    setUploadingFiles(files.map(f => ({ name: f.name, status: 'uploading', progress: 0 })))

    // Create FormData for file upload
    const formData = new FormData()
    files.forEach((file, index) => {
      formData.append(`media[${index}]`, file)
    })
    formData.append('platform_id', intendedPlatform)

    // Handle CSRF token safely
    const csrfMeta = document.querySelector('meta[name="csrf-token"]')
    const csrfToken = csrfMeta ? csrfMeta.getAttribute('content') : null
    if (csrfToken) {
      formData.append('_token', csrfToken)
    } else {
      console.warn('CSRF token not found, using alternative method')
    }

    // Use Inertia router for reliable CSRF handling
    router.post(route('user.gallery.store'),
      {
        media: files,
        platform_id: intendedPlatform
      },
      {
        forceFormData: true,
        onSuccess: () => {
          setUploadingFiles(files.map(f => ({ name: f.name, status: 'completed', progress: 100 })))
          setTimeout(() => {
            router.reload({ only: ['media'] })
            setIsFileSubmitting(false)
            setMediaUploadModalOpen(false)
            setFiles([])
            setUploadProgress(0)
            setUploadingFiles([])
          }, 1000)
        },
        onError: (errors) => {
          console.error('Upload failed:', errors)
          setUploadingFiles(files.map(f => ({ name: f.name, status: 'error', progress: 0 })))

          // Show specific error messages
          const errorMessages = Object.values(errors).flat()
          const errorMessage = errorMessages.length > 0
            ? errorMessages.join('\\n')
            : 'Upload failed. Please try again.'
          alert(errorMessage)

          setIsFileSubmitting(false)
        }
      }
    )
  }

  const handleDeleteClick = (item) => {

    setMediaToDelete(item)
    setIsDeleteModalOpen(true)
  }

  const { handleDelete, isDeleting } = useDeleteHandler('user.gallery.item.delete', (deletedId) => {
    setMediaItems((prev) => prev.filter((m) => m.id !== deletedId));
    setIsDeleteModalOpen(false);
    setMediaToDelete(null);
  });

  const handleDownload = (item) => {
    fetch(item.thumbnail)
      .then((res) => res.blob())
      .then((blob) => {
        const link = document.createElement("a");
        link.href = window.URL.createObjectURL(blob);
        link.download = item.title || "file";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      })
      .catch(() => alert("Download failed"));
  };

  const handleSearch = (e) => {
    setSearchQuery(e.target.value)

    router.get(
      route("user.gallery.index"),
      {
        search: searchQuery,
      },
      {
        preserveState: true,
        preserveScroll: true,

      }
    );
  };



  const MediaCard = ({ item }) => (
    <Card className="overflow-hidden hover:shadow-md transition-shadow">
      <CardContent className="p-0">
        <div className="relative">
          <img src={item.thumbnail || "/placeholder.svg"} alt={item.title} className="w-full h-24 object-cover" />
          {item.isVideo && (
            <div className="absolute inset-0 flex items-center justify-center overflow-hidden">
              <video
                src={item.thumbnail}
                muted
                playsInline
                loop
                autoPlay
              />
            </div>
          )}
          <div className="absolute top-2 right-2">
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-8 w-8 p-0 bg-black/20 hover:bg-black/40 text-white rounded-full"
                >
                  <MoreVertical className="h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-32">
                <DropdownMenuItem className="flex items-center gap-2" onClick={() => openPreview(item)}>
                  <Eye className="h-4 w-4" />
                  Preview
                </DropdownMenuItem >
                <DropdownMenuItem className="flex items-center gap-2" onClick={() => handleDownload(item)}>
                  <Download className="h-4 w-4" />
                  Download
                </DropdownMenuItem>
                <DropdownMenuItem className="flex items-center gap-2 text-red-600" onClick={() => handleDeleteClick(item)} >
                  <Trash2 className="h-4 w-4" />
                  Delete
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
        <div className="p-4">
          <h3 className="font-medium text-sm mb-1 truncate">{item.title}</h3>
          <p className="text-xs text-muted-foreground">{item.type}</p>
        </div>
      </CardContent>
    </Card>
  )

  const MediaListItem = ({ item }) => (
    <div className="flex items-center gap-4 p-4 border-b border-gray-200 dark:border-zinc-800 md:flex-nowrap flex-wrap hover:bg-muted/50 transition-colors">
  {/* Thumbnail */}
  <div className="relative flex-shrink-0">
    <img
      src={item.thumbnail || "/placeholder.svg"}
      alt={item.title}
      className="w-16 h-12 object-cover rounded"
    />
    {item.isVideo && (
      <div className="absolute inset-0 flex items-center justify-center">
        <div className="bg-black/50 rounded-full p-1">
          <Play className="h-3 w-3 text-white fill-white" />
        </div>
      </div>
    )}
  </div>

  {/* Title + Type */}
  <div className="flex-1 min-w-0">
    <h3 className="font-medium text-sm truncate">{item.title}</h3>
    <p className="text-xs text-muted-foreground">{item.type}</p>
  </div>

  {/* Meta info */}
  <div className="text-xs text-muted-foreground md:text-right text-left w-full md:w-auto">
    <p className="mb-2">Size: {item.size}</p>
    <p>Date: {item.date}</p>
  </div>

  {/* Action buttons */}
  <div className="flex gap-2 w-full md:w-auto justify-start md:justify-end">
    <Button
      size="sm"
      variant="outline"
      className="h-8 w-8 p-0 bg-blue-500 hover:bg-blue-600 text-white border-blue-500"
      onClick={() => openPreview(item)}
    >
      <Eye className="h-4 w-4" />
    </Button>
    <Button
      size="sm"
      variant="outline"
      className="h-8 w-8 p-0 bg-green-500 hover:bg-green-600 text-white border-green-500"
      onClick={() => handleDownload(item)}
    >
      <Download className="h-4 w-4" />
    </Button>
    <Button
      size="sm"
      variant="outline"
      className="h-8 w-8 p-0 bg-red-500 hover:bg-red-600 text-white border-red-500"
      onClick={() => handleDeleteClick(item)}
    >
      <Trash2 className="h-4 w-4" />
    </Button>
  </div>
</div>

  )

  const breadcrumbs = [{ label: "Home", href: route("user.home") }, { label: "Gallery" }]

  return (
    <AppLayout breadcrumbs={breadcrumbs}>
      <div className="flex-1 p-6 overflow-auto bg-gray-50 dark:bg-black">
        {/* Header */}
        <div className="mb-6">
          <div className="flex items-center gap-3 mb-2">
            <div>
              <Image className="h-6 w-6 text-primary" />
            </div>
            <h1 className="text-xl sm:text-2xl dark:text-gray-200 font-bold">
              {t("Media Gallery")}
            </h1>
          </div>
          <p className="text-gray-500 dark:text-gray-200">
            {t("Upload, organize and manage your media files for social media posts")}
          </p>
        </div>

        <Tabs defaultValue="all" onValueChange={setActiveFilter} className="space-y-6">
          <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 mb-6">
            <TabsList className="inline-flex bg-white rounded-lg p-1 shadow-sm gap-1 ltr:flex-row rtl:flex-row-reverse">
              <TabsTrigger
                value="all"
                className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-primary data-[state=active]:to-secondary data-[state=active]:text-white data-[state=active]:shadow-sm rounded-md px-4 py-2 text-sm font-medium transition-colors"
              >
                All
              </TabsTrigger>
              <TabsTrigger
                value="images"
                className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-primary data-[state=active]:to-secondary data-[state=active]:text-white data-[state=active]:shadow-sm rounded-md px-4 py-2 text-sm font-medium transition-colors"
              >
                Images
              </TabsTrigger>
              <TabsTrigger
                value="videos"
                className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-primary data-[state=active]:to-secondary data-[state=active]:text-white data-[state=active]:shadow-sm rounded-md px-4 py-2 text-sm font-medium transition-colors"
              >
                Videos
              </TabsTrigger>
            </TabsList>

            <div className="flex items-center flex-wrap gap-3">
              <div className="flex border border-gray-300 dark:border-gray-600 rounded-lg overflow-hidden">
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => setViewMode("grid")}
                  className={`h-9 px-3 rounded-none dark:text-gray-100 ${viewMode === "grid" ? "bg-gray-200 dark:bg-gray-700 dark:text-gray-100" : "hover:bg-gray-100 dark:hover:bg-gray-800"
                    }`}
                >
                  <Grid3X3 className="h-4 w-4" />
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => setViewMode("list")}
                  className={`h-9 px-3 rounded-none dark:text-gray-100 ${viewMode === "list" ? "bg-gray-200 dark:bg-gray-700" : "hover:bg-gray-100 dark:hover:bg-gray-800"
                    }`}
                >
                  <List className="h-4 w-4" />
                </Button>
              </div>

              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
                <Input
                  placeholder="Search"
                  value={searchQuery}
                  onChange={(e) => handleSearch(e)}
                  className="pl-10 w-64"
                />
              </div>

              <Button
                variant="white"
                onClick={() => {
                  setMediaUploadModalOpen(true)
                  setFiles([])
                  setIntendedPlatform('all')
                }}
                className="bg-gradient-to-r from-primary to-secondary hover:from-secondary hover:to-primary text-white border-0 shadow-sm"
              >
                <Upload className="h-4 w-4 mr-2" />
                Upload Media
              </Button>

              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="outline" className="min-w-[140px] justify-between">
                    {platforms.find((p) => p.slug === selectedPlatform)?.name || "Select Platform"}
                    <ChevronDown className="h-4 w-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end" className="w-[140px]">
                  {platforms.map((platform) => (
                    <DropdownMenuItem
                      key={platform.slug}
                      onClick={() => handlePlatformChange(platform.slug)}
                      className={selectedPlatform === platform.slug ? "bg-gray-100 dark:bg-gray-800" : ""}
                    >
                      {platform.name}
                    </DropdownMenuItem>
                  ))}
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          </div>
          
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.2 }}>
              <TabsContent value="all" className="mt-0">
                <div className="mb-8">
                  {filteredItems.length === 0 ? (
                    // Empty State
                    <div className="bg-white dark:bg-zinc-900 rounded-xl border border-gray-200 dark:border-zinc-800 p-12">
                      <div className="text-center">
                        <div className="mx-auto w-16 h-16 bg-gradient-to-br from-primary/10 to-secondary/10 rounded-xl flex items-center justify-center mb-4">
                          <FolderOpen className="h-8 w-8 text-gray-400 dark:text-gray-500" />
                        </div>
                        <div className="space-y-2 mb-6">
                          <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">No media files yet</h3>
                          <p className="text-sm text-gray-500 dark:text-gray-400 max-w-sm mx-auto">
                            {searchQuery ?
                              "No media files match your search criteria. Try adjusting your search terms." :
                              "Upload your first media files to get started. You can add images and videos for your social media posts."
                            }
                          </p>
                        </div>
                        {!searchQuery && (
                          <Button
                            variant="white"
                            onClick={() => {
                              setMediaUploadModalOpen(true)
                              setFiles([])
                              setIntendedPlatform('all')
                            }}
                            className="bg-gradient-to-r from-primary to-secondary hover:from-secondary hover:to-primary text-white border-0 shadow-sm"
                          >
                            <Upload className="h-4 w-4 mr-2" />
                            Upload Your First Media
                          </Button>
                        )}
                      </div>
                    </div>
                  ) : (
                    // Media Grid/List
                    viewMode === "grid" ? (
                      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
                        {filteredItems.map((item) => (
                          <MediaCard key={item.id} item={item} />
                        ))}
                      </div>
                    ) : (
                      <div className="bg-white dark:bg-zinc-900 rounded-lg border border-gray-200 dark:border-zinc-800 overflow-hidden">
                        {filteredItems.map((item) => (
                          <MediaListItem key={item.id} item={item} />
                        ))}
                      </div>
                    )
                  )}
                </div>
              </TabsContent>
           
              <TabsContent value="images" className="mt-0">
            <div className="mb-8">
              {filteredItems.length === 0 ? (
                // Empty State for Images
                <div className="bg-white dark:bg-zinc-900 rounded-xl border border-gray-200 dark:border-zinc-800 p-12">
                  <div className="text-center">
                    <div className="mx-auto w-16 h-16 bg-gradient-to-br from-primary/10 to-secondary/10 rounded-xl flex items-center justify-center mb-4">
                      <Image className="h-8 w-8 text-gray-400 dark:text-gray-500" />
                    </div>
                    <div className="space-y-2 mb-6">
                      <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">No images found</h3>
                      <p className="text-sm text-gray-500 dark:text-gray-400 max-w-sm mx-auto">
                        {searchQuery ?
                          "No images match your search criteria. Try adjusting your search terms." :
                          "Upload your first images to create engaging visual content for your social media posts."
                        }
                      </p>
                    </div>
                    {!searchQuery && (
                      <Button
                        variant="white"
                        onClick={() => {
                          setMediaUploadModalOpen(true)
                          setFiles([])
                          setIntendedPlatform('all')
                        }}
                        className="bg-gradient-to-r from-primary to-secondary hover:from-secondary hover:to-primary text-white border-0 shadow-sm"
                      >
                        <Upload className="h-4 w-4 mr-2" />
                        Upload Images
                      </Button>
                    )}
                  </div>
                </div>
              ) : (
                // Images Grid/List
                viewMode === "grid" ? (
                  <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
                    {filteredItems.map((item) => (
                      <MediaCard key={item.id} item={item} />
                    ))}
                  </div>
                ) : (
                  <div className="bg-white dark:bg-zinc-900 rounded-lg border border-gray-200 dark:border-zinc-800 overflow-hidden">
                    {filteredItems.map((item) => (
                      <MediaListItem key={item.id} item={item} />
                    ))}
                  </div>
                )
              )}
            </div>
              </TabsContent>
          
              <TabsContent value="videos" className="mt-0">
                <div className="mb-8">
                  {filteredItems.length === 0 ? (
                    // Empty State for Videos
                    <div className="bg-white dark:bg-zinc-900 rounded-xl border border-gray-200 dark:border-zinc-800 p-12">
                      <div className="text-center">
                        <div className="mx-auto w-16 h-16 bg-gradient-to-br from-primary/10 to-secondary/10 rounded-xl flex items-center justify-center mb-4">
                          <Play className="h-8 w-8 text-gray-400 dark:text-gray-500" />
                        </div>
                        <div className="space-y-2 mb-6">
                          <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">No videos found</h3>
                          <p className="text-sm text-gray-500 dark:text-gray-400 max-w-sm mx-auto">
                            {searchQuery ?
                              "No videos match your search criteria. Try adjusting your search terms." :
                              "Upload your first videos to create dynamic content for your social media posts."
                            }
                          </p>
                        </div>
                        {!searchQuery && (
                          <Button
                            variant="white"
                            onClick={() => {
                              setMediaUploadModalOpen(true)
                              setFiles([])
                              setIntendedPlatform('all')
                            }}
                            className="bg-gradient-to-r from-primary to-secondary hover:from-secondary hover:to-primary text-white border-0 shadow-sm"
                          >
                            <Upload className="h-4 w-4 mr-2" />
                            Upload Videos
                          </Button>
                        )}
                      </div>
                    </div>
                  ) : (
                    // Videos Grid/List
                    viewMode === "grid" ? (
                      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
                        {filteredItems.map((item) => (
                          <MediaCard key={item.id} item={item} />
                        ))}
                      </div>
                    ) : (
                      <div className="bg-white dark:bg-zinc-900 rounded-lg border border-gray-200 dark:border-zinc-800 overflow-hidden">
                        {filteredItems.map((item) => (
                          <MediaListItem key={item.id} item={item} />
                        ))}
                      </div>
                    )
                  )}
                </div>
              </TabsContent>
          </motion.div>

        </Tabs>

        <Pagination
          links={media.links}
          currentPage={media.current_page}
          lastPage={media.last_page}
          only={['media']}
          className="mt-4"
        />


        <Modal
          isOpen={previewModal.isOpen}
          onClose={closePreview}
          title="Detail Image"
          showSubmit={false}
          width="w-[48rem]"

        >
          {previewModal.item && (
            <div className="flex gap-4 h-[40vh]">
              {/* Left side - Image preview */}
              <div className="flex-1 flex items-center justify-center relative bg-gray-50 rounded-lg overflow-hidden">
                <Button
                  variant="ghost"
                  size="sm"
                  className="absolute left-2 top-1/2 -translate-y-1/2 h-7 w-7 p-0 bg-black/20 hover:bg-black/40 text-white rounded-full z-10"
                  onClick={() => navigatePreview("prev")}
                >
                  <ChevronLeft className="h-3 w-3" />
                </Button>

                <div className="w-full h-full flex items-center justify-center p-3">
                  <img
                    src={previewModal.item.thumbnail || "/placeholder.svg"}
                    alt={previewModal.item.title}
                    className="max-w-full max-h-full object-contain rounded-lg shadow-sm"
                  />
                </div>

                <Button
                  variant="ghost"
                  size="sm"
                  className="absolute right-2 top-1/2 -translate-y-1/2 h-7 w-7 p-0 bg-black/20 hover:bg-black/40 text-white rounded-full z-10"
                  onClick={() => navigatePreview("next")}
                >
                  <ChevronRight className="h-3 w-3" />
                </Button>
              </div>

              {/* Right side - File details */}
              <div className="w-64 flex flex-col justify-between py-2">
                <div className="space-y-4">
                  <div className="space-y-4">
                    <div className="flex justify-between items-start">
                      <span className="text-xs font-medium text-gray-600 dark:text-gray-400">File Name</span>
                      <span className="text-xs text-right max-w-32 truncate font-medium">
                        {previewModal.item.title}
                      </span>
                    </div>

                    <div className="flex justify-between items-center">
                      <span className="text-xs font-medium text-gray-600 dark:text-gray-400">Resolution</span>
                      <span className="text-xs font-medium">2400 x 1600</span>
                    </div>

                    <div className="flex justify-between items-center">
                      <span className="text-xs font-medium text-gray-600 dark:text-gray-400">File Type</span>
                      <span className="text-xs font-medium">Image</span>
                    </div>

                    <div className="flex justify-between items-center">
                      <span className="text-xs font-medium text-gray-600 dark:text-gray-400">Size</span>
                      <span className="text-xs font-medium">{previewModal.item.size}</span>
                    </div>

                    <div className="flex justify-between items-center">
                      <span className="text-xs font-medium text-gray-600 dark:text-gray-400">Date</span>
                      <span className="text-xs font-medium">{previewModal.item.date}</span>
                    </div>
                  </div>
                </div>

                {/* Action buttons positioned at bottom right */}
                <div className="flex gap-2 justify-end pt-4">
                  <Button
                    variant="outline"
                    size="sm"
                    className="text-gray-600 hover:text-gray-800 bg-transparent border-gray-300"
                  >
                    Delete
                  </Button>
                  <Button size="sm" className="bg-cyan-500 hover:bg-cyan-600 text-white px-4">
                    Download
                  </Button>
                </div>
              </div>
            </div>
          )}
        </Modal>


        <Modal
          isDataSubmitting={isFileSubmitting}
          isOpen={mediaUploadModalOpen}
          onClose={() => {
            if (!isFileSubmitting) {
              setMediaUploadModalOpen(false)
              setFiles([])
              setUploadProgress(0)
              setUploadingFiles([])
            }
          }}
          title="Upload Media"
          showSubmit={true}
          width="w-[56rem]"
          maxHeight="max-h-[85vh]"
          onSubmit={handleUpload}
          submitText={isFileSubmitting ? `Uploading ${files.length} file(s)...` : `Upload ${files.length} file(s)`}
        >
          <div className="space-y-6">
            {/* File upload */}
            <FileUploadField
              label="Select Media Files (Images & Videos)"
              accept="image/*,video/*"
              field="media_files"
              multiple={true}
              onChange={handleFilesChange}
              value={files}
              hint="Support: JPG, PNG, GIF, MP4, MOV, AVI. Max 20MB per file. You can select multiple files at once."
            />

            {/* Platform select */}
            <div>
              <label className="block text-sm font-medium text-gray-900 dark:text-gray-100 mb-2">
                Select Platform *
              </label>
              <Select
                value={intendedPlatform}
                onValueChange={(value) => setIntendedPlatform(value)}
                disabled={isFileSubmitting}
              >
                <SelectTrigger className="w-full bg-white dark:bg-zinc-800 border-gray-300 dark:border-zinc-600">
                  <SelectValue placeholder="Choose a platform" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem key="all" value="all">
                    All Platforms
                  </SelectItem>
                  {platforms.map((platform) => (
                    <SelectItem key={platform.id} value={platform.id.toString()}>
                      {platform.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                Choose "All Platforms" to make files accessible across all platforms, or select a specific platform
              </p>
            </div>

            {/* Upload Progress */}
            {isFileSubmitting && uploadingFiles.length > 0 && (
              <div className="space-y-3 border-t border-gray-200 dark:border-zinc-800 pt-4">
                <div className="flex items-center justify-between">
                  <h4 className="text-sm font-medium text-gray-900 dark:text-gray-100">
                    Upload Progress
                  </h4>
                  <span className="text-sm text-gray-500 dark:text-gray-400">
                    {uploadingFiles.filter(f => f.status === 'completed').length} / {uploadingFiles.length} completed
                  </span>
                </div>
                <div className="space-y-2 max-h-48 overflow-y-auto border border-gray-200 dark:border-zinc-800 rounded-lg p-2">
                  {uploadingFiles.map((file, index) => (
                    <div key={index} className="flex items-center space-x-3 p-2 bg-gray-50 dark:bg-gray-800 rounded">
                      <div className={`w-2 h-2 rounded-full ${
                        file.status === 'completed' ? 'bg-green-500' :
                        file.status === 'error' ? 'bg-red-500' :
                        'bg-blue-500 animate-pulse'
                      }`} />
                      <span className="text-sm text-gray-700 dark:text-gray-300 truncate flex-1">
                        {file.name}
                      </span>
                      <span className="text-xs text-gray-500 dark:text-gray-400">
                        {file.status === 'completed' ? 'Done' :
                         file.status === 'error' ? 'Error' :
                         'Uploading...'}
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        </Modal>


        {/* Delete Modal */}
        <DeleteModal
          isOpen={isDeleteModalOpen}
          onClose={() => setIsDeleteModalOpen(false)}
          title="Delete this Media?"
          description="Are you really sure you want to delete this media?"
          onConfirm={() => handleDelete(mediaToDelete?.id)}
          isDeleting={isDeleting}
        />
      </div>
    </AppLayout>
  )
}
