import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Loader2 } from "lucide-react";
import StatusUpdateCard from "@/components/status-updates/StatusUpdateCard";

export default function ClientStatusUpdatesPage() {
  const [updates, setUpdates] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [currentUserId, setCurrentUserId] = useState<string | null>(null);

  useEffect(() => {
    supabase.auth.getUser().then(({ data }) => {
      setCurrentUserId(data?.user?.id || null);
    });
  }, []);

  const fetchData = async () => {
    setLoading(true);
    const { data } = await supabase
      .from("status_updates")
      .select("*, associations(name), status_update_votes(*), profiles:created_by(full_name)")
      .order("created_at", { ascending: false });
    setUpdates(data || []);
    setLoading(false);
  };

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

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-foreground">Status Updates</h1>
        <p className="text-muted-foreground mt-1">Latest updates regarding your account.</p>
      </div>

      {loading ? (
        <div className="flex justify-center py-12">
          <Loader2 className="h-8 w-8 animate-spin text-primary" />
        </div>
      ) : updates.length === 0 ? (
        <div className="text-center py-12 text-muted-foreground bg-muted/50 rounded-xl border border-dashed">
          <p>No status updates available.</p>
        </div>
      ) : (
        <div className="space-y-4">
          {updates.map((u, i) => (
            <StatusUpdateCard
              key={u.id}
              update={u}
              canManage={false}
              onEdit={() => {}}
              onDelete={fetchData}
              onRefresh={fetchData}
              index={i}
              currentUserId={currentUserId}
            />
          ))}
        </div>
      )}
    </div>
  );
}
