"use client";
import { useState, useRef } from "react";
import { createClient } from "@/utils/supabase/client";
import { useRouter } from "next/navigation";
import { ChevronLeft, Send, Image as ImageIcon, Video, X, Loader2, UploadCloud } from "lucide-react";

export default function NewPostPage() {
  const router = useRouter();
  const supabase = createClient();
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  const [content, setContent] = useState("");
  const [file, setFile] = useState<File | null>(null);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  const [mediaType, setMediaType] = useState<"image" | "video" | "none">("none");
  const [sending, setSending] = useState(false);

  // Handle File Selection
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = e.target.files?.[0];
    if (selectedFile) {
      setFile(selectedFile);
      setPreviewUrl(URL.createObjectURL(selectedFile));
      
      // Auto-set media type based on file mime type
      if (selectedFile.type.startsWith("image/")) setMediaType("image");
      else if (selectedFile.type.startsWith("video/")) setMediaType("video");
    }
  };

  const clearMedia = () => {
    setFile(null);
    setPreviewUrl(null);
    setMediaType("none");
    if (fileInputRef.current) fileInputRef.current.value = "";
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!content && !file) return alert("Please add content or a file");

    setSending(true);

    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) throw new Error("No authenticated user found");

      let uploadedUrl = null;

      // 1. Upload File to Supabase Storage if it exists
      if (file) {
        const fileExt = file.name.split('.').pop();
        const fileName = `${Math.random()}-${Date.now()}.${fileExt}`;
        const filePath = `${user.id}/${fileName}`;

        const { error: uploadError } = await supabase.storage
          .from('community') // MAKE SURE THIS BUCKET EXISTS AND IS PUBLIC
          .upload(filePath, file);

        if (uploadError) throw uploadError;

        // Get Public URL
        const { data: urlData } = supabase.storage
          .from('community')
          .getPublicUrl(filePath);
        
        uploadedUrl = urlData.publicUrl;
      }

      // 2. Insert into community_posts table
      const { error: insertError } = await supabase.from('community_posts').insert({
        user_id: user.id,
        content: content,
        media_url: uploadedUrl,
        media_type: mediaType,
      });

      if (insertError) throw insertError;
      
      router.push("/dashboard/posts");
      router.refresh();
    } catch (error: any) {
      console.error(error);
      alert(error.message || "Something went wrong");
    } finally {
      setSending(false);
    }
  };

  return (
    <div className="max-w-2xl mx-auto space-y-8 animate-in slide-in-from-bottom-4 duration-500 pb-10">
      <button 
        onClick={() => router.back()} 
        className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest text-slate-400 hover:text-black transition-colors"
      >
        <ChevronLeft size={14} /> Back to Community
      </button>

      <div className="bg-[#1C1C1C] rounded-[40px] shadow-2xl overflow-hidden border border-white/5">
        <div className="p-10 border-b border-white/5 flex items-center gap-4 bg-gradient-to-r from-[#D4FB51]/10 to-transparent">
          <div className="w-12 h-12 rounded-2xl bg-[#D4FB51] flex items-center justify-center shadow-lg shadow-[#D4FB51]/20">
            <Send size={24} className="text-black" />
          </div>
          <div>
            <h1 className="text-2xl font-black text-white uppercase tracking-tight">Create Broadcast</h1>
            <p className="text-[10px] text-gray-500 font-bold uppercase tracking-widest mt-1">Uploading to Cloud Storage</p>
          </div>
        </div>

        <form onSubmit={handleSubmit} className="p-10 space-y-6">
          <div className="space-y-2">
            <label className="text-[10px] text-gray-400 font-black uppercase tracking-widest ml-4">Post Content</label>
            <textarea 
              className="w-full bg-[#2D2D2D] border border-white/5 rounded-[24px] p-6 h-40 text-white font-medium outline-none focus:border-[#D4FB51] transition-all placeholder:text-gray-600 resize-none shadow-inner"
              placeholder="Share updates, advice, or news..."
              value={content}
              onChange={(e) => setContent(e.target.value)}
            ></textarea>
          </div>

          <div className="space-y-4">
            <label className="text-[10px] text-gray-400 font-black uppercase tracking-widest ml-4">Media Attachment</label>
            
            {/* Hidden File Input */}
            <input 
              type="file" 
              ref={fileInputRef}
              className="hidden" 
              accept="image/*,video/*"
              onChange={handleFileChange}
            />

            {!previewUrl ? (
              <div className="flex gap-4">
                <button
                  type="button"
                  onClick={() => fileInputRef.current?.click()}
                  className="flex-1 group flex flex-col items-center justify-center gap-3 p-8 rounded-[32px] border-2 border-dashed border-white/10 bg-[#2D2D2D]/50 hover:border-[#D4FB51]/50 hover:bg-[#2D2D2D] transition-all"
                >
                  <UploadCloud size={32} className="text-gray-500 group-hover:text-[#D4FB51] transition-colors" />
                  <span className="text-[10px] font-black text-gray-400 uppercase tracking-widest">Select Image or Video</span>
                </button>
              </div>
            ) : (
              <div className="relative rounded-[32px] overflow-hidden border border-white/10 bg-black aspect-video flex items-center justify-center">
                {mediaType === "image" ? (
                  <img src={previewUrl} className="w-full h-full object-contain" alt="Preview" />
                ) : (
                  <video src={previewUrl} className="w-full h-full object-contain" controls />
                )}
                <button 
                  type="button"
                  onClick={clearMedia}
                  className="absolute top-4 right-4 p-2 bg-black/50 text-white rounded-full hover:bg-rose-500 transition-colors"
                >
                  <X size={20} />
                </button>
              </div>
            )}
          </div>

          <button 
            disabled={sending}
            className="w-full bg-[#D4FB51] text-black py-5 rounded-2xl font-black uppercase tracking-widest text-xs flex items-center justify-center gap-3 hover:scale-[1.02] active:scale-95 transition-all disabled:opacity-50 disabled:grayscale mt-4"
          >
            {sending ? (
              <>
                <Loader2 className="animate-spin" size={18} />
                <span>Uploading Media...</span>
              </>
            ) : (
              "Post to Community"
            )}
          </button>
        </form>
      </div>
    </div>
  );
}