"use client";
import { useState, useRef, useCallback } from "react";
import { PageHeader } from "@/components/page-header";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { toast } from "sonner";
import { UploadCloud, Search, Copy, Trash2, Image as ImageIcon, FileVideo, File, ZoomIn, X, FolderPlus, Folder, ChevronRight, MoreVertical } from "lucide-react";
import { deleteMedia, createMediaFolder, deleteMediaFolder, moveMediaToFolder } from "@/app/actions/media";
import { Dialog, DialogContent } from "@/components/ui/dialog";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { ResponsiveModal } from "@/components/ui/responsive-modal";
import { Label } from "@/components/ui/label";

function formatBytes(b: number) {
  if (b < 1024) return b + " B";
  if (b < 1048576) return (b / 1024).toFixed(1) + " KB";
  return (b / 1048576).toFixed(1) + " MB";
}

export default function MediaPageClient({ initialMedia, initialFolders }: { initialMedia: any[], initialFolders: any[] }) {
  const [media, setMedia] = useState(initialMedia);
  const [folders, setFolders] = useState(initialFolders);
  const [currentFolderId, setCurrentFolderId] = useState<string | null>(null);
  
  const [search, setSearch] = useState("");
  const [filterType, setFilterType] = useState<"all" | "image" | "video" | "other">("all");
  const [uploading, setUploading] = useState(false);
  const [preview, setPreview] = useState<any>(null);
  
  const [deleteId, setDeleteId] = useState<string | null>(null);
  const [deleteFolderId, setDeleteFolderId] = useState<string | null>(null);
  
  const [isFolderModalOpen, setIsFolderModalOpen] = useState(false);
  const [newFolderName, setNewFolderName] = useState("");
  
  const [isDragging, setIsDragging] = useState(false);
  const fileRef = useRef<HTMLInputElement>(null);

  const currentFolder = currentFolderId ? folders.find(f => f.id === currentFolderId) : null;
  const childFolders = folders.filter(f => f.parentId === currentFolderId);
  
  const displayedMedia = media.filter(m => m.folderId === currentFolderId);

  const filtered = displayedMedia.filter(m => {
    const matchSearch = !search || m.filename.toLowerCase().includes(search.toLowerCase()) || (m.alt && m.alt.includes(search));
    const matchType = filterType === "all" ||
      (filterType === "image" && m.mimeType?.startsWith("image/")) ||
      (filterType === "video" && m.mimeType?.startsWith("video/")) ||
      (filterType === "other" && !m.mimeType?.startsWith("image/") && !m.mimeType?.startsWith("video/"));
    return matchSearch && matchType;
  });

  const uploadFile = async (file: File) => {
    const formData = new FormData();
    formData.append("file", file);
    try {
      const res = await fetch("/api/upload", { method: "POST", body: formData });
      const data = await res.json();
      if (data.success) {
        if (currentFolderId) {
          await moveMediaToFolder([data.media.id], currentFolderId);
          data.media.folderId = currentFolderId;
        }
        setMedia(p => [data.media, ...p]);
        toast.success(`${file.name} آپلود شد.`);
      } else toast.error(data.error || "خطا در آپلود");
    } catch { toast.error("خطا در آپلود فایل"); }
  };

  const handleFiles = async (files: FileList | null) => {
    if (!files || files.length === 0) return;
    setUploading(true);
    for (const file of Array.from(files)) await uploadFile(file);
    setUploading(false);
    if (fileRef.current) fileRef.current.value = "";
  };

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    handleFiles(e.dataTransfer.files);
  }, [currentFolderId]);

  const copyUrl = (url: string) => {
    navigator.clipboard.writeText(url);
    toast.success("لینک کپی شد!");
  };

  const handleDelete = async (id: string) => {
    const res = await deleteMedia(id);
    if (res.success) {
      setMedia(p => p.filter(m => m.id !== id));
      toast.success("رسانه حذف شد.");
    } else toast.error("خطا در حذف");
    setDeleteId(null);
    setPreview(null);
  };

  const handleDeleteFolder = async (id: string) => {
    const res = await deleteMediaFolder(id);
    if (res.success) {
      setFolders(p => p.filter(f => f.id !== id));
      toast.success("پوشه حذف شد.");
    } else toast.error("خطا در حذف پوشه");
    setDeleteFolderId(null);
  };

  const handleCreateFolder = async () => {
    if (!newFolderName.trim()) return;
    const res = await createMediaFolder(newFolderName, currentFolderId || undefined);
    if (res.success && res.folder) {
      setFolders([...folders, res.folder]);
      setNewFolderName("");
      setIsFolderModalOpen(false);
      toast.success("پوشه ایجاد شد.");
    } else {
      toast.error(res.error || "خطا در ایجاد پوشه");
    }
  };

  const stats = {
    total: media.length,
    images: media.filter(m => m.mimeType?.startsWith("image/")).length,
    videos: media.filter(m => m.mimeType?.startsWith("video/")).length,
  };

  return (
    <div className="flex flex-col h-full overflow-hidden bg-muted/20">
      <PageHeader
        title="کتابخانه رسانه"
        subtitle={`${stats.total} فایل · ${stats.images} تصویر · ${stats.videos} ویدئو`}
        icon={<ImageIcon className="w-5 h-5" />}
        actions={[
          { label: "پوشه جدید", icon: <FolderPlus className="w-4 h-4" />, onClick: () => setIsFolderModalOpen(true), variant: "outline" },
          { label: uploading ? "در حال آپلود..." : "آپلود فایل", icon: <UploadCloud className="w-4 h-4" />, onClick: () => fileRef.current?.click(), variant: "default", className: "bg-indigo-600 hover:bg-indigo-700 text-white" },
        ]}
      />
      <input ref={fileRef} type="file" multiple accept="image/*,video/*,.pdf,.zip" className="hidden" onChange={e => handleFiles(e.target.files)} />

      <div className="flex-1 overflow-auto p-4 md:p-6 space-y-6 max-w-7xl mx-auto w-full">
        {/* Breadcrumb */}
        <div className="flex items-center gap-2 text-sm text-muted-foreground bg-card border px-4 py-2 rounded-xl shadow-sm">
          <button onClick={() => setCurrentFolderId(null)} className={`hover:text-indigo-600 transition-colors ${!currentFolderId ? 'font-bold text-foreground' : ''}`}>خانه</button>
          {currentFolder && (
            <>
              <ChevronRight className="w-4 h-4" />
              <span className="font-bold text-foreground">{currentFolder.name}</span>
            </>
          )}
        </div>

        {/* Filters */}
        <div className="flex flex-col sm:flex-row gap-3">
          <div className="relative flex-1">
            <Search className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <Input placeholder="جستجو در فایل‌ها..." className="pr-9 rounded-xl" value={search} onChange={e => setSearch(e.target.value)} />
          </div>
          <div className="flex gap-2">
            {(["all", "image", "video", "other"] as const).map(t => (
              <button key={t} onClick={() => setFilterType(t)}
                className={`px-4 py-2 rounded-xl text-xs font-bold transition-colors border ${filterType === t ? "bg-indigo-600 text-white border-indigo-600 shadow-md" : "bg-card text-muted-foreground border-border hover:bg-muted"}`}>
                {t === "all" ? "همه" : t === "image" ? "تصاویر" : t === "video" ? "ویدئوها" : "سایر"}
              </button>
            ))}
          </div>
        </div>

        {/* Drop Zone */}
        <div
          onDragOver={e => { e.preventDefault(); setIsDragging(true); }}
          onDragLeave={() => setIsDragging(false)}
          onDrop={handleDrop}
          className={`border-2 border-dashed rounded-2xl p-8 text-center transition-all ${isDragging ? "border-indigo-500 bg-indigo-50 dark:bg-indigo-900/20" : "border-muted-foreground/20 bg-muted/10"}`}
        >
          <UploadCloud className={`w-10 h-10 mx-auto mb-3 transition-colors ${isDragging ? "text-indigo-500" : "text-muted-foreground/40"}`} />
          <p className="text-sm font-medium text-muted-foreground">{isDragging ? "رها کنید..." : "فایل‌ها را اینجا بکشید یا دکمه آپلود را بزنید"}</p>
        </div>

        {/* Folders Grid */}
        {childFolders.length > 0 && !search && filterType === "all" && (
          <div className="space-y-3">
            <h3 className="font-bold text-muted-foreground text-sm pr-1">پوشه‌ها</h3>
            <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
              {childFolders.map(f => (
                <div key={f.id} className="group bg-card border rounded-2xl p-4 shadow-sm hover:shadow-md hover:border-indigo-500/30 transition-all flex items-center gap-3 cursor-pointer relative" onClick={() => setCurrentFolderId(f.id)}>
                  <Folder className="w-8 h-8 text-indigo-400 fill-indigo-400/20" />
                  <div className="flex-1 min-w-0">
                    <p className="font-bold text-sm truncate">{f.name}</p>
                    <p className="text-[10px] text-muted-foreground">{f._count?.media || 0} فایل</p>
                  </div>
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button variant="ghost" size="icon" className="h-6 w-6 absolute top-2 left-2 opacity-0 group-hover:opacity-100 transition-opacity" onClick={e => e.stopPropagation()}>
                        <MoreVertical className="w-4 h-4 text-muted-foreground" />
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                      <DropdownMenuItem className="text-rose-500 focus:bg-rose-50 focus:text-rose-600 cursor-pointer" onClick={(e) => { e.stopPropagation(); setDeleteFolderId(f.id); }}>
                        <Trash2 className="w-4 h-4 ml-2" /> حذف پوشه
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Media Grid */}
        <div className="space-y-3">
          <h3 className="font-bold text-muted-foreground text-sm pr-1">فایل‌ها</h3>
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4">
            {filtered.length === 0 ? (
              <div className="col-span-full py-16 text-center bg-card border rounded-2xl border-dashed">
                <ImageIcon className="w-12 h-12 mx-auto mb-3 text-muted-foreground/30" />
                <p className="text-muted-foreground font-medium">رسانه‌ای در این پوشه یافت نشد.</p>
              </div>
            ) : filtered.map(m => (
              <div key={m.id} className="group bg-card border rounded-2xl overflow-hidden shadow-sm hover:shadow-md hover:border-indigo-500/30 transition-all flex flex-col">
                <div className="aspect-square bg-muted/30 relative overflow-hidden cursor-pointer" onClick={() => setPreview(m)}>
                  {m.mimeType?.startsWith("image/") ? (
                    <img src={m.url} alt={m.alt || m.filename} className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" />
                  ) : m.mimeType?.startsWith("video/") ? (
                    <div className="w-full h-full flex items-center justify-center bg-muted">
                      <FileVideo className="w-8 h-8 text-purple-500" />
                    </div>
                  ) : (
                    <div className="w-full h-full flex items-center justify-center bg-muted">
                      <File className="w-8 h-8 text-muted-foreground" />
                    </div>
                  )}
                  <div className="absolute inset-0 bg-black/0 group-hover:bg-black/40 transition-colors flex items-center justify-center">
                    <ZoomIn className="w-8 h-8 text-white scale-50 opacity-0 group-hover:scale-100 group-hover:opacity-100 transition-all duration-300" />
                  </div>
                </div>
                <div className="p-3">
                  <p className="text-xs font-medium text-foreground truncate">{m.filename}</p>
                  <p className="text-[10px] text-muted-foreground font-sans mt-0.5">{formatBytes(m.size || 0)}</p>
                  <div className="flex gap-1 mt-3">
                    <Button variant="outline" size="sm" className="h-7 px-2 text-indigo-500 hover:text-indigo-600 hover:bg-indigo-50 flex-1 border-indigo-100 text-[10px]" onClick={() => copyUrl(m.url)}>
                      <Copy className="w-3 h-3 ml-1" /> لینک
                    </Button>
                    <Button variant="outline" size="sm" className="h-7 w-7 p-0 text-rose-500 hover:text-rose-600 hover:bg-rose-50 border-rose-100 shrink-0" onClick={() => setDeleteId(m.id)}>
                      <Trash2 className="w-3 h-3" />
                    </Button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* New Folder Modal */}
      <ResponsiveModal open={isFolderModalOpen} onOpenChange={setIsFolderModalOpen} title="پوشه جدید">
        <div className="p-4 space-y-4">
          <div className="space-y-2">
            <Label>نام پوشه</Label>
            <Input value={newFolderName} onChange={e => setNewFolderName(e.target.value)} placeholder="مثال: محصولات ۱۴۰۳" autoFocus />
          </div>
          <div className="pt-2">
            <Button className="w-full" onClick={handleCreateFolder} disabled={!newFolderName.trim()}>ایجاد پوشه</Button>
          </div>
        </div>
      </ResponsiveModal>

      {/* Preview Dialog */}
      <Dialog open={!!preview} onOpenChange={open => !open && setPreview(null)}>
        <DialogContent className="max-w-4xl p-0 overflow-hidden bg-background rounded-2xl border-none">
          {preview && (
            <div className="flex flex-col md:flex-row h-[70vh] md:h-[600px]">
              <div className="flex-1 bg-black/95 flex items-center justify-center p-6 relative group">
                <Button variant="ghost" size="icon" className="absolute top-4 right-4 text-white hover:bg-white/20 z-10" onClick={() => setPreview(null)}><X className="w-5 h-5" /></Button>
                {preview.mimeType?.startsWith("image/") ? (
                  <img src={preview.url} alt={preview.alt || preview.filename} className="max-h-full max-w-full object-contain rounded drop-shadow-2xl" />
                ) : (
                  <div className="text-white text-center"><File className="w-20 h-20 mx-auto mb-4 opacity-50" /><p className="font-sans">{preview.filename}</p></div>
                )}
              </div>
              <div className="w-full md:w-80 p-6 space-y-6 bg-card flex flex-col">
                <div>
                  <h3 className="font-black text-lg mb-1">جزئیات فایل</h3>
                  <p className="text-xs text-muted-foreground">اطلاعات تکمیلی رسانه</p>
                </div>
                
                <div className="space-y-4 text-sm flex-1">
                  <div className="bg-muted/50 p-3 rounded-xl">
                    <p className="text-xs text-muted-foreground mb-1">نام فایل</p>
                    <p className="font-sans font-medium break-all">{preview.filename}</p>
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    <div className="bg-muted/50 p-3 rounded-xl">
                      <p className="text-xs text-muted-foreground mb-1">نوع فایل</p>
                      <p className="font-sans font-medium truncate">{preview.mimeType}</p>
                    </div>
                    <div className="bg-muted/50 p-3 rounded-xl">
                      <p className="text-xs text-muted-foreground mb-1">حجم</p>
                      <p className="font-sans font-medium">{formatBytes(preview.size || 0)}</p>
                    </div>
                  </div>
                </div>
                
                <div className="space-y-2 pt-4 border-t">
                  <Button className="w-full gap-2 bg-indigo-600 hover:bg-indigo-700" onClick={() => copyUrl(preview.url)}>
                    <Copy className="w-4 h-4" /> کپی لینک مستقیم
                  </Button>
                  <Button className="w-full gap-2" variant="outline" onClick={() => setDeleteId(preview.id)}>
                    <Trash2 className="w-4 h-4 text-rose-500" /> <span className="text-rose-500">حذف فایل</span>
                  </Button>
                </div>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* Delete Media Dialog */}
      <AlertDialog open={!!deleteId} onOpenChange={open => !open && setDeleteId(null)}>
        <AlertDialogContent className="rounded-2xl">
          <AlertDialogHeader>
            <AlertDialogTitle>حذف رسانه</AlertDialogTitle>
            <AlertDialogDescription>این فایل برای همیشه از کتابخانه حذف می‌شود. آیا مطمئن هستید؟</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel className="rounded-xl">انصراف</AlertDialogCancel>
            <AlertDialogAction className="bg-rose-500 hover:bg-rose-600 rounded-xl" onClick={() => deleteId && handleDelete(deleteId)}>حذف برای همیشه</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Delete Folder Dialog */}
      <AlertDialog open={!!deleteFolderId} onOpenChange={open => !open && setDeleteFolderId(null)}>
        <AlertDialogContent className="rounded-2xl">
          <AlertDialogHeader>
            <AlertDialogTitle>حذف پوشه</AlertDialogTitle>
            <AlertDialogDescription>فایل‌های داخل پوشه حذف نمی‌شوند بلکه به پوشه اصلی (خانه) منتقل می‌شوند. آیا مطمئن هستید؟</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel className="rounded-xl">انصراف</AlertDialogCancel>
            <AlertDialogAction className="bg-rose-500 hover:bg-rose-600 rounded-xl" onClick={() => deleteFolderId && handleDeleteFolder(deleteFolderId)}>بله، حذف پوشه</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}

