"use client";
import { useEffect, useState, useCallback } from "react";
import { createClient } from "@/utils/supabase/client";
import { useParams, useRouter } from "next/navigation";
import Link from "next/link";
import { 
  Baby, 
  Users as FamilyIcon, 
  ChevronLeft, 
  Calendar, 
  Mail,
  Send,
  MapPin,
  Trash2,
  Edit,
  History,
  X,
  UserCircle2,
  Navigation
} from "lucide-react";

export default function UserDetails() {
  const { id } = useParams();
  const router = useRouter();
  const supabase = createClient();
  
  const [user, setUser] = useState<any>(null);
  const [babies, setBabies] = useState<any[]>([]);
  const [families, setFamilies] = useState<any[]>([]);
  const [familyMembers, setFamilyMembers] = useState<any[]>([]);
  const [notifications, setNotifications] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  // Edit Modal State
  const [editingNotif, setEditingNotif] = useState<any>(null);
  const [editTitle, setEditTitle] = useState("");
  const [editMessage, setEditMessage] = useState("");

  const fetchData = useCallback(async () => {
    setLoading(true);
    
    // 1. Fetch Profile (including Address and Location JSON)
    const { data: profile } = await supabase.from('profiles').select('*').eq('id', id).single();
    setUser(profile);

    // 2. Fetch Families where user is a member OR owner
    // First get the family IDs from family_members table
    const { data: memberEntries } = await supabase.from('family_members').select('family_id').eq('user_id', id);
    const familyIds = memberEntries?.map(m => m.family_id) || [];

    if (familyIds.length > 0) {
      // 3. Fetch Family Details
      const { data: familyData } = await supabase.from('families').select('*').in('id', familyIds);
      setFamilies(familyData || []);

      // 4. Fetch All Members of these families (Family Circle)
      const { data: allMembers } = await supabase
        .from('family_members')
        .select('role, joined_at, profiles:user_id(id, full_name, email)')
        .in('family_id', familyIds);
      
      // Filter out the current user to show only "Other Members"
      const others = allMembers?.filter(m => (m.profiles as any).id !== id) || [];
      setFamilyMembers(others);

      // 5. Fetch Babies connected to these families
      const { data: babyData } = await supabase.from('babies').select('*').in('family_id', familyIds);
      setBabies(babyData || []);
    }

    // 6. Notifications History
    const { data: notifs } = await supabase
      .from('notifications')
      .select('*')
      .eq('user_id', id)
      .order('created_at', { ascending: false });
    setNotifications(notifs || []);

    setLoading(false);
  }, [id, supabase]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  const handleDeleteNotif = async (notifId: string) => {
    if (!confirm("Are you sure?")) return;
    await supabase.from('notifications').delete().eq('id', notifId);
    fetchData();
  };

  const handleUpdateNotif = async (e: React.FormEvent) => {
    e.preventDefault();
    await supabase.from('notifications').update({ title: editTitle, message: editMessage }).eq('id', editingNotif.id);
    setEditingNotif(null);
    fetchData();
  };

  if (loading && !user) return (
    <div className="flex items-center justify-center h-[60vh]">
      <div className="w-8 h-8 border-4 border-[#D4FB51] border-t-transparent rounded-full animate-spin"></div>
    </div>
  );

  return (
    <div className="space-y-8 animate-in fade-in duration-700 pb-20">
      
      {/* --- HEADER --- */}
      <button onClick={() => router.back()} className="flex items-center gap-2 text-[10px] font-black uppercase tracking-[0.2em] text-slate-400 hover:text-[#1C1C1C] transition-colors">
        <ChevronLeft size={14} /> Back to Users
      </button>

      <div className="bg-white p-10 rounded-[40px] shadow-sm border border-slate-50 flex flex-col lg:flex-row justify-between items-start lg:items-center gap-8">
        <div className="flex items-center gap-8">
          <div className="w-24 h-24 rounded-[30px] bg-[#1C1C1C] flex items-center justify-center shadow-2xl relative">
            <span className="text-[#D4FB51] text-4xl font-black">{user?.full_name?.substring(0, 1)}</span>
            <div className="absolute -bottom-1 -right-1 bg-emerald-500 w-5 h-5 rounded-full border-4 border-white"></div>
          </div>
          <div>
            <h1 className="text-4xl font-black text-[#1C1C1C] tracking-tighter">{user?.full_name}</h1>
            <div className="flex flex-wrap items-center gap-4 mt-2">
              <p className="flex items-center gap-1.5 text-xs font-bold text-slate-500"><Mail size={14} className="text-[#D4FB51]" /> {user?.email}</p>
              <span className="w-1 h-1 bg-slate-300 rounded-full"></span>
              <p className="flex items-center gap-1.5 text-xs font-bold text-slate-500"><Calendar size={14} className="text-[#D4FB51]" /> Joined {new Date(user?.created_at).toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })}</p>
            </div>
          </div>
        </div>
        <Link href={`/dashboard/users/${id}/notify`} className="bg-[#1C1C1C] text-[#D4FB51] px-10 py-5 rounded-[22px] font-black uppercase tracking-widest text-[11px] flex items-center gap-3 hover:scale-105 active:scale-95 transition-all shadow-xl">
          <Send size={18} /> Send Notification
        </Link>
      </div>

      <div className="grid grid-cols-12 gap-8">
        {/* --- LEFT COLUMN: SYSTEM & RELATIONS --- */}
        <div className="col-span-12 lg:col-span-4 space-y-8">
            
            {/* Location & Address */}
            <div className="bg-white p-8 rounded-[32px] shadow-sm border border-slate-50">
              <h3 className="text-[11px] font-black text-slate-400 uppercase tracking-[0.2em] mb-6 flex items-center gap-2">
                <MapPin size={14} className="text-[#D4FB51]" /> User Location
              </h3>
              <div className="space-y-4">
                <div className="bg-slate-50 p-5 rounded-2xl border border-slate-100">
                   <p className="text-[10px] font-black text-slate-400 uppercase mb-1">Primary Address</p>
                   <p className="text-sm font-black text-[#1C1C1C]">{user?.address || "No address provided"}</p>
                </div>
                {user?.last_location && (
                  <div className="bg-slate-50 p-5 rounded-2xl border border-slate-100 flex items-center justify-between">
                    <div>
                      <p className="text-[10px] font-black text-slate-400 uppercase mb-1">Last Known Coordinates</p>
                      <p className="text-xs font-bold text-[#1C1C1C]">
                        Lat: {user.last_location.lat?.toFixed(4)}, Long: {user.last_location.long?.toFixed(4)}
                      </p>
                    </div>
                    <Navigation size={18} className="text-slate-300" />
                  </div>
                )}
              </div>
            </div>

            {/* Family Members (Circle) */}
            <div className="bg-white p-8 rounded-[32px] shadow-sm border border-slate-50">
              <h3 className="text-[11px] font-black text-slate-400 uppercase tracking-[0.2em] mb-6 flex items-center gap-2">
                <UserCircle2 size={14} className="text-[#D4FB51]" /> Family Circle
              </h3>
              <div className="space-y-3">
                {familyMembers.length > 0 ? familyMembers.map((member, idx) => (
                  <div key={idx} className="flex items-center gap-4 p-4 bg-slate-50 rounded-2xl border border-slate-100">
                    <div className="w-10 h-10 rounded-xl bg-white flex items-center justify-center font-black text-xs text-[#1C1C1C] shadow-sm">
                      {(member.profiles as any).full_name?.substring(0,1)}
                    </div>
                    <div>
                      <p className="text-sm font-black text-[#1C1C1C]">{(member.profiles as any).full_name}</p>
                      <p className="text-[9px] font-black text-slate-400 uppercase tracking-widest">{member.role}</p>
                    </div>
                  </div>
                )) : (
                  <p className="text-xs font-bold text-slate-400 italic text-center py-4">No other members in family circle.</p>
                )}
              </div>
            </div>

            {/* Babies */}
            <div className="bg-white p-8 rounded-[32px] shadow-sm border border-slate-50">
              <h3 className="text-[11px] font-black text-slate-400 uppercase tracking-[0.2em] mb-6 flex items-center gap-2">
                <Baby size={14} className="text-[#D4FB51]" /> Registered Babies
              </h3>
              <div className="grid grid-cols-2 gap-3">
                {babies.map(b => (
                  <div key={b.id} className="p-4 bg-slate-50 rounded-2xl border border-slate-100 font-black text-xs text-[#1C1C1C] text-center">
                    {b.name}
                  </div>
                ))}
              </div>
            </div>
        </div>

        {/* --- RIGHT COLUMN: NOTIFICATION HISTORY --- */}
        <div className="col-span-12 lg:col-span-8">
          <div className="bg-white p-10 rounded-[40px] shadow-sm border border-slate-50">
            <div className="flex items-center justify-between mb-10">
              <h3 className="text-2xl font-black text-[#1C1C1C] uppercase tracking-tight flex items-center gap-4">
                <History className="text-[#D4FB51]" size={28} /> Activity Log
              </h3>
              <span className="bg-[#1C1C1C] text-[#D4FB51] text-[10px] font-black px-4 py-1.5 rounded-full uppercase tracking-widest">
                {notifications.length} Events
              </span>
            </div>

            <div className="space-y-4">
              {notifications.map((notif) => (
                <div key={notif.id} className="group p-6 bg-slate-50 rounded-[24px] border border-slate-100 hover:border-[#D4FB51] transition-all flex justify-between items-center">
                  <div className="space-y-1">
                    <div className="flex items-center gap-3">
                      <span className="text-sm font-black text-[#1C1C1C]">{notif.title}</span>
                      <span className={`text-[9px] font-black uppercase tracking-widest px-2 py-0.5 rounded ${notif.is_read ? 'bg-emerald-50 text-emerald-500' : 'bg-amber-50 text-amber-500'}`}>
                        {notif.is_read ? 'Received' : 'Sent'}
                      </span>
                    </div>
                    <p className="text-xs font-bold text-slate-500">{notif.message}</p>
                    <p className="text-[9px] font-black text-slate-400 uppercase mt-2">{new Date(notif.created_at).toLocaleString()}</p>
                  </div>
                  
                  <div className="flex gap-2 opacity-0 group-hover:opacity-100 transition-all transform translate-x-2 group-hover:translate-x-0">
                    <button onClick={() => { setEditingNotif(notif); setEditTitle(notif.title); setEditMessage(notif.message); }} className="p-3 bg-white text-slate-600 rounded-xl hover:text-black shadow-sm border border-slate-100"><Edit size={16} /></button>
                    <button onClick={() => handleDeleteNotif(notif.id)} className="p-3 bg-white text-slate-600 rounded-xl hover:text-rose-600 shadow-sm border border-slate-100"><Trash2 size={16} /></button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* --- EDIT MODAL (Dark Tabela Style) --- */}
      {editingNotif && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-[#1C1C1C]/80 backdrop-blur-md p-6">
          <div className="bg-[#1C1C1C] w-full max-w-xl rounded-[40px] shadow-2xl border border-white/10 animate-in zoom-in-95">
            <div className="p-8 border-b border-white/5 flex items-center justify-between">
              <h2 className="text-xl font-black text-white uppercase tracking-tight flex items-center gap-3"><Edit className="text-[#D4FB51]" size={20} /> Modify Log</h2>
              <button onClick={() => setEditingNotif(null)} className="p-2 text-gray-500 hover:text-white"><X size={24} /></button>
            </div>
            <form onSubmit={handleUpdateNotif} className="p-8 space-y-6">
              <input value={editTitle} onChange={(e) => setEditTitle(e.target.value)} className="w-full bg-[#2D2D2D] border border-white/5 rounded-2xl p-5 text-white font-bold outline-none focus:border-[#D4FB51]" />
              <textarea value={editMessage} onChange={(e) => setEditMessage(e.target.value)} className="w-full bg-[#2D2D2D] border border-white/5 rounded-2xl p-5 h-40 text-white font-bold outline-none focus:border-[#D4FB51] resize-none" />
              <button type="submit" className="w-full bg-[#D4FB51] text-black py-5 rounded-2xl font-black uppercase tracking-widest text-xs">Update Notification</button>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}