import { useEffect, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/contexts/AuthContext";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Loader2, Megaphone, Plus, Send, X } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { formatDateEST } from "@/lib/timezoneUtils";

interface Association { id: string; name: string }
interface StatusUpdate {
  id: string;
  title: string;
  content: string | null;
  created_at: string;
  association_id: string;
  associations?: { name: string } | null;
}

export default function StatusUpdatesWidget() {
  const { user } = useAuth();
  const { toast } = useToast();
  const [associations, setAssociations] = useState<Association[]>([]);
  const [updates, setUpdates] = useState<StatusUpdate[]>([]);
  const [loading, setLoading] = useState(true);
  const [composing, setComposing] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [associationId, setAssociationId] = useState("");
  const [title, setTitle] = useState("");
  const [content, setContent] = useState("");

  const loadData = async () => {
    setLoading(true);
    const [{ data: assocs }, { data: ups }] = await Promise.all([
      supabase.from("associations").select("id, name").eq("status", "active").order("name"),
      supabase
        .from("status_updates")
        .select("id, title, content, created_at, association_id, associations(name)")
        .order("created_at", { ascending: false })
        .limit(5),
    ]);
    setAssociations((assocs as Association[]) || []);
    setUpdates((ups as any) || []);
    setLoading(false);
  };

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

  const reset = () => {
    setTitle(""); setContent(""); setAssociationId(""); setComposing(false);
  };

  const handleSubmit = async () => {
    if (!title.trim()) {
      toast({ variant: "destructive", title: "Title required" });
      return;
    }
    if (!associationId) {
      toast({ variant: "destructive", title: "Select an association" });
      return;
    }
    setSubmitting(true);
    try {
      const { error } = await supabase.from("status_updates").insert({
        title: title.trim(),
        content: content.trim() || null,
        association_id: associationId,
        created_by: user?.id ?? null,
      });
      if (error) throw error;
      toast({ title: "Status update posted" });
      reset();
      await loadData();
    } catch (err: any) {
      toast({ variant: "destructive", title: "Failed to post", description: err.message });
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="flex h-full flex-col p-4">
      <div className="mb-3 flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Megaphone className="h-4 w-4 text-primary" />
          <h3 className="text-sm font-semibold text-foreground">Status Updates</h3>
        </div>
        {!composing ? (
          <Button size="sm" variant="outline" className="h-7 text-xs" onClick={() => setComposing(true)}>
            <Plus className="mr-1 h-3 w-3" /> New
          </Button>
        ) : (
          <Button size="sm" variant="ghost" className="h-7 text-xs" onClick={reset}>
            <X className="h-3.5 w-3.5" />
          </Button>
        )}
      </div>

      {composing && (
        <div className="mb-3 space-y-2 rounded-lg border bg-muted/30 p-3">
          <Select value={associationId} onValueChange={setAssociationId}>
            <SelectTrigger className="h-8 text-xs">
              <SelectValue placeholder="Select association" />
            </SelectTrigger>
            <SelectContent>
              {associations.map((a) => (
                <SelectItem key={a.id} value={a.id} className="text-xs">{a.name}</SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Input
            placeholder="Title"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            className="h-8 text-xs"
          />
          <Textarea
            placeholder="Update details (optional)"
            value={content}
            onChange={(e) => setContent(e.target.value)}
            rows={3}
            className="resize-none text-xs"
          />
          <Button size="sm" className="w-full h-8 text-xs" onClick={handleSubmit} disabled={submitting}>
            {submitting ? <Loader2 className="mr-1 h-3 w-3 animate-spin" /> : <Send className="mr-1 h-3 w-3" />}
            Post Update
          </Button>
        </div>
      )}

      <div className="flex-1 overflow-y-auto space-y-2">
        {loading ? (
          <div className="flex justify-center py-6">
            <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
          </div>
        ) : updates.length === 0 ? (
          <p className="py-6 text-center text-xs text-muted-foreground">No status updates yet</p>
        ) : (
          updates.map((u) => (
            <div key={u.id} className="rounded-lg border bg-card p-2.5">
              <div className="flex items-start justify-between gap-2">
                <p className="text-xs font-semibold text-foreground line-clamp-1">{u.title}</p>
                <Badge variant="outline" className="text-2xs shrink-0">
                  {u.associations?.name ?? "—"}
                </Badge>
              </div>
              {u.content && (
                <p className="mt-1 text-2xs text-muted-foreground line-clamp-2">
                  {(() => {
                    const doc = new DOMParser().parseFromString(u.content, "text/html");
                    return (doc.body.textContent || "").replace(/\s+/g, " ").trim();
                  })()}
                </p>
              )}
              <p className="mt-1 text-2xs text-muted-foreground">{formatDateEST(u.created_at)}</p>
            </div>
          ))
        )}
      </div>
    </div>
  );
}
