import React, { useState, useRef, useCallback, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import { Upload, Copy, Trash2, Loader2, ImageIcon, Search, ExternalLink } from "lucide-react";
import { Dialog, DialogContent } from "@/components/ui/dialog";
import { v4 as uuidv4 } from "uuid";

const BUCKET = "company-assets";

interface MediaFile {
  name: string;
  url: string;
  created_at: string;
  size: number;
  type: string;
}

export default function MediaLibraryPage() {
  const { toast } = useToast();
  const inputRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);
  const [files, setFiles] = useState<MediaFile[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [preview, setPreview] = useState<string | null>(null);

  const fetchFiles = useCallback(async () => {
    setLoading(true);
    const { data, error } = await supabase.storage.from(BUCKET).list("media", {
      limit: 500,
      sortBy: { column: "created_at", order: "desc" },
    });
    if (error) {
      toast({ title: "Failed to load media", description: error.message, variant: "destructive" });
      setLoading(false);
      return;
    }
    const mapped = (data || [])
      .filter((f) => f.name && !f.name.startsWith("."))
      .map((f) => {
        const { data: urlData } = supabase.storage.from(BUCKET).getPublicUrl(`media/${f.name}`);
        return {
          name: f.name,
          url: urlData.publicUrl,
          created_at: f.created_at || "",
          size: (f.metadata as any)?.size || 0,
          type: (f.metadata as any)?.mimetype || "",
        };
      });
    setFiles(mapped);
    setLoading(false);
  }, [toast]);

  // Load on mount
  useEffect(() => {
    fetchFiles();
  }, [fetchFiles]);

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const selected = e.target.files;
    if (!selected || selected.length === 0) return;

    setUploading(true);
    let successCount = 0;

    for (const file of Array.from(selected)) {
      if (file.size > 10 * 1024 * 1024) {
        toast({ title: `${file.name} exceeds 10MB limit`, variant: "destructive" });
        continue;
      }
      const ext = file.name.split(".").pop() || "jpg";
      const fileName = `media/${uuidv4()}.${ext}`;

      const { error } = await supabase.storage.from(BUCKET).upload(fileName, file, {
        contentType: file.type,
        upsert: false,
      });
      if (error) {
        toast({ title: `Failed to upload ${file.name}`, description: error.message, variant: "destructive" });
      } else {
        successCount++;
      }
    }

    if (successCount > 0) {
      toast({ title: `${successCount} file(s) uploaded` });
      fetchFiles();
    }
    setUploading(false);
    if (inputRef.current) inputRef.current.value = "";
  };

  const handleDelete = async (name: string) => {
    const { error } = await supabase.storage.from(BUCKET).remove([`media/${name}`]);
    if (error) {
      toast({ title: "Delete failed", description: error.message, variant: "destructive" });
    } else {
      setFiles((prev) => prev.filter((f) => f.name !== name));
      toast({ title: "File deleted" });
    }
  };

  const copyUrl = (url: string) => {
    navigator.clipboard.writeText(url);
    toast({ title: "URL copied to clipboard" });
  };

  const filtered = files.filter((f) => f.name.toLowerCase().includes(search.toLowerCase()));

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Media Library</h1>
          <p className="text-sm text-muted-foreground">Upload images and copy shareable URLs.</p>
        </div>
        <div>
          <input
            ref={inputRef}
            type="file"
            accept="image/*"
            multiple
            className="hidden"
            onChange={handleUpload}
          />
          <Button onClick={() => inputRef.current?.click()} disabled={uploading} className="gap-2">
            {uploading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Upload className="h-4 w-4" />}
            {uploading ? "Uploading..." : "Upload Images"}
          </Button>
        </div>
      </div>

      <div className="relative max-w-sm">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
        <Input
          placeholder="Search files..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="pl-9"
        />
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-20 text-muted-foreground">
          <Loader2 className="h-6 w-6 animate-spin mr-2" /> Loading media...
        </div>
      ) : filtered.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-20 text-muted-foreground">
          <ImageIcon className="h-12 w-12 mb-3 opacity-40" />
          <p className="text-sm">{files.length === 0 ? "No media uploaded yet." : "No results."}</p>
        </div>
      ) : (
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
          {filtered.map((file) => (
            <Card key={file.name} className="group overflow-hidden">
              <div
                className="aspect-square bg-muted flex items-center justify-center cursor-pointer overflow-hidden"
                onClick={() => setPreview(file.url)}
              >
                <img
                  src={file.url}
                  alt={file.name}
                  className="w-full h-full object-cover transition-transform duration-200 group-hover:scale-105"
                  loading="lazy"
                />
              </div>
              <CardContent className="p-2 space-y-1">
                <p className="text-xs font-medium truncate text-foreground" title={file.name}>
                  {file.name}
                </p>
                <div className="flex gap-1">
                  <Button
                    variant="outline"
                    size="icon"
                    className="h-7 w-7"
                    title="Copy URL"
                    onClick={() => copyUrl(file.url)}
                  >
                    <Copy className="h-3 w-3" />
                  </Button>
                  <Button
                    variant="outline"
                    size="icon"
                    className="h-7 w-7"
                    title="Open in new tab"
                    onClick={() => window.open(file.url, "_blank")}
                  >
                    <ExternalLink className="h-3 w-3" />
                  </Button>
                  <Button
                    variant="outline"
                    size="icon"
                    className="h-7 w-7 text-destructive hover:text-destructive"
                    title="Delete"
                    onClick={() => handleDelete(file.name)}
                  >
                    <Trash2 className="h-3 w-3" />
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      <Dialog open={!!preview} onOpenChange={() => setPreview(null)}>
        <DialogContent className="max-w-4xl p-1 bg-transparent border-none shadow-none">
          {preview && (
            <img src={preview} alt="Preview" className="max-h-[85vh] w-auto mx-auto rounded-lg shadow-2xl" />
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
