import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Inbox, ArrowRight, FileText, ShieldAlert, MessageCircle, Loader2, UserPlus } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { useNavigate } from "react-router-dom";
import { formatDistanceToNow } from "date-fns";

const sourceIcons: Record<string, typeof FileText> = {
  public_form: FileText,
  violation_response: ShieldAlert,
  client_request: MessageCircle,
  homeowner_ticket: MessageCircle,
  registration_request: UserPlus,
};

const sourceLabels: Record<string, string> = {
  public_form: "Form",
  violation_response: "Violation",
  client_request: "Request",
  homeowner_ticket: "Ticket",
  registration_request: "Registration",
};

const statusStyles: Record<string, string> = {
  new: "cc-badge-danger",
  in_progress: "cc-badge-warning",
  resolved: "cc-badge-success",
  archived: "cc-badge-neutral",
};

interface InboxItem {
  id: string;
  source_type: string;
  title: string;
  submitter_name: string | null;
  submitter_email: string | null;
  status: string;
  created_at: string;
}

export function FormInboxCard() {
  const [items, setItems] = useState<InboxItem[]>([]);
  const [newCount, setNewCount] = useState(0);
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();

  useEffect(() => {
    const fetchItems = async () => {
      const [{ data, error }, { count }] = await Promise.all([
        supabase
          .from("form_inbox")
          .select("id, source_type, title, submitter_name, submitter_email, status, created_at")
          .neq("status", "archived")
          .order("created_at", { ascending: false })
          .limit(3),
        supabase
          .from("form_inbox")
          .select("*", { count: "exact", head: true })
          .eq("status", "new"),
      ]);

      if (!error && data) setItems(data);
      setNewCount(count || 0);
      setLoading(false);
    };

    fetchItems();

    const channel = supabase
      .channel("form-inbox-dashboard")
      .on("postgres_changes", { event: "*", schema: "public", table: "form_inbox" }, () => {
        fetchItems();
      })
      .subscribe();

    return () => { supabase.removeChannel(channel); };
  }, []);

  return (
    <Card className="border shadow-sm">
      <CardHeader className="pb-2 px-4 pt-4">
        <div className="flex items-center justify-between">
          <div>
            <CardTitle className="text-[15px] font-semibold flex items-center gap-2">
              <Inbox className="h-4 w-4 text-primary" /> Form Inbox
              {newCount > 0 && (
                <Badge variant="destructive" className="text-2xs px-1.5 py-0 h-4 min-w-4 flex items-center justify-center">
                  {newCount}
                </Badge>
              )}
            </CardTitle>
            <CardDescription className="text-[12px]">Submissions & responses</CardDescription>
          </div>
          <Button
            variant="ghost"
            size="sm"
            className="text-[12px] h-7 gap-1 text-primary"
            onClick={() => navigate("/dashboard/form-inbox")}
          >
            View all <ArrowRight className="h-3 w-3" />
          </Button>
        </div>
      </CardHeader>
      <CardContent className="px-0 pb-0">
        {loading ? (
          <div className="flex items-center justify-center py-8">
            <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
          </div>
        ) : items.length === 0 ? (
          <div className="text-center py-8 px-4">
            <Inbox className="h-6 w-6 text-muted-foreground/20 mx-auto mb-2" />
            <p className="text-[13px] text-muted-foreground">No pending items</p>
          </div>
        ) : (
          <div className="divide-y divide-border">
            {items.map((item) => {
              const Icon = sourceIcons[item.source_type] || FileText;
              return (
                <div
                  key={item.id}
                  className="flex items-center gap-3 px-4 py-2.5 hover:bg-muted/50 transition-colors cursor-pointer"
                  onClick={() => navigate("/dashboard/form-inbox")}
                >
                  <div className="h-7 w-7 rounded-full bg-primary/10 flex items-center justify-center shrink-0">
                    <Icon className="h-3.5 w-3.5 text-primary" />
                  </div>
                  <div className="min-w-0 flex-1">
                    <p className="text-[13px] font-medium text-foreground truncate">{item.title}</p>
                    <div className="flex items-center gap-2 mt-0.5">
                      <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-2xs font-medium border ${statusStyles[item.status] || "cc-badge-neutral"}`}>
                        {item.status === "in_progress" ? "In Progress" : item.status.charAt(0).toUpperCase() + item.status.slice(1)}
                      </span>
                      <span className="text-2xs text-muted-foreground">
                        {item.submitter_name || item.submitter_email || "Anonymous"} · {formatDistanceToNow(new Date(item.created_at), { addSuffix: true })}
                      </span>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </CardContent>
    </Card>
  );
}
