"use client";
import { useState, useEffect, useRef } from "react";
import { createClient } from "@/utils/supabase/client";
import { 
  User, Shield, FileText, Camera, Save, 
  UserPlus, Trash2, ShieldCheck, Loader2, Check 
} from "lucide-react";

type Tab = "profile" | "admins" | "legal";

export default function SettingsPage() {
  const supabase = createClient();
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  // States
  const [activeTab, setActiveTab] = useState<Tab>("profile");
  const [loading, setLoading] = useState(false);
  const [profile, setProfile] = useState<any>(null);
  const [admins, setAdmins] = useState<any[]>([]);
  const [legal, setLegal] = useState({ privacy: "", terms: "" });

  // Profile Form State
  const [formData, setFormData] = useState({ full_name: "", email: "" });

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

  async function fetchInitialData() {
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) return;

    // Fetch current profile
    const { data: profileData } = await supabase
      .from('profiles')
      .select('*')
      .eq('id', user.id)
      .single();
    
    if (profileData) {
      setProfile(profileData);
      setFormData({ full_name: profileData.full_name || "", email: profileData.email || "" });
    }

    // Fetch all admins
    const { data: adminData } = await supabase
      .from('profiles')
      .select('*')
      .eq('is_admin', true);
    setAdmins(adminData || []);
  }

  // Handle Profile Picture Upload
  const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file || !profile) return;

    setLoading(true);
    try {
      const fileExt = file.name.split('.').pop();
      const filePath = `avatars/${profile.id}-${Math.random()}.${fileExt}`;

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

      if (uploadError) throw uploadError;

      const { data: { publicUrl } } = supabase.storage
        .from('avatars')
        .getPublicUrl(filePath);

      const { error: updateError } = await supabase
        .from('profiles')
        .update({ avatar_url: publicUrl })
        .eq('id', profile.id);

      if (updateError) throw updateError;

      setProfile({ ...profile, avatar_url: publicUrl });
      alert("Profile picture updated!");
    } catch (error: any) {
      alert(error.message);
    } finally {
      setLoading(false);
    }
  };

  const handleUpdateProfile = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    const { error } = await supabase
      .from('profiles')
      .update({ full_name: formData.full_name })
      .eq('id', profile.id);
    
    if (!error) alert("Profile updated successfully");
    setLoading(false);
  };

  return (
    <div className="max-w-5xl mx-auto space-y-8 animate-in fade-in duration-500 pb-20">
      {/* HEADER */}
      <div className="flex flex-col gap-2">
        <h1 className="text-3xl font-black text-[#1C1C1C] tracking-tighter uppercase">Settings</h1>
        <p className="text-[11px] text-slate-500 font-black uppercase tracking-[0.2em]">System Configuration & Admin Management</p>
      </div>

      {/* TABS NAVIGATION */}
      <div className="flex bg-white p-1.5 rounded-2xl shadow-sm border border-slate-200 w-full overflow-x-auto no-scrollbar">
        {(["profile", "admins", "legal"] as Tab[]).map((tab) => (
          <button
            key={tab}
            onClick={() => setActiveTab(tab)}
            className={`flex-1 flex items-center justify-center gap-2 py-3 px-6 rounded-xl text-[11px] font-black uppercase tracking-widest transition-all ${
              activeTab === tab ? "bg-[#1C1C1C] text-[#D4FB51] shadow-lg" : "text-slate-400 hover:text-slate-600"
            }`}
          >
            {tab === "profile" && <User size={14} />}
            {tab === "admins" && <Shield size={14} />}
            {tab === "legal" && <FileText size={14} />}
            {tab}
          </button>
        ))}
      </div>

      {/* TAB CONTENT: PROFILE */}
      {activeTab === "profile" && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Avatar Section */}
          <div className="bg-white p-8 rounded-[32px] border border-slate-100 shadow-sm flex flex-col items-center text-center space-y-6">
            <div className="relative group">
              <div className="w-32 h-32 rounded-[40px] bg-slate-100 border-4 border-white shadow-xl overflow-hidden">
                {profile?.avatar_url ? (
                  <img src={profile.avatar_url} className="w-full h-full object-cover" alt="Avatar" />
                ) : (
                  <div className="w-full h-full flex items-center justify-center text-3xl font-black text-slate-300">
                    {profile?.full_name?.substring(0, 2).toUpperCase()}
                  </div>
                )}
              </div>
              <button 
                onClick={() => fileInputRef.current?.click()}
                className="absolute bottom-0 right-0 p-3 bg-[#D4FB51] text-black rounded-2xl shadow-lg hover:scale-110 transition-transform"
              >
                <Camera size={18} />
              </button>
              <input type="file" ref={fileInputRef} hidden accept="image/*" onChange={handleAvatarUpload} />
            </div>
            <div>
              <h3 className="font-black text-[#1C1C1C]">{profile?.full_name}</h3>
              <p className="text-[10px] text-slate-400 font-bold uppercase tracking-widest">{profile?.email}</p>
            </div>
          </div>

          {/* Details Form */}
          <div className="lg:col-span-2 bg-white p-8 rounded-[32px] border border-slate-100 shadow-sm">
            <form onSubmit={handleUpdateProfile} className="space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-2">
                  <label className="text-[10px] font-black uppercase text-slate-400 tracking-widest ml-1">Full Name</label>
                  <input 
                    type="text" 
                    className="w-full bg-slate-50 border border-slate-100 rounded-2xl p-4 text-sm font-bold outline-none focus:ring-4 focus:ring-[#D4FB51]/10 focus:border-[#D4FB51] transition-all"
                    value={formData.full_name}
                    onChange={(e) => setFormData({...formData, full_name: e.target.value})}
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-[10px] font-black uppercase text-slate-400 tracking-widest ml-1">Email Address</label>
                  <input 
                    type="email" 
                    disabled
                    className="w-full bg-slate-100 border border-slate-100 rounded-2xl p-4 text-sm font-bold text-slate-400 cursor-not-allowed"
                    value={formData.email}
                  />
                </div>
              </div>
              <button 
                disabled={loading}
                className="bg-[#1C1C1C] text-[#D4FB51] px-8 py-4 rounded-2xl font-black text-[11px] uppercase tracking-widest flex items-center gap-2 hover:scale-[1.02] active:scale-95 transition-all disabled:opacity-50"
              >
                {loading ? <Loader2 className="animate-spin" size={16} /> : <Save size={16} />}
                Save Changes
              </button>
            </form>
          </div>
        </div>
      )}

      {/* TAB CONTENT: ADMINS */}
      {activeTab === "admins" && (
        <div className="space-y-6">
          <div className="flex items-center justify-between px-4">
            <h3 className="text-sm font-black text-[#1C1C1C] uppercase tracking-tight flex items-center gap-2">
              <ShieldCheck size={18} className="text-[#D4FB51]" /> Active Administrators
            </h3>
            <button className="flex items-center gap-2 bg-[#D4FB51] text-black px-4 py-2 rounded-xl font-black text-[10px] uppercase tracking-widest hover:shadow-lg transition-all">
              <UserPlus size={14} /> Add Admin
            </button>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {admins.map((admin) => (
              <div key={admin.id} className="bg-white p-6 rounded-[32px] border border-slate-100 shadow-sm flex items-center justify-between group">
                <div className="flex items-center gap-4">
                  <div className="w-12 h-12 rounded-xl bg-slate-50 overflow-hidden flex items-center justify-center font-black text-slate-400">
                    {admin.avatar_url ? <img src={admin.avatar_url} className="w-full h-full object-cover" /> : admin.full_name?.substring(0, 1)}
                  </div>
                  <div>
                    <p className="text-sm font-black text-[#1C1C1C]">{admin.full_name}</p>
                    <p className="text-[10px] text-slate-400 font-bold">{admin.email}</p>
                  </div>
                </div>
                <button className="opacity-0 group-hover:opacity-100 p-2 text-slate-300 hover:text-rose-500 transition-all">
                  <Trash2 size={16} />
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* TAB CONTENT: LEGAL */}
      {activeTab === "legal" && (
        <div className="grid grid-cols-1 gap-8">
          <div className="bg-white p-8 rounded-[40px] border border-slate-100 shadow-sm space-y-8">
            <div className="space-y-4">
              <h3 className="text-sm font-black text-[#1C1C1C] uppercase flex items-center gap-2">
                <FileText size={18} className="text-[#D4FB51]" /> Privacy Policy
              </h3>
              <textarea 
                className="w-full bg-slate-50 border border-slate-100 rounded-[24px] p-6 h-64 text-sm font-medium outline-none focus:bg-white focus:ring-4 focus:ring-[#D4FB51]/10 transition-all"
                placeholder="Enter privacy policy markdown or text..."
              />
            </div>

            <div className="space-y-4">
              <h3 className="text-sm font-black text-[#1C1C1C] uppercase flex items-center gap-2">
                <FileText size={18} className="text-[#D4FB51]" /> Terms of Use
              </h3>
              <textarea 
                className="w-full bg-slate-50 border border-slate-100 rounded-[24px] p-6 h-64 text-sm font-medium outline-none focus:bg-white focus:ring-4 focus:ring-[#D4FB51]/10 transition-all"
                placeholder="Enter terms and conditions..."
              />
            </div>

            <button className="w-full bg-[#1C1C1C] text-[#D4FB51] py-5 rounded-2xl font-black uppercase tracking-widest text-xs flex items-center justify-center gap-3 hover:scale-[1.01] active:scale-95 transition-all">
              <Save size={18} /> Update Legal Documents
            </button>
          </div>
        </div>
      )}
    </div>
  );
}