"use client";
import { useEffect, useState } from "react";
import { createClient } from "@/utils/supabase/client";
import { useParams, useRouter } from "next/navigation";
import { Bell, Send, ChevronLeft, CheckCircle2, User } from "lucide-react";

export default function SendNotification() {
  const { id } = useParams();
  const router = useRouter();
  const supabase = createClient();
  
  const [user, setUser] = useState<any>(null);
  const [notifMessage, setNotifMessage] = useState("");
  const [notifTitle, setNotifTitle] = useState("");
  const [sending, setSending] = useState(false);

  useEffect(() => {
    async function getUser() {
      const { data } = await supabase.from('profiles').select('full_name, email').eq('id', id).single();
      setUser(data);
    }
    getUser();
  }, [id, supabase]);

  const handleSend = async (e: React.FormEvent) => {
    e.preventDefault();
    setSending(true);

    const { error } = await supabase.from('notifications').insert({
      user_id: id,
      title: notifTitle,
      message: notifMessage,
      type: 'admin',
      is_read: false,
      data: { sent_at: new Date().toISOString(), platform: 'Admin Panel' }
    });

    if (error) {
      alert("Failed to send: " + error.message);
    } else {
      alert("Notification successfully delivered!");
      router.push(`/dashboard/users/${id}`); // Go back to profile
    }
    setSending(false);
  };

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

      {/* --- NOTIFICATION FORM --- */}
      <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 justify-between bg-gradient-to-r from-black/20 to-transparent">
          <div className="flex items-center gap-4">
            <div className="w-12 h-12 rounded-2xl bg-[#D4FB51] flex items-center justify-center shadow-lg shadow-[#D4FB51]/20">
              <Bell size={24} className="text-black" />
            </div>
            <div>
              <h1 className="text-2xl font-black text-white uppercase tracking-tight">Direct Message</h1>
              <p className="text-[10px] text-gray-500 font-bold uppercase tracking-widest mt-1">
                To: <span className="text-[#D4FB51]">{user?.full_name || "Loading..."}</span>
              </p>
            </div>
          </div>
          <div className="hidden sm:block text-right">
            <p className="text-[10px] text-gray-500 font-black uppercase tracking-widest">Target Email</p>
            <p className="text-xs text-gray-400 font-bold">{user?.email || "..."}</p>
          </div>
        </div>

        <form onSubmit={handleSend} className="p-10 space-y-6">
          <div className="space-y-2">
            <label className="text-[10px] font-black text-gray-500 uppercase tracking-[0.2em] ml-2">Message Subject</label>
            <input 
              className="w-full bg-[#2D2D2D] border border-white/5 rounded-[20px] p-5 text-white font-bold outline-none focus:border-[#D4FB51] focus:ring-4 focus:ring-[#D4FB51]/5 transition-all placeholder:text-gray-600"
              placeholder="e.g. Action Required: Update your plan"
              value={notifTitle}
              onChange={(e) => setNotifTitle(e.target.value)}
              required
            />
          </div>

          <div className="space-y-2">
            <label className="text-[10px] font-black text-gray-500 uppercase tracking-[0.2em] ml-2">Message Body (Plain Text)</label>
            <textarea 
              className="w-full bg-[#2D2D2D] border border-white/5 rounded-[24px] p-5 h-56 text-white font-bold outline-none focus:border-[#D4FB51] focus:ring-4 focus:ring-[#D4FB51]/5 transition-all placeholder:text-gray-600 resize-none"
              placeholder="Describe what the user needs to see in their app..."
              value={notifMessage}
              onChange={(e) => setNotifMessage(e.target.value)}
              required
            ></textarea>
          </div>

          <div className="flex flex-col sm:flex-row items-center gap-6 pt-4">
            <button 
              type="submit"
              disabled={sending}
              className="w-full sm:w-auto bg-[#D4FB51] text-black px-12 py-5 rounded-2xl font-black uppercase tracking-widest text-xs flex items-center justify-center gap-3 hover:scale-105 active:scale-95 transition-all disabled:opacity-50 disabled:scale-100"
            >
              {sending ? "Processing..." : <><Send size={18} /> Broadcast Message</>}
            </button>
            <div className="flex items-center gap-2 text-[10px] text-gray-500 font-bold uppercase">
              <CheckCircle2 size={14} className="text-emerald-500" />
              Secure Real-time Delivery
            </div>
          </div>
        </form>
      </div>
      
      {/* Help Note */}
      <div className="p-8 bg-white/50 backdrop-blur-sm rounded-[32px] border border-slate-100">
        <p className="text-xs text-slate-500 font-bold leading-relaxed">
          <span className="text-[#1C1C1C]">Note:</span> This message will appear in the user's mobile app notification center. 
          The delivery is instantaneous via Supabase Postgres Changes stream.
        </p>
      </div>
    </div>
  );
}