"use client";

import { useState, useRef } from "react";
import { supabase } from "@/lib/supabase";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Upload, Film, Image as ImageIcon, User, Loader2 } from "lucide-react";
import { toast } from "sonner";

const BUCKETS = [
  { id: "videos", label: "Videos", icon: Film, types: "video/*" },
  { id: "thumbnails", label: "Thumbnails", icon: ImageIcon, types: "image/*" },
  { id: "avatars", label: "Avatars", icon: User, types: "image/*" },
];

export default function MediaPage() {
  const [uploading, setUploading] = useState(false);
  const [activeTab, setActiveTab] = useState("videos");
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploading(true);
    try {
      const fileExt = file.name.split(".").pop();
      const fileName = `${Date.now()}.${fileExt}`;
      const filePath = `${activeTab}/${fileName}`;

      const { error: uploadError } = await supabase.storage
        .from(activeTab)
        .upload(filePath, file);

      if (uploadError) throw uploadError;

      toast.success("File uploaded successfully!");
    } catch (error) {
      console.error("Upload failed:", error);
      toast.error("Upload failed: " + (error instanceof Error ? error.message : "Unknown error"));
    } finally {
      setUploading(false);
      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
    }
  };

  const activeBucket = BUCKETS.find((b) => b.id === activeTab);

  return (
    <div className="p-8">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-white mb-2">Media Library</h1>
        <p className="text-neutral-400">Upload and manage media files</p>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="bg-neutral-900 border-neutral-800 mb-6">
          {BUCKETS.map((bucket) => (
            <TabsTrigger
              key={bucket.id}
              value={bucket.id}
              className="data-[state=active]:bg-orange-500 data-[state=active]:text-white"
            >
              <bucket.icon className="w-4 h-4 mr-2" />
              {bucket.label}
            </TabsTrigger>
          ))}
        </TabsList>

        {BUCKETS.map((bucket) => (
          <TabsContent key={bucket.id} value={bucket.id}>
            <Card className="bg-neutral-900 border-neutral-800">
              <CardHeader>
                <CardTitle className="text-white flex items-center gap-2">
                  <bucket.icon className="w-5 h-5 text-orange-500" />
                  Upload {bucket.label}
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="border-2 border-dashed border-neutral-700 rounded-lg p-12 text-center hover:border-orange-500/50 transition-colors">
                  <input
                    type="file"
                    ref={fileInputRef}
                    onChange={handleUpload}
                    accept={bucket.types}
                    className="hidden"
                    id={`file-upload-${bucket.id}`}
                  />
                  <label
                    htmlFor={`file-upload-${bucket.id}`}
                    className="cursor-pointer flex flex-col items-center"
                  >
                    <div className="w-16 h-16 bg-neutral-800 rounded-full flex items-center justify-center mb-4">
                      {uploading ? (
                        <Loader2 className="w-8 h-8 text-orange-500 animate-spin" />
                      ) : (
                        <Upload className="w-8 h-8 text-neutral-400" />
                      )}
                    </div>
                    
                    <p className="text-white font-medium mb-2">
                      {uploading ? "Uploading..." : `Click to upload ${bucket.label.toLowerCase()}`}
                    </p>
                    <p className="text-neutral-500 text-sm">
                      {bucket.id === "videos"
                        ? "MP4, MOV up to 100MB"
                        : "JPG, PNG up to 5MB"}
                    </p>
                  </label>
                </div>

                <div className="mt-6 p-4 bg-neutral-950 rounded-lg">
                  <h4 className="text-sm font-medium text-white mb-2">Storage Path</h4>
                  <code className="text-sm text-neutral-400">
                    {bucket.id}/filename.ext
                  </code>
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        ))}
      </Tabs>
    </div>
  );
}
